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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(inventory): flip batch-split identity — parent keeps its id, child departs (#1328)
Sid99641b7a653b
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex eab6222e10..5b41cb1720 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -613,3 +613,13 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** When adding a reference column to an audited table, either give it a real FK constraint (registry/hops then cover it automatically) or declare a per-column `snapshotFields` override on that table's audit config. For targets whose display value lives on another table, use `fkDisplayHops` (two-stage batched lookup). Resolution precedence is override > hop > registry; hops and registry must stay disjoint, and overrides must not target hop tables — both invariants are enforced by tests in `fk-snapshots.test.ts`. Snapshots are frozen at write time: config changes never backfill existing audit rows.**Applies to:** `packages/database/src/audit.config.ts` (`fkDisplayRegistry`, `fkDisplayHops`, `snapshotFields`), `packages/jobs/src/inngest/functions/events/fk-snapshots.ts` + `audit.ts`, and any migration adding reference columns to tables listed in `auditConfig.entities`.++## A flip/refactor must not add ledger rows to a code path that deliberately posted none++**Context:** Implementing the batch-split identity flip (spec `2026-08-04-batch-split-identity-flip.md`) via a shared `buildBatchSplitRecords` builder that emits a 2-row net-zero `Batch Split` `itemLedger` pair. Wired it into all five split writers uniformly, including `post-shipment`'s Purchase-Order-sourced block.++**Problem:** The pre-flip `post-shipment` PO block (subcontract / outside-processing shipments against a PO) wrote split **genealogy only** — `trackedEntity` + `trackedActivity` + output rows — and posted **zero** `itemLedger` rows, unlike the SO block which posts a `Sales Shipment` negative-adjustment the split pair complements. Mechanically wiring the builder's ledger inserts into the PO block introduced a −q on the parent that nothing in that path offsets, changing inventory behavior for subcontract shipments with unclear valuation consequences. Own-file `deno check` and typecheck stay green (it compiles fine), so only reading the ORIGINAL of each branch caught it. Self-review found it; the browser e2e never would have (no shippable PO fixture).++**Rule:** When applying a uniform transformation across N sibling branches, diff each branch against its own pre-change body — don't assume they were symmetric. A branch that posted no ledger, sent no email, fired no event before your change must still post/send/fire nothing after, unless the spec explicitly says otherwise. "It typechecks and the other four branches do it" is not evidence the fifth should. Preserve per-branch behavior; the flip's mandate was which id departs, not to newly introduce inventory movements.++**Applies to:** `packages/database/supabase/functions/post-shipment/index.ts` (PO vs SO split blocks); any refactor threading a shared record-builder through multiple writers (`post-*`, `issue`, sync handlers).diff --git a/.ai/plans/2026-08-04-batch-split-identity-flip.md b/.ai/plans/2026-08-04-batch-split-identity-flip.mdnew file mode 100644index 0000000000..18793a7671--- /dev/null+++ b/.ai/plans/2026-08-04-batch-split-identity-flip.md@@ -0,0 +1,728 @@+# Batch Split Identity Flip — implementation plan++**Spec:** .ai/specs/2026-08-04-batch-split-identity-flip.md+**Research:** .ai/research/batch-split-identity.md+**Branch:** feat/batch-split-identity-flip (PR B) — Tasks 1–3 ship first from fix/split-display-fixes (PR A)++Convention being implemented (memorize before any task): on a partial batch draw of+quantity `q` from `parent`, the parent KEEPS its id and is decremented by `q`; a NEW+`child` entity (same `readableId`, attrs cloned + `"Split From Entity ID": parent.id`)+holds `q` and is what departs (lineside / other bin / consumed / shipped). Split activity:+input parent@q, output child@q — never a survivor self-loop. Ledger: exactly two net-zero+`Batch Split` rows (−q parent, +q child) at the parent's resolved bin. The OLD convention+(original departs, new = remainder, `"Split Entity ID"` tagged on the survivor) must not+survive anywhere. Serial paths never split — do not touch `case "serial"` /+`unpickSerial`. No DB migration exists in this plan; nothing schema-related changes.++## Progress+- [x] Task 1: Fix activity-feed tracking labels + hide Batch Split bookkeeping rows+- [x] Task 2: Group Storage Units rows by (lot, storage unit)+- [x] Task 3: Filter split self-loops in traceability sidebar/graph + fix ExpiryTracePopover copy+- [x] Task 4: Add "Split From Entity ID" to the shared attribute types+- [x] Task 5: Pure batch-split/merge record builders + Deno tests+- [x] Task 6: Flip post-picking batch pick+- [x] Task 7: Rework post-picking unpickBatch (allocation-qty undo + merge-back)+- [x] Task 8: Merge-on-return in the post-picking return sweep+- [x] Task 9: Flip issue trackedEntitiesToOperation+- [x] Task 10: Flip issue maintenanceDispatchTrackedEntities+- [x] Task 11: Flip post-stock-transfer batch + unpick merge-back redetect+- [x] Task 12: Flip post-shipment SO + PO splits, retained-parent label ids+- [x] Task 13: Align quality-disposition subdivideBatchEntity+- [x] Task 14: Reader filters — root-entity queries + serial assignment + newest-live audit+ (audit log: issue:1165 filters by Operation marker, acts on caller id — left; MES+ getTrackedEntitiesByJobMakeMethodIds + JobsTable map make-method→readableId, invariant+ across fragments — left; MES/ERP getTrackedEntitiesByMakeMethodId consumers select via+ isSerialEntityIncompleteForOperation which already guards status !== Consumed — left;+ JobHeader sums Available rows — left; issue new.tsx + association.new.tsx link ALL+ entities — left; print-job resolvers Operation case renders all rows — left. Adjacent+ observation, NOT in plan scope: print-job resolver "Shipment" case selects by the+ Shipment attribute, which post-flip lands on consumed children — flagged in run report.)+- [x] Task 15: MES — issue confirmation, Convert/Scrap retarget, scan mapping, picked-lots semantics+ (Convert/Scrap were reachable ONLY from the deleted split screen → deleted per the+ plan's dead-code clause. Scan mapping matches by entity id; parent→child resolution+ added via pickedAllocation.splitFromEntityId — active when picked-lots data is loaded,+ i.e. the process view with a picking allocation.)+- [x] Task 16: ERP routes — label print retargeting (stock transfer, shipment, maintenance)+- [x] Task 17: Validation gates (lint ✓, scoped typechecks ×4 ✓, deno tests 12+5 ✓, lingui extract + 24 translations filled ✓)+- [~] Task 18: Browser verification — PARTIAL but core writers PROVEN e2e (2026-08-05,+ real Chrome via chrome MCP against erp.batch-split-identity-flip.dev). Seeded lot 2026/09+ = 8 @ BIN-A via the real post-inventory-adjustment edge fn; added BATCH-TEST-01 (Pull+ from Inventory) to job J000005, generated picking list PL000004, and exercised the live+ edge functions:+ • PICK 6-of-8 (post-picking `case "batch"`, Task 6): shelf entity kept its id decremented+ 8→2 (no `Split Entity ID` on it), new child qty 6 carries `Split From Entity ID`=parent,+ ledger 2-row Batch Split nets zero + Transfer pair books on the CHILD, allocation →+ CHILD, Split genealogy input parent@6 → ONE output child@6. Every invariant held.+ • UNPICK (post-picking `unpickBatch`, Task 7): shelf restored 2→8, child drained to 0/+ Consumed, Split activity deleted, allocation deleted, on-hand reconciles. Clean merge-back.+ Evidence + queries recorded in `.ai/playbooks/batch-split-identity-flip.md`. Earlier+ blocker (in-app pane's portaled combobox) was resolved by using the real Chrome MCP+ (1:1 coords). NOT yet exercised live: issue partial-consume (Task 9), complete→merge+ sweep (Task 8), stock transfer (Task 11 — new wizard is demand-driven, needs a WC-1+ demand), shipment (Task 12 — no SO), NCR disposition (Task 13). Those share the same+ verified `buildBatchSplitRecords` builder; cover per the playbook checklist.++## Dependencies+- Tasks 1–3 independent of everything (PR A; ship first).+- Task 4 → Task 5 → Tasks 6–13 (writers; 6–13 mutually independent, but 7 and 8 edit the+ same file as 6 — run 6 → 7 → 8 sequentially; 9 → 10 same file sequentially).+- Tasks 14–16 depend only on Task 4; parallel to writers, but land in the same PR B.+- Task 17 after all code tasks. Task 18 last (needs the user's running dev stack).++---++## Task 1: Fix activity-feed tracking labels + hide Batch Split bookkeeping rows++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx` — label+ source + row filtering+- Modify: `apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx` — thread+ `itemTrackingType`++**Steps:**+1. In `InventoryActivity.tsx`, six sites build `Math.abs(ledgerRecord.quantity) > 1 ?+ "batch" : "serial"` (≈ lines 81, 98, 200, 244, 297, 307). Replace the ternary with a+ `trackingNoun` derived from a new `itemTrackingType` prop: `"Serial"` → `"serial"`,+ `"Batch"` → `"batch"`, anything else → omit the tracked-entity clause entirely.+ Thread the prop through the component(s) in this file down to `getActivityText`+ (convert `getActivityText` to take `(ledgerRecord, trackingNoun)`).+2. In the route `$itemId.activity.tsx`: read the loader; if item data with+ `itemTrackingType` is already loaded, pass it down; otherwise fetch it in the loader+ via the items service `getItem(client, itemId)` pattern used by the sibling+ quantities routes and pass `item.itemTrackingType`. If neither is feasible without+ new service code, STOP and report — do not guess a tracking type client-side.+3. In the row-collapsing/reducer stage of `InventoryActivity.tsx` (the+ `CollapsedItemLedger` reduce near the top), drop rows with+ `documentType === "Batch Split"` from the feed entirely — they are internal net-zero+ bookkeeping; the Transfer/Consumption rows tell the real story. Keep them in any+ raw ledger table views (this file only).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0, no errors in InventoryActivity.tsx or $itemId.activity.tsx+rg -n 'quantity\) > 1 \? "batch" : "serial"' apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx+# Expected: no matches+```++**Out of scope:** StockMovementsTable (raw ledger view keeps Batch Split rows), any+locale/.po updates beyond what lingui extract picks up in Task 17.++## Task 2: Group Storage Units rows by (lot, storage unit)++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx`+- Copy from (precedent): `apps/erp/app/modules/inventory/ui/Valuation/InventoryValuationWorkbench.tsx`+ — the `expandedIds: Set<string>` + flattened-rows `useMemo` expand/collapse pattern++**Steps:**+1. Rows arrive as `itemStorageUnitQuantities: ItemStorageUnitQuantities[]` (one row per+ (storage unit, tracked entity)). Build a `useMemo` grouping by key+ `${storageUnitId}::${readableId}` (fall back to the tracked entity id when+ `readableId` is null so untracked/unnumbered rows stay singletons).+2. Groups with one member render exactly as today (zero visual change). Groups with >1:+ render a group row — storage unit name, summed quantity, the shared Tracking ID chip,+ earliest expiration of the members, a `×N` count, and a chevron `IconButton`+ toggling the key in an `expandedIds` set (precedent file's pattern). When expanded,+ member rows render beneath exactly as today (existing per-entity actions — edit,+ label print, adjustment menu — stay on member rows ONLY).+3. Keep sort: storage unit, then `readableId`, then existing order within group.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** the picker components (`TrackedEntityPicker`), the quantities list+page, any service/RPC change — grouping is purely presentational in this component.++## Task 3: Filter split self-loops in traceability sidebar/graph + ExpiryTracePopover copy++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx` —+ self-loop classification (useMemo at ~line 77)+- Modify: `apps/erp/app/modules/inventory/lineage.server.ts` — `toGraphData` (~line 448)+- Modify: `apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx` (~218–230)++**Steps:**+1. Sidebar: in the `useMemo`, precompute for the selected entity the set of activity ids+ where it appears in BOTH `payload.inputs` and `payload.outputs` (self-loop = historical+ split survivor). For those activities: skip the `producedBy` push and the+ `consumedBy` push, and instead push into a new `splits: RelatedActivity[]` list+ (quantity = the output-row quantity, i.e. what the entity kept). Render a "Splits"+ section between "Produced by" and "Consumed by" using the same `Section` component,+ row label unchanged (activity headline), so a receipt-originated lot no longer shows+ "Produced by Split" / "Consumed by Split".+2. Graph: in `toGraphData`, drop OUTPUT links whose `(trackedActivityId, trackedEntityId)`+ pair also exists in `payload.inputs` (the survivor's output edge). Keep the input edge.+3. `ExpiryTracePopover.tsx`: the "Split from another batch — Parent {id}" block currently+ keys off the legacy `"Split Entity ID"` attribute with inverted meaning. Change it to+ read `"Split From Entity ID"` (correct parent pointer, Task 4 type). For legacy+ entities that only have `"Split Entity ID"`, suppress the block (it names the CHILD,+ not the parent — showing it as "Parent" is wrong).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** strict-RPC SQL (unchanged), EntityNode labels, worker/ lineage code.++## Task 4: Add "Split From Entity ID" to the shared attribute types++**Depends on:** none+**Files:**+- Modify: `packages/utils/src/types.ts` (~line 51, `TrackedEntityAttributes`)+- Modify: `packages/database/supabase/functions/lib/utils.ts` (~line 15, same interface)++**Steps:**+1. Add `"Split From Entity ID"?: string;` beside the existing+ `"Split Entity ID"?: string;` in both declarations. Do NOT remove the legacy key+ (historical rows carry it).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/utils+# Expected: exit 0+rg -n '"Split From Entity ID"' packages/utils/src/types.ts packages/database/supabase/functions/lib/utils.ts+# Expected: one match in each file+```++**Out of scope:** removing `"Split Entity ID"` (still written on ACTIVITY attributes and+present on historical entities).++## Task 5: Pure batch-split/merge record builders + Deno tests++**Depends on:** Task 4+**Files:**+- Create: `packages/database/supabase/functions/shared/batch-split.ts`+- Create: `packages/database/supabase/functions/shared/batch-split.test.ts`+- Copy from (precedent): `packages/database/supabase/functions/issue/resolve-tracked-entity-bin.ts`+ + its colocated `.test.ts` (pure module + `deno test`, no DB imports)++**Steps:**+1. `batch-split.ts` exports two pure functions (NO imports from `../lib/database.ts` —+ node code will import this file too; see lesson "Node-side re-exports from the Deno+ functions tree must dodge lib/database.ts"):+ ```typescript+ export type BatchSplitInput = {+ parent: { id: string; readableId: string | null; quantity: number;+ sourceDocument: string | null; sourceDocumentId: string | null;+ sourceDocumentReadableId: string | null; itemId: string | null;+ expirationDate: string | null; attributes: Record<string, unknown> | null };+ drawQuantity: number; // q, must be > 0 and < parent.quantity+ childId: string; // caller-supplied nanoid+ splitActivityId: string; // caller-supplied nanoid+ activitySourceDocument: string; // e.g. "Picking List"+ activitySourceDocumentId: string;+ bin: { storageUnitId: string | null; locationId: string | null };+ itemLedgerItemId: string; // itemId for the ledger rows+ companyId: string; userId: string; postingDate: string;+ childStatus: "Available" | "Consumed";+ extraChildAttributes?: Record<string, unknown>;+ };+ export function buildBatchSplitRecords(input: BatchSplitInput): {+ childEntityInsert: {...}; // quantity = q, attrs = parent attrs minus+ // "Split Entity ID"/"Split From Entity ID"+ // + { "Split From Entity ID": parent.id }+ // + extraChildAttributes+ parentUpdate: { quantity: number }; // parent.quantity - q (attrs untouched)+ activityInsert: {...}; // type "Split", attributes { "Original Quantity":+ // parent.quantity, "Drawn Quantity": q,+ // "Remaining Quantity": parent.quantity - q,+ // "Split Entity ID": childId }+ activityInputInsert: {...}; // parent @ q+ activityOutputInsert: {...}; // child @ q (exactly ONE output — no self-loop)+ ledgerInserts: [{...}, {...}]; // −q on parent, +q on child; entryType+ // "Negative Adjmt."/"Positive Adjmt.",+ // documentType "Batch Split", documentId+ // splitActivityId, at input.bin+ };+ export function buildMergeRecords(input: { child: { id: string; quantity: number };+ parent: { id: string; quantity: number }; mergeQuantity: number;+ mergeActivityId: string; companyId: string; userId: string }): {+ activityInsert: {...}; // type "Merge"+ activityInputInsert: {...}; // child @ mergeQuantity+ activityOutputInsert: {...}; // parent @ mergeQuantity+ parentUpdate: { quantity: number }; // parent.quantity + mergeQuantity+ childUpdate: { quantity: number; status?: "Consumed" }; // Consumed when → 0+ };+ ```+ Throw on `drawQuantity <= 0`, `drawQuantity >= parent.quantity`, or+ `mergeQuantity > child.quantity` — the callers' split gates should make these+ unreachable; loud beats silent.+2. Tests assert: child (not parent) carries `"Split From Entity ID"`; parent update only+ decrements; exactly one activity output and it is the child; ledger rows net to zero+ with −q on parent / +q on child; merge Consumed-at-zero behavior; the throw cases.++**Verify:**+```bash+deno test packages/database/supabase/functions/shared/batch-split.test.ts+# Expected: all tests pass (ok | N passed)+```++**Out of scope:** wiring into any writer (Tasks 6–13); itemLedger typing beyond what the+writers already use (mirror the `ItemLedgerInsert` field shape they build inline).++## Task 6: Flip post-picking batch pick++**Depends on:** Task 5+**Files:**+- Modify: `packages/database/supabase/functions/post-picking/index.ts` — `case "batch"`+ (~372–634)++**Steps:**+1. In the split branch (`entityQuantity !== transferQuantity`, ~404): replace the inline+ entity/activity/ledger writes (~407–529) with `buildBatchSplitRecords` (import from+ `../shared/batch-split.ts`): parent = the loaded `trackedEntity`, `drawQuantity =+ transferQuantity`, `childStatus: "Available"`, activity source `"Picking List"` /+ `pickingListId`, bin = `{ storageUnitId: fromStorageUnitId, locationId }`. Insert/+ update in the same trx order: activity → child entity → input/output → parent update →+ ledger rows. Set `splitEntityId = childId` (response meaning now = departing child).+2. Everything after the split must reference the CHILD when a split occurred, else the+ original entity: introduce `const pickedEntityId = didSplit ? childId :+ trackedEntityId;` and use it for: the Pick `trackedActivityInput` (~551–560), BOTH+ Transfer ledger rows (~563–590), and the `pickingListLineTrackedEntity` upsert+ (~609–629).+3. Do not modify `case "serial"`, `case "inventory"`, `case "unpickInventory"`.++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/post-picking/index.ts 2>&1 | rg "post-picking/index.ts" ; echo "exit:$?"+# Expected: exit:1 (no own-file errors; pre-existing lib noise is fine per lessons.md+# "gate on own-file error deltas") — record the error count before your change and+# assert it did not grow.+rg -n "pickedEntityId" packages/database/supabase/functions/post-picking/index.ts | head -5+# Expected: matches in the Pick input, Transfer rows, and allocation upsert+```++**Out of scope:** unpick and return cases (Tasks 7–8), label printing (picking still+prints nothing — spec decision).++## Task 7: Rework post-picking unpickBatch (allocation-qty undo + merge-back)++**Depends on:** Task 6+**Files:**+- Modify: `packages/database/supabase/functions/post-picking/index.ts` —+ `case "unpickSerial"/"unpickBatch"` (~636–743)++**Steps:**+1. Split the shared case: keep `unpickSerial` behavior byte-identical (qty is always 1);+ give `unpickBatch` its own branch.+2. `unpickBatch` for entity id E (the id recorded in `pickingListLineTrackedEntity` —+ callers pass what they rendered from allocations):+ a. Load the allocation row (`pickingListLineId`, `trackedEntityId = E`); unpick+ quantity `q = allocation.quantityPicked`. STOP and report if no allocation row —+ do not fall back to `trackedEntity.quantity`.+ b. Reverse the Transfer pair for E: −q @ `line.toStorageUnitId`, +q @+ `line.storageUnitId` (as today, but with `q`, not entity quantity).+ c. Delete the Pick activity for E on this picking list (existing query, ~664–677).+ d. If `E.attributes["Split From Entity ID"]` names a parent P that exists and+ `P.readableId === E.readableId`: merge-back undo — `P.quantity += q`;+ `E.quantity -= q`, set `E.status = 'Consumed'` when it reaches 0; two ledger rows+ `Batch Split` documentType at the SOURCE bin (−q on E, +q on P) so the original+ split pair nets out; DELETE the Split activity that created E (find it via+ `trackedActivity.type = 'Split'` AND `attributes->>'Split Entity ID' = E.id` AND+ `companyId`) and its input/output rows. Do NOT delete E's entity row.+ If P is missing/mismatched (legacy pre-flip allocation), skip the merge — E simply+ returns to the source bin as its own entity (today's behavior).+ e. Keep the existing `quantityPicked` decrement, line status reset, allocation-row+ delete, and `restoreJobMaterialSource` call.++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/post-picking/index.ts 2>&1 | rg -c "post-picking/index.ts"+# Expected: own-file error count unchanged from Task 6 baseline+rg -n "quantityPicked" packages/database/supabase/functions/post-picking/index.ts | rg -n "unpick" -A0 | head -3+# Expected: unpickBatch derives q from the allocation row+```++**Out of scope:** `unpickInventory`, stock-transfer unpick (Task 11).++## Task 8: Merge-on-return in the post-picking return sweep++**Depends on:** Task 7+**Files:**+- Modify: `packages/database/supabase/functions/post-picking/index.ts` —+ `returnTrackedAllocationRemainder` (~944–1109)++**Steps:**+1. The lineage walk (~998–1058) stays as-is (seed + forward descendants; still correct —+ spec §returns). For each lineage entity `E` with lineside on-hand `r > 0` about to be+ transferred back to `sourceBin`:+ a. Resolve `P` from `E.attributes["Split From Entity ID"]` (may be absent on legacy+ rows). Load P scoped by `companyId`.+ b. Merge when P exists AND `P.status = 'Available'` AND `P.readableId ===+ E.readableId` AND `resolveTrackedEntityBin`-style net on-hand places P at+ `sourceBin`: use `buildMergeRecords` — Transfer ledger −r on E @ lineside, +r on+ P @ sourceBin (keep the existing Transfer entryType/documentType the sweep uses+ today), `P.quantity += r`, `E.quantity −= r` (Consumed at 0), insert the Merge+ activity + input(E@r)/output(P@r).+ c. Otherwise fall back to today's behavior verbatim (transfer E back, E stays+ Available at sourceBin).+2. Keep the allocation decrement/delete keyed on the allocated id (~1066–1095) unchanged.+3. Do not touch `returnUntrackedMaterialRemainder` or `maybeRestoreJobMaterialSource`.++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/post-picking/index.ts 2>&1 | rg -c "post-picking/index.ts"+# Expected: own-file error count unchanged+rg -n '"Merge"' packages/database/supabase/functions/post-picking/index.ts+# Expected: one trackedActivity type "Merge" insert site+```++**Out of scope:** operation/job sweep orchestration and policy gates (untouched — spec+2026-08-04-picked-material-return-timing owns them).++## Task 9: Flip issue trackedEntitiesToOperation++**Depends on:** Task 5+**Files:**+- Modify: `packages/database/supabase/functions/issue/index.ts` —+ `case "trackedEntitiesToOperation"` split block (~2203–2400)++**Steps:**+1. Replace the inline split writes (~2224–2355) with `buildBatchSplitRecords`: parent =+ the loaded entity, `drawQuantity = quantity` (the consumed amount), `childStatus:+ "Consumed"` is NOT set here — create the child `"Available"` and let step 2 flip it+ (mirrors the existing two-phase shape), activity source `"Job Material"` /+ `actualMaterialId`, bin from `resolveTrackedEntityBin(itemLedgers, trackedEntityId)`,+ `extraChildAttributes` = the per-consume keys the case adds today (Job Operation+ Step / Unit when present). Respect the existing `methodType !== "Make to Order"`+ guard: MTO skips ONLY the ledger inserts (entity/activity writes still happen).+2. This is the atomicity-critical edit (spec risk #1): in the SAME edit, repoint to the+ CHILD id — `splitEntities.push({originalId: trackedEntityId, newId: childId, ...,+ quantity: consumed qty (was remainder)})`, the `status: "Consumed"` update+ (~2359–2365), the Consume `trackedActivityInput` (~2367–2373), and the Consumption+ ledger row (~2376–2387). The parent is touched ONLY by the builder's quantity+ decrement. Grep the whole case afterward for remaining uses of the original id and+ justify each survivor (the parent decrement and the `splitEntities.originalId` are+ the only legitimate ones).+3. `splitEntities[].quantity` consumers (MES modal, Task 15) will read it as the+ consumed child quantity + compute remaining from parent — update the pushed object to+ `{ originalId, newId, readableId, quantity: <consumed q>, remainingQuantity:+ <parent quantity after decrement> }`.++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/issue/index.ts 2>&1 | rg -c "issue/index.ts"+# Expected: own-file error count unchanged from pre-task baseline+rg -n 'set\(\{\s*$' -A3 packages/database/supabase/functions/issue/index.ts | rg -n '"Consumed"' | head -4+# Expected: the trackedEntitiesToOperation Consumed update targets the child id variable+```++**Out of scope:** `unconsumeTrackedEntities` (id passed by caller; semantics unchanged),+`jobOperationBatchComplete` / `jobOperationSerialComplete` (Task 14 audits their+selection filters only).++## Task 10: Flip issue maintenanceDispatchTrackedEntities++**Depends on:** Task 9+**Files:**+- Modify: `packages/database/supabase/functions/issue/index.ts` —+ `case "maintenanceDispatchTrackedEntities"` (~3231–3419)++**Steps:**+1. Same builder replacement as Task 9 (activity source `"Maintenance Dispatch Item"`).+ Replace this block's `itemLedgers.find(...)`-based bin with+ `resolveTrackedEntityBin` (aligns with Block A; lesson "actual bin" — the fix is+ in-scope here because this task's tests exercise the path).+2. Repoint to child: status Consumed, Consume input, `Maintenance Consumption` ledger,+ AND the `maintenanceDispatchItemTrackedEntity` junction insert (~3394–3400).+ `splitEntities` shape as in Task 9 step 3.++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/issue/index.ts 2>&1 | rg -c "issue/index.ts"+# Expected: own-file count unchanged+rg -n "maintenanceDispatchItemTrackedEntity" packages/database/supabase/functions/issue/index.ts+# Expected: junction insert references the child id variable+```++**Out of scope:** `maintenanceDispatchUnconsume` (caller-supplied id).++## Task 11: Flip post-stock-transfer batch + unpick merge-back redetect++**Depends on:** Task 5+**Files:**+- Modify: `packages/database/supabase/functions/post-stock-transfer/index.ts` —+ `case "batch"` (~406–683) and `case "unpickBatch"` (~815–1058)++**Steps:**+1. `case "batch"`: builder replacement (source `"Stock Transfer"` / `stockTransferId`,+ bin `fromStorageUnitId`, child `"Available"`). Departing side = child: the Transfer+ activity input, BOTH Transfer ledger rows (from → `toStorageUnitId`), and+ `stockTransferLine.trackedEntityId` update (~669–680) all use the child id.+ `splitEntityId` response = child id.+2. `case "unpickBatch"` for entity id E (from the line):+ - New detection: E is a split child iff `E.attributes["Split From Entity ID"]` is+ set. Legacy detection (pre-flip rows): `E.attributes["Split Entity ID"]` set (E was+ the departed original; its pointer names the remainder). Handle BOTH:+ - New shape: P = parent from the pointer; merge E fully back into P (P.quantity +=+ E.quantity, E → Consumed @ 0), ledger rows as the branch writes today but with+ roles P=receiver / E=drained; delete the Split activity found via+ `type='Split'` AND `attributes->>'Split Entity ID' = E.id` AND+ `sourceDocumentId = stockTransferId` AND `companyId` — scoped, fixing the+ pre-existing multi-line bug at ~884.+ - Legacy shape: keep the existing merge code path, but scope its Split-activity+ query the same way (`attributes->>'Split Entity ID' = <remainder id>`).+ - No pointer at all → existing plain reverse-transfer branch unchanged.++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/post-stock-transfer/index.ts 2>&1 | rg -c "post-stock-transfer/index.ts"+# Expected: own-file count unchanged+rg -n "Split From Entity ID" packages/database/supabase/functions/post-stock-transfer/index.ts | head -3+# Expected: matches in both the batch case (via builder import) and unpickBatch detection+```++**Out of scope:** `case "serial"` / `unpickSerial`, destination-bin merging (spec: none+in v1).++## Task 12: Flip post-shipment SO + PO splits, retained-parent label ids++**Depends on:** Task 5+**Files:**+- Modify: `packages/database/supabase/functions/post-shipment/index.ts` — SO split block+ (~705–1065) and PO split block (~1418–1652)++**Steps:**+1. Both blocks are near-verbatim twins — apply identical edits to each:+ a. The `trackedEntitySplits`/`trackedEntityUpdates` maps: parent is now only+ decremented (builder handles it); the SHIPPED portion becomes the child with+ `status: "Consumed"`, `quantity: shippedQuantity`, and the shipment attributes+ (`Shipment`, `Shipment Line`, `Shipment Line Index`) moved onto the CHILD via+ `extraChildAttributes`. The parent keeps its attributes and gains nothing —+ delete the dead `updatedAttributesObj` code (~944–957 / ~1603–1616) and the+ `"Split Entity ID"`-on-parent write; the retained parent must NOT carry shipment+ attrs (this was the old code's dead intent — make it real).+ b. Shipment activity `trackedActivityInput` rows reference the child for split lots+ (unchanged full-lot shipments keep the original id).+ c. Ledger: builder's 2-row Batch Split pair at the shipment line's bin, then the+ existing shipment ledger rows book against the child.+ d. `splitEntityIds` response: push the RETAINED PARENT ids (label semantics — spec).+2. Void branches untouched (they contain no split logic).++**Verify:**+```bash+deno check --no-lock packages/database/supabase/functions/post-shipment/index.ts 2>&1 | rg -c "post-shipment/index.ts"+# Expected: own-file count unchanged+rg -n "updatedAttributesObj" packages/database/supabase/functions/post-shipment/index.ts+# Expected: no matches (dead code removed)+```++**Out of scope:** `Outbound Transfer` case (no splits), void merge-back (pre-existing+asymmetry, unchanged).++## Task 13: Align quality-disposition subdivideBatchEntity++**Depends on:** Task 4 (types); builder import optional — this file is ERP app code+**Files:**+- Modify: `apps/erp/app/modules/quality/quality-disposition.server.ts` (~195–385)++**Steps:**+1. Identity polarity here is ALREADY post-flip (original keeps `keepQty`, new entity+ carries `moveQty`). Align the contract: stop writing `"Split Entity ID"` onto the+ original (~257–268); write `"Split From Entity ID": original.id` on the new entity;+ activity attributes keep `"Split Entity ID": newEntity.id`; edges become input+ original@moveQty → output newEntity@moveQty only (drop the survivor output);+ ledger becomes the 2-row pair (−moveQty original, +moveQty new).+2. Import `buildBatchSplitRecords` from+ `packages/database/supabase/functions/shared/batch-split.ts` via a relative import if+ the module resolves cleanly under the ERP tsconfig (it is pure, no Deno imports);+ if the import fails to typecheck for path/module-resolution reasons, mirror the+ record shapes inline and add a comment pinning it to `shared/batch-split.ts` — do+ NOT create a second divergent helper elsewhere.+3. Update this file's "keep in sync with issue" comment (~154–163) to reference the+ shared builder as the contract.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** disposition row logic, NCR flows beyond the split mechanics.++## Task 14: Reader filters — root-entity queries + serial assignment + newest-live audit++**Depends on:** Task 4+**Files:**+- Modify: `apps/erp/app/modules/production/production.service.ts` (~2249, ~2280)+- Modify: `packages/database/supabase/functions/assign-serial-numbers/index.ts` (~88–108)+- Audit/modify as needed: `packages/database/supabase/functions/issue/index.ts` (~1165–1179),+ `apps/mes/app/services/operations.service.ts` (~51, ~1151),+ `apps/erp/app/modules/inventory/inventory.service.ts` (~1367),+ `apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx` (~994),+ `apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx` (~104–116),+ `apps/erp/app/routes/x+/issue+/new.tsx` (~288),+ `apps/erp/app/routes/x+/issue+/$id.association.new.tsx` (~427),+ `packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts` (~157–161)++**Steps:**+1. `production.service.ts` both functions: alongside the existing+ `.is("attributes->>Split Entity ID", null)` add+ `.is("attributes->>Split From Entity ID", null)` (survivors carry neither key across+ both conventions — spec Design Decisions).+2. `assign-serial-numbers`: extend the seed exclusion the same way (exclude rows where+ EITHER pointer key is non-null) so `seeds.length === 1` holds post-flip.+3. Audit each listed "newest live" site: the selection of a make-method/job entity must+ land on the SURVIVOR via a status filter (`status != 'Consumed'` or equivalent), not+ `createdAt` recency (the flip makes the survivor the OLDER row). Where a site already+ filters by status AND that yields exactly one live row, leave it and note it in the+ task log; where it orders by `createdAt` without a status guard, add the status guard.+ If any site's semantics are genuinely "most recent activity" (not "the live lot"),+ STOP and report that site rather than changing it.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/jobs+# Expected: exit 0+rg -n "Split From Entity ID" apps/erp/app/modules/production/production.service.ts packages/database/supabase/functions/assign-serial-numbers/index.ts+# Expected: matches at both getTrackedEntit* filters and the seed filter+```++**Out of scope:** rewriting the traveler PDF routes (they consume the fixed service).++## Task 15: MES — issue confirmation, Convert/Scrap retarget, scan mapping, picked-lots semantics++**Depends on:** Tasks 4, 9 (response shape)+**Files:**+- Modify: `apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx`+ (~529–546, ~1041–1075, ~1117–1180, ~1960–1999, scan-tab resolution)+- Modify: `apps/mes/app/services/inventory.service.ts` —+ `getPickedTrackedEntitiesForMaterial` (~401–454)+- Modify: `apps/mes/app/routes/x+/issue-tracked-entity.tsx` (~78–116)++**Steps:**+1. `IssueMaterialModal`: delete the full-screen "Batch Split Occurred" state + its+ `PrintButton` (~1117–1155). On a successful issue with `splitEntities.length > 0`,+ close the modal as the no-split path does and fire ONE toast per split via the+ existing MES toast util: `` t`Issued ${quantity} of ${readableId} — ${remainingQuantity} remains` ``+ (fields from the Task 9 response shape). Keep `ConvertSplitModal`/`ScrapSplitModal`+ flows but retarget them to the surviving lineside entity: post-flip the leftover at+ lineside is the ORIGINAL allocated entity (`split.originalId`), not `newId` — update+ the `entity.newId` matches (~1970 and the Convert/Scrap wiring at ~1156–1180). If+ Convert/Scrap prove to be dead code paths only reachable from the deleted screen,+ delete them too and note it — do not leave unreachable UI.+2. Scan mapping: in the scan-tab resolution path of the modal, when a scanned entity id+ X is not itself allocated/at-lineside for this operation, look for an allocation row+ (in the already-loaded picked-lots data) whose entity has+ `attributes["Split From Entity ID"] === X`; if found, resolve the scan to that child.+ If the modal matches scans by `readableId` rather than entity id, verify the match+ still lands on the allocated lineside child and skip this step with a note.+3. `getPickedTrackedEntitiesForMaterial`: rewrite the docstring (~407–409) — allocated+ ids are now the departing children staged at lineside; behavior/query unchanged+ (allocation rows already point at the lineside entity post-Task-6).+4. `issue-tracked-entity.tsx`: remove the per-split `print-job` trigger (~103–112) and+ the printer resolution that only serves it (~86–101) if now unused. Consumed+ portions get no label (spec).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=mes+# Expected: exit 0+rg -n "Batch Split Occurred" apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx+# Expected: no matches+```++**Out of scope:** allocation.ts (no change — FIFO fix falls out of the writers),+IssueMaterialModal seeding/tab logic from spec 2026-07-24 (untouched).++## Task 16: ERP routes — label print retargeting (stock transfer, shipment, maintenance)++**Depends on:** Tasks 4, 11, 12+**Files:**+- Modify: `apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx` (~125–147)+- Modify: `apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx` (~193–214)+- Modify: `apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx` (~308–323)+- Modify: `apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx` (~61–72)+- Modify: `apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx` (~61–72)+- Modify: `apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx` (~105–119)++**Steps:**+1. Stock-transfer routes: `splitEntityId` is now the DEPARTING child. Print the `Entity`+ label for the child (it physically arrives at the destination bin) and keep the+ reprint for the parent (quantity changed) — i.e. the two print calls swap which id is+ "new label" vs "reprint". Resolve roles defensively from the entity's+ `"Split From Entity ID"` attribute rather than positionally (deploy-skew tolerance,+ spec risk table).+2. `$shipmentId.post.tsx`: `splitEntityIds` now carries RETAINED parent ids (Task 12) —+ the print loop needs no id change, only the `sourceDocument` switches from `"Split"`+ to `"Entity"` (these are existing entities being reprinted). Verify+ `packages/printing/src/registry.ts` accepts `Entity` for productLabel (it does — it+ is the standard source); leave the `Split` registry entry for history.+3. Shipment labels download routes: replace the `"Split Entity ID"`-based filter with:+ collect the shipment's tracking entities that carry `"Split From Entity ID"`+ (shipped children), map to their parent ids, print parents; legacy rows (attribute+ `"Split Entity ID"` present on the shipped original) keep the old mapping as a+ fallback so historical shipments still download correct labels.+4. Maintenance route: remove the per-split `Split` print block (~105–119) — consumed+ portions get no label.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+rg -n '"Split"' apps/erp/app/routes/x+/maintenance+/\$dispatchId.add-and-issue.tsx+# Expected: no product-label print with sourceDocument "Split" remains+```++**Out of scope:** `packages/documents` templates (token contract unchanged),+`inventory.service.ts:2933–2950` picking splitEntityId (still intentionally unused).++## Task 17: Validation gates++**Depends on:** Tasks 1–16+**Steps:**+1. `pnpm run lint` — fix anything introduced by these changes.+2. Scoped typechecks (never whole-repo):+ ```bash+ pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/utils --filter=@carbon/jobs+ ```+3. Deno test + own-file check deltas:+ ```bash+ deno test packages/database/supabase/functions/shared/batch-split.test.ts+ deno test packages/database/supabase/functions/issue/resolve-tracked-entity-bin.test.ts+ ```+4. UI strings changed (Task 1 nouns, Task 15 toast) → run lingui extract and fill:+ `pnpm lingui:extract`, then `/translate` if new empty msgstr appear.++**Verify:**+```bash+pnpm run lint && pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/utils --filter=@carbon/jobs+# Expected: both exit 0+```++## Task 18: Browser verification (/test) of acceptance criteria++**Depends on:** Task 17; requires the user's running dev stack (`crbn up`) — never+restart or rebuild it (memory: connect to the running server only).++**Steps:**+1. Invoke `/auth` then `/test` against the spec's acceptance criteria, minimum flows:+ - batch pick 1-of-8 → shelf row same id qty 7 (check Storage Units card + DB row),+ allocation on new child id, activity feed shows only the Transfer row (no phantom+ adjustments), Storage Units grouped row math correct.+ - issue partial from lineside → toast (no split screen, no print), consumed child in+ genealogy, survivor at lineside.+ - complete op/job → leftover merges into shelf entity (7 → 7.5, Merge activity in+ graph), no new Available fragment.+ - unpick → shelf back to 8, Split activity gone.+ - stock transfer partial → child at destination, `stockTransferLine.trackedEntityId`+ = child, unpick merges back (test on a 2-line transfer).+ - traceability graph for the lot: star shape, no self-loop sections on the shelf+ entity's sidebar.+2. Record the playbook to `.ai/playbooks/batch-split-identity-flip.md` per /test.+3. Any failure → STOP, fix, re-run the affected flow before checking off.++**Verify:** the /test run report lists each flow PASS; paste summary into the PR and the+spec changelog.++**Out of scope:** shipment browser flow if no shippable sales order exists in the dev+tenant — cover with the Deno/typecheck level and note it in the run log.diff --git a/.ai/playbooks/batch-split-identity-flip.md b/.ai/playbooks/batch-split-identity-flip.mdnew file mode 100644index 0000000000..47b561204c--- /dev/null+++ b/.ai/playbooks/batch-split-identity-flip.md@@ -0,0 +1,199 @@+# Manual testing checklist — Batch Split Identity Flip++## ✅ Browser e2e verified 2026-08-05 (real Chrome, erp.batch-split-identity-flip.dev)++Seeded lot 2026/09 = 8 @ BIN-A via the real `post-inventory-adjustment` edge fn.+Added BATCH-TEST-01 (qty 2, Pull from Inventory) to job J000005 Assembly op,+generated picking list PL000004, and exercised the real edge functions:++**PICK 6-of-8 (post-picking `case "batch"`, Task 6) — ALL INVARIANTS HOLD:**+- shelf `shrc1t…` kept its id, decremented 8→2, no `Split Entity ID` written on it+- new child `F0vLO…` qty 6, `Split From Entity ID = shrc1t…`+- ledger: Batch Split −6 shelf / +6 child @ BIN-A (net 0) + Transfer −6 BIN-A / +6 WC-1 on the **child**+- `pickingListLineTrackedEntity` → the **child** id+- Split genealogy: input parent@6 → **one** output child@6 (no self-loop)++**UNPICK (post-picking `unpickBatch`, Task 7) — CLEAN MERGE-BACK:**+- shelf restored 2→8 Available; child drained to 0 / Consumed+- Split activity deleted; allocation row deleted; on-hand reconciles (shelf 8 @ BIN-A)++**ISSUE partial-consume 2-of-6 (MES `issue` `trackedEntitiesToOperation`, Task 9 —+atomicity-critical) — ALL INVARIANTS HOLD:**+- lineside child `smHXnQA2LZ` kept its id, decremented 6→4 (Available @ WC-1)+- consumed portion is a NEW grandchild `ik-Mt17…` qty 2, **Consumed**, `Split From+ Entity ID` = the lineside child (not the shelf)+- Consume activity input references the **consumed grandchild** (entity + ledger halves+ flipped atomically), Split genealogy input child@2 → ONE output grandchild@2+- ledger booked at the actual lineside bin WC-1 (resolveTrackedEntityBin): Batch Split+ −2/+2 net zero + Consumption −2 on the grandchild+- MES showed the lighter toast "Issued 2 of BATCH-TEST-01 — 4 remains" (Task 15) — no+ full-screen split screen, no label print; picker correctly listed both lots (shelf 2 ++ lineside child 6) and issued from the lineside child++Verified live across the two most important edge functions (post-picking + issue).+Remaining flows (complete→merge sweep Task 8, stock transfer Task 11, shipment Task 12,+NCR disposition Task 13) unverified in-browser — same shared `buildBatchSplitRecords`+builder; cover per the checklist below.++---+++Spec: `.ai/specs/2026-08-04-batch-split-identity-flip.md`+Branches: `fix/split-display-fixes` (PR A, display) → `feat/batch-split-identity-flip` (PR B, the flip)++**Core invariant to keep in mind for every split:** the shelf/source lot **keeps its+id and is decremented**; a **new child** entity (same batch number, attribute+`"Split From Entity ID" = <parent id>`) holds the departing quantity. The Split+activity is `input parent@q → output child@q` (no self-loop). The ledger gets exactly+**two** net-zero `Batch Split` rows (−q parent, +q child) at the parent's bin.++## DB helper (authoritative checks)++```bash+DB=$(grep '^SUPABASE_DB_URL' .env.local | cut -d= -f2-)+# Company: d9otj388c0gg27mdg1pg Item BATCH-TEST-01: item_2vR3NXXDHwTXP99sdyA2d8+# Bins: BIN-A sh_M8q44ioXwZ4HbHwRdXHUHw WC-1 sh_GEB3c6mNM9nkEexp99VeL8++# Lot rows for the item (id, qty, status, Split From pointer)+psql "$DB" -c "SELECT id, quantity, status, attributes->>'Split From Entity ID' AS split_from FROM \"trackedEntity\" WHERE \"itemId\"='item_2vR3NXXDHwTXP99sdyA2d8' ORDER BY \"createdAt\";"++# Ledger for the item, per bin (should net to on-hand)+psql "$DB" -c "SELECT \"trackedEntityId\", \"storageUnitId\", \"entryType\", \"documentType\", quantity FROM \"itemLedger\" WHERE \"itemId\"='item_2vR3NXXDHwTXP99sdyA2d8' ORDER BY \"createdAt\";"++# Genealogy edges of a split/merge activity+psql "$DB" -c "SELECT a.type, i.\"trackedEntityId\" AS input, i.quantity AS in_qty, o.\"trackedEntityId\" AS output, o.quantity AS out_qty FROM \"trackedActivity\" a LEFT JOIN \"trackedActivityInput\" i ON i.\"trackedActivityId\"=a.id LEFT JOIN \"trackedActivityOutput\" o ON o.\"trackedActivityId\"=a.id WHERE a.type IN ('Split','Merge') ORDER BY a.\"createdAt\";"+```++`BATCH-TEST-01` already exists (batch-tracked). If you want a fresh scenario, seed a+lot via **Inventory → Quantities → BATCH-TEST-01 → Update Inventory** (Set Quantity 8,+Storage Unit BIN-A, Batch Number e.g. `2026/09`).++---++## A. Display fixes (PR A) — safe to verify on any batch lot, incl. historical++- [ ] **Activity feed labels** — Inventory → Quantities → item → Activity tab. Tracked+ rows say "batch"/"serial" per the item's tracking type (not by quantity>1). A+ sub-1 batch quantity is NOT called "serial".+- [ ] **Batch Split rows hidden** — the activity feed shows the Transfer/Consumption+ rows for a pick/issue but NOT the internal `Batch Split` bookkeeping rows.+- [ ] **Storage Units grouping** — item detail → Storage Units card. Fragments of the+ same lot in the same bin collapse into one group row (summed qty, `×N` count,+ earliest expiration, chevron). Expanding shows the member rows; per-row actions+ (edit / print / adjust) live on the members only. A single-member lot renders+ exactly as before (no chevron).+- [ ] **Traceability sidebar** — Inventory → Traceability, open a received lot that has+ been split. Its sidebar shows a **"Splits"** section (not "Produced by Split" /+ "Consumed by Split"). The graph is a star from the received lot, no self-loop.+- [ ] **Expiry popover** — a split child's expiry trace shows "Split from another batch+ — Parent {id}" using the correct parent (child's `Split From Entity ID`). A+ legacy-only lot (old `Split Entity ID`) does NOT show a bogus parent row.++---++## B. Pick (post-picking `case "batch"`)++Setup: a Job whose BOM has BATCH-TEST-01 as a batch material, generate a picking list,+pick **1 of 8** from lot `2026/09`.++- [ ] Shelf lot keeps its id at **qty 7**, same `createdAt` (not a new row).+- [ ] A **new child** lot at qty 1 sits at the lineside bin with+ `"Split From Entity ID" = <shelf id>`.+- [ ] The picking-list allocation (`pickingListLineTrackedEntity`) references the+ **child** id, not the shelf id.+- [ ] Ledger: exactly **−1/+1 `Batch Split`** at the warehouse bin, plus the Transfer+ pair (−1 warehouse / +1 lineside) on the **child**.+- [ ] Activity feed shows only the Transfer (no phantom adjustments); Storage Units math+ is right.++```sql+-- expect: shelf lot 7 (split_from NULL), child lot 1 (split_from = shelf id)+-- expect: Batch Split −1/+1 net zero + Transfer −1/+1 on child+```++## C. Issue / consume (issue `trackedEntitiesToOperation`)++Issue **0.5** of the picked child (0.5 of 1) from the lineside in MES.++- [ ] MES shows a **one-line toast** ("Issued 0.5 of 2026/09 — 0.5 remains"), **no**+ full-screen split screen, **no** label print.+- [ ] A child-of-child at qty 0.5 is **Consumed** with a Consumption ledger row.+- [ ] The lineside survivor keeps the picked-child id at 0.5 Available.+- [ ] Genealogy: the Consume input references the consumed child (not the survivor).++## D. Operation/Job complete → merge-on-return (post-picking return sweep)++Complete the operation/job so the sweep returns the 0.5 lineside leftover.++- [ ] The 0.5 leftover **merges into the shelf lot** (7 → 7.5) with a **`Merge`**+ activity (input [email protected] → output [email protected]).+- [ ] **No** new Available fragment is left behind.+- [ ] Picking-list header status unchanged (return booked on `quantityReturned`, not+ `quantityPicked`).++## E. Unpick (post-picking `unpickBatch`)++Unpick the batch pick from D's picking list (before consuming, or on a fresh pick).++- [ ] Shelf lot back to **8**; allocation row gone.+- [ ] The **Split activity is deleted** (clean undo); child set Consumed@0.+- [ ] Ledger transfer reversed at the picked magnitude (from the allocation row, not+ the entity's current qty).++## F. Stock transfer (post-stock-transfer `case "batch"` + `unpickBatch`)++Inventory → Stock Transfers, new transfer, move **2** of the 8-lot from BIN-A to WC-1.++- [ ] Source lot stays in BIN-A at **qty 6**; a **new child qty 2** at WC-1 with+ `Split From Entity ID`.+- [ ] `stockTransferLine.trackedEntityId` = the **child** id.+- [ ] Ledger: Batch Split −2/+2 at source + Transfer pair to WC-1 on the child.+- [ ] **Unpick that line** → merges the child fully back into the source lot (6 → 8),+ Split activity deleted. **Test on a 2-line transfer** to confirm the scoped+ Split-activity lookup (each line's unpick deletes only its own Split).++## G. Shipment (post-shipment SO block)++Requires a shippable sales order with a batch line. Ship a partial lot (e.g. 3 of 8).++- [ ] Retained shelf lot keeps its id, decremented, and carries **no** shipment+ attributes.+- [ ] The **shipped child** is Consumed; the `Sales Shipment` ledger books against the+ child.+- [ ] Auto-print / labels-download route emits labels for the **retained** lot(s) only+ (shipped child gets none).+- [ ] (PO-sourced / subcontract shipment, if reachable: split posts genealogy only —+ **no** itemLedger — matching pre-flip behavior. This was a self-review fix.)++## H. NCR disposition (quality `subdivideBatchEntity`)++Quality → Issue with a batch item, split a disposition row mid-lot.++- [ ] Original lot keeps its id + `keepQty`; new lot has `moveQty` ++ `Split From Entity ID`; 2-row net-zero Batch Split ledger.++---++## I. Cross-cutting invariants++- [ ] **Serial assignment** — a job whose output batch was split still assigns serials+ (seed filter matches exactly 1; excludes both pointer keys).+- [ ] **Traveler PDF** prints the surviving lot id (production reader filter).+- [ ] **Availability picker** — after a pick, the lot shows 7 available at the warehouse;+ FEFO/FIFO position unchanged (survivor keeps its `createdAt`).+- [ ] **MES scan mapping** — scanning the shelf label id in the issue modal resolves to+ the allocated lineside child for that operation.+- [ ] **Full-quantity draw** (q = whole lot) still produces **no** Split.+- [ ] **Historical fragments** (pre-flip lots with old `Split Entity ID`) still render,+ return, and consume correctly.+- [ ] **Per-bin ledger nets** — after every flow, `itemLedger` per (entity, bin) is+ non-negative and total on-hand matches the Storage Units card.++## J. Regression sanity++- [ ] Serial pick/issue/unpick unchanged (serials never split).+- [ ] A non-tracked (Inventory) item's pick/issue unchanged.+- [ ] Traceability graph for a fully-consumed lot renders without the dragged-node+ crash (separate pre-existing bug flagged as a background task — not part of this+ change).+```diff --git a/.ai/research/batch-split-identity.md b/.ai/research/batch-split-identity.mdnew file mode 100644index 0000000000..a5727cd59d--- /dev/null+++ b/.ai/research/batch-split-identity.md@@ -0,0 +1,78 @@+# Batch split identity — how ERPs keep lot identity stable across partial draws++> Desk research (model knowledge, no live browsing), 2026-08-04. Grounding: Carbon's+> tracked-entity model read directly from source the same day (`post-picking`, `issue`,+> `post-stock-transfer`, `post-shipment` edge functions; `.claude/rules/traceability-model.md`).+> Purpose: inform `.ai/specs/2026-08-04-batch-split-identity-flip.md`.++## The question++When a batch/lot is partially picked/consumed/transferred, which side of the split keeps+the existing identity — the portion that leaves, or the portion that stays on the shelf?+And should the remainder be a new record at all?++## Industry consensus: the lot number IS the identity; stock is quantity-per-(lot, location)++| System | Model | Partial draw behavior |+|---|---|---|+| SAP ECC/S4 (Batch Management) | `Batch` is master data (MCHA/MCH1); stock = quantity per (material, batch, storage location) in stock tables | Goods issue/transfer posts quantity movements against the SAME batch. No new batch record, no "split" event. Genealogy = goods-issue postings to orders (batch where-used list). |+| Dynamics 365 SCM | Batch number + license plate; on-hand = quantity per (batch, warehouse/location dims) | Picking part of a batch never mints a new batch id. Work/transactions carry quantities. |+| Business Central | Lot No. on item ledger entries; on-hand per lot = Σ ledger | Partial consumption = negative item-ledger entry with the same Lot No. Lot identity immutable. |+| Odoo | `stock.lot` (identity) + `stock.quant` = quantity per (lot, location) | Moves shift quantity between quants of the SAME lot; quants merge automatically per (lot, location). Closest structural analogue to Carbon's proposal #2. |+| Katana / Fishbowl (SMB MES) | Lot/batch record + per-location quantities | Same pattern: identity stable, quantities move. |++Nobody in this set fragments a lot into new identity records on partial draws. "Split" as+a genealogy event does not exist in these systems for batches — the traceability edge is+the consumption/issue posting itself: (order, lot, quantity). Lot splits with new+identities appear only in niche flows (e.g. SAP batch derivation / re-labeling, D365+"batch merge/split" as an explicit user action creating a NEW batch number deliberately —+i.e. a physical re-identification, not bookkeeping).++Implication for Carbon: fragments carry zero traceability information for a homogeneous+batch — kg within a lot are indistinguishable, so per-fragment identity is pure+bookkeeping overhead. Serials are the qty-1 degenerate case and never split.++## Carbon today (verified in source, 2026-08-04)++`trackedEntity` = identity + quantity + status in one row; picking allocation+(`pickingListLineTrackedEntity`), consumption status, and genealogy edges all key on the+row id. Split writers (`post-picking` batch case, `issue` ×2, `post-stock-transfer`,+`post-shipment`) all implement the same convention:++- ORIGINAL id follows the DEPARTING portion (quantity overwritten to the transfer/consume+ amount); attribute `Split Entity ID` → new remainder id.+- NEW nanoid minted for the REMAINDER that stays on the shelf.+- Split activity records the original as BOTH input (full pre-split qty) AND output+ (departing qty), remainder as second output.++Consequences observed on a live tenant (Zero Farms): shelf lot's internal id churns on+every draw → stale physical labels/QR (the shelf bag's label points at the entity that+left), Storage Units UI shows N indistinguishable rows per lot, traceability graph is a+chain of renamed remainders + one Split diamond per draw, activity feed renders the split+ledger triplet (−full/+kept/+remainder) as phantom "adjustments", and returns never merge+(fragment count grows monotonically).++## Decision already taken by the team (Slack, May 15 + Jul 21 2026)++Brad Barbin: "during a split — existing batch stays on shelf with updated quantity, new+batch gets consumed by job." Davide + Umberto + Sid concurred (fixes label reprint,+bidirectional trace). Believed implemented; verified 2026-08-04 it never was — code still+does the inverse.++This is the *inverse-identity* variant of the industry model: keep the entity abstraction,+but pin the identity to the shelf stock (like SAP's batch+storage-location bucket) and+mint short-lived ids only for departing portions that are immediately consumed/shipped.+Combined with merge-on-return it converges on Odoo's quant behavior for the shelf side+while preserving Carbon's per-entity genealogy edges.++## Takeaways for the spec++1. Flip all four split writers: shelf keeps id + decremented quantity; departing portion+ = new entity (which the pick allocates / job consumes / shipment ships).+2. Split activity edges: shelf entity = input (drawn qty), departing entity = output+ (drawn qty). Recording the shelf entity also as an output (survivor self-loop) is what+ makes the UI claim a received lot was "Produced by Split" — drop it or filter it.+3. Returns should merge quantity back into the shelf entity (id now stable, same lot) —+ the industry systems have no fragment to return; merging is the equivalent.+4. History: existing fragments stay; convention applies going forward (matches how SAP+ handles convention changes — no retroactive re-identification).diff --git a/.ai/specs/2026-08-04-batch-split-identity-flip.md b/.ai/specs/2026-08-04-batch-split-identity-flip.mdnew file mode 100644index 0000000000..bb079d11d5--- /dev/null+++ b/.ai/specs/2026-08-04-batch-split-identity-flip.md@@ -0,0 +1,270 @@+# Batch Split Identity Flip — shelf lot keeps its identity++> Status: draft+> Author: Sid (design interview) + Claude+> Date: 2026-08-04+> Research: `.ai/research/batch-split-identity.md`+> Decision source: Slack (Brad Barbin / Davide Codemo / Umberto / Sid), May 15 + Jul 21 2026 —+> "during a split — existing batch stays on shelf with updated quantity, new batch gets+> consumed by job." Believed implemented; verified 2026-08-04 it never was.++## TLDR++Every partial draw from a batch (pick, issue/consume, stock transfer, shipment, NCR+disposition) writes a Split where the ORIGINAL `trackedEntity` id follows the DEPARTING+portion and a NEW id is minted for the remainder left on the shelf. This spec inverts the+convention in all five split writers: **the shelf entity keeps its id and is decremented;+the departing portion is the new entity.** Returns MERGE quantity back into the shelf+entity. Effects: physical shelf labels/QRs stay valid forever, Storage Units shows one row+per lot per bin in steady state, FEFO/FIFO ordering stops being corrupted by splits+(`createdAt` no longer churns), the traceability graph becomes a star rooted at the+received lot instead of a chain of renamed remainders, and fragment count stops growing+monotonically. Batch-only: serial paths never split. **No DB migration** — the entire+convention lives in edge-function/app code and JSONB attributes; SQL is convention-agnostic+(verified: zero migrations reference `'Split'` or `"Split Entity ID"`).++## Problem Statement++Observed on a live tenant (Zero Farms), lot `2026/09`, item SD08810001:++1. One routine job cycle (pick 1 kg from an 8 kg lot, issue 0.5, return 0.5) produces+ 2 Split activities and 3 surviving fragments of the same lot — Storage Units shows+ `0.5`, `7`, `1` as three indistinguishable `2026/09` rows. Fragments never re-merge, so+ the count grows forever.+2. The shelf bag's printed label/QR points at the entity id that LEFT with the picker —+ every physical label goes stale on the first partial draw (Umberto: "forgetting to+ print the new label").+3. The traceability graph is a chain of renamed remainders + one Split diamond per draw;+ the survivor is recorded as both input and output of its own Split, so the sidebar+ claims a receipt-originated lot was "Produced by Split" and "Consumed by Split 8" while+ Available at qty 1.+4. FEFO/FIFO picking is corrupted: the shelf remainder is a NEW row with a fresh+ `createdAt` after every draw (`sortLotsByPickMethod` and the availability RPCs order by+ `createdAt`).+5. The activity feed renders the split's internal ledger triplet as three phantom human+ "adjustments" per pick, and calls sub-1 batch quantities "serial".++Industry consensus (see research file): lot number = identity; stock = quantity per+(lot, location); nobody mints new lot identities on partial draws. Fragments carry zero+traceability information for a homogeneous batch.++## Proposed Solution++### New convention (batch draws only)++On a partial draw of `parent` (shelf/lineside entity) for quantity `q`:++1. Create `child` entity: new nanoid, same `readableId` / `sourceDocument*` / `itemId` /+ `expirationDate`, cloned `attributes` **plus** `"Split From Entity ID": parent.id`+ (and minus any stale pointer keys), `quantity: q`, status per flow (Available for+ pick/transfer; the consuming flows set it Consumed in the same transaction).+2. Decrement `parent.quantity -= q`. Parent attributes are NOT tagged (no more+ `"Split Entity ID"` on the survivor).+3. Split activity: `trackedActivityInput` = parent @ `q`; `trackedActivityOutput` =+ child @ `q`. **No survivor self-loop** (today's input @ full-qty + output @ kept-qty+ pair is dropped). Activity `attributes` keep `Original Quantity` / `Remaining+ Quantity` / the flow's drawn-quantity key, plus `"Split Entity ID": child.id` —+ standardized across all writers (post-shipment omits it today).+4. Ledger: **two** net-zero `Batch Split` rows at the parent's resolved bin+ (`resolveTrackedEntityBin` — lesson `.ai/lessons.md` "actual bin"): `−q` on parent,+ `+q` on child. (Replaces today's `−full/+kept/+remainder` triplet.) The subsequent+ movement (Transfer pair / Consumption / Shipment) books against **child**.+5. Everything downstream that tracked the departing portion references **child**:+ `pickingListLineTrackedEntity` allocation, `stockTransferLine.trackedEntityId`,+ `maintenanceDispatchItemTrackedEntity`, Consume activity input, `status: "Consumed"`,+ Consumption/Shipment ledger rows, `splitEntityId`/`splitEntities[].newId` responses.++Full-quantity draws (q = parent quantity) keep today's no-split fast path unchanged.++### Merge-on-return (new)++When leftover tracked material returns to the warehouse (return sweep at op/job complete),+each returning entity `E` with lineside on-hand `r`:++- Resolve `P` = `E.attributes["Split From Entity ID"]` (one hop; the sweep's lineage+ members each carry a direct pointer).+- **Merge** when `P` exists, `P.status = 'Available'`, `P.readableId = E.readableId`, and+ `P`'s resolved bin = the return target bin: ledger Transfer `−r` on E @ lineside,+ `+r` on P @ target bin; `P.quantity += r`; `E.quantity −= r`, and when it hits 0 →+ `E.status = 'Consumed'`. Genealogy: new `trackedActivity` `type: "Merge"` with input+ E @ `r`, output P @ `r` (type is TEXT — no enum change; UI renders it generically).+- **Fallback** (P missing / not Available / different bin): today's behavior — E returns+ as its own Available entity at the target bin. Never block a return on merge+ eligibility.++**Unpick** (post-picking `unpickBatch`, post-stock-transfer `unpickBatch`) is an undo, not+a return: reverse the Transfer pair for the **allocated child** (quantity from the+allocation row / transfer line — NOT `trackedEntity.quantity`), restore+`parent.quantity += q`, set child `Consumed` @ 0 (row kept — `itemLedger.trackedEntityId`+FK is `ON DELETE SET NULL`; deleting would null history), and DELETE the Split activity ++its input/output rows (clean undo, matching today's Pick-activity deletion). The+stock-transfer merge-back branch detects the split via the child's+`"Split From Entity ID"` (today it reads the pointer off the departing original) and its+Split-activity lookup gets scoped to the entity + transfer (fixes the pre-existing+multi-line bug at `post-stock-transfer/index.ts:884`).++No destination-bin auto-merge in v1 (user-resolved): a transferred child arriving at a bin+that already holds the same lot stays its own entity.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Which side keeps identity | Shelf/source entity keeps id + decrements; departing portion = new entity | Team decision (Slack May 15). Industry: lot identity pinned to stock at rest; labels stay valid. |+| Scope | Batch only; all five writers in lockstep (`post-picking` batch, `issue` ×2, `post-stock-transfer` batch, `post-shipment` SO + PO, `quality-disposition.subdivideBatchEntity`) | Serial paths never split (verified). quality-disposition already has the survivor-keeps-id shape; only pointer/edges/ledger align. Its own comment mandates lockstep with `issue`. |+| Pointer attribute | Stop tagging the survivor; write `"Split From Entity ID": parentId` on the child. Type added to `TrackedEntityAttributes` (`packages/utils/src/types.ts`, `functions/lib/utils.ts`) | A survivor can split many times — a single-valued forward pointer can't hold N children (already broken in spirit today). Child→parent is 1:1, and it's exactly what merge-back needs. |+| "Root/live entity" filters | `.is('attributes->>Split Entity ID', null)` sites additionally filter `.is('attributes->>Split From Entity ID', null)` | Legacy key excludes old departed originals; new key excludes new children. Survivors carry neither → filters keep returning exactly the live root across mixed history. Sites: `production.service.ts:2249,:2280` (traveler PDFs, job page), `assign-serial-numbers/index.ts:88–108`. |+| Split activity edge shape | input = parent @ q; output = child @ q. No survivor self-loop | Honest quantities (edge = the draw), kills "Produced by Split ×2 / Consumed by Split 8" sidebar lies, no strict-RPC self-loop reliance for new data. Mass balance is still derivable from activity attributes. |+| Split ledger rows | 2-row net-zero pair (−q parent / +q child) at parent's `resolveTrackedEntityBin` bin; `documentType: 'Batch Split'` unchanged | Halves feed noise; keeps Xero net-zero exclusion valid (`inventory-adjustment.ts:101–110`); honors the actual-bin lesson. |+| Allocation rows | `pickingListLineTrackedEntity` records the **child** id at posting | Child is the lineside lot — the thing the operator consumes. Availability RPCs need NO change: allocated child sits in excluded lineside bins (same shape as today's departed original); parent is never allocated so its shelf availability is its real remaining qty. |+| Return semantics | Merge into parent (conditions above) with standalone-fragment fallback; Merge activity for genealogy | User-resolved. Odoo-quant behavior per (lot, bin); zero fragments in steady state. |+| Destination merge | None in v1 | User-resolved. Minimal change; revisit. |+| Unpick semantics | Undo: reverse transfer using allocation/line quantity, parent re-increment, child Consumed@0, Split activity deleted | Mirrors today's delete-the-Pick-activity philosophy; fixes `unpickBatch`'s use of `trackedEntity.quantity` (post-flip that would be the remainder) and the unscoped stock-transfer Split lookup. |+| History | Forward-only; no data migration | User-resolved. Old fragments drain as consumed; matches SAP-style convention changes. |+| `splitEntityId` / `splitEntities[].newId` responses | Meaning flips to "departing child id"; every consumer updated in the same PR; app-side consumers resolve the entity's ROLE from `"Split From Entity ID"` rather than assuming | Tolerates the brief function/app deploy skew on release. |+| MES issue UX | Kill the full-screen "Batch Split Occurred" flow; show a one-line confirmation ("Issued 0.5 of 2026/09 — 0.5 remains at {bin}"). No auto label print on issue/maintenance paths. Convert/Scrap retarget to the surviving lineside entity | User-resolved (lighter confirmation option). Consumed portions need no label (Brad). |+| Labels | Stock transfer: print Entity label for the child (it physically arrives somewhere new) + keep the parent reprint (qty changed). Shipment: auto-print retargets to the RETAINED parents (qty changed); shipped child gets no label. Picking: still prints nothing (existing gap; lineside flows scan by lot/allocation, see scan mapping) | Labels exist for stock at rest. `file+/shipment+/$id.labels[.]{zpl,pdf}` resolve retained lots via the child's `"Split From Entity ID"` instead of the legacy forward pointer. |+| MES scan mapping | Issue-modal scan of a parent (shelf label) resolves to its allocated lineside child for the operation when one exists (via `pickingListLineTrackedEntity` + `Split From` pointer) | Today scanning the shelf label "works" only because the shelf label's id departed. Post-flip the shelf label points at warehouse stock; without mapping, issue would consume the warehouse lot at the wrong bin — silent-corruption site #3's cousin. |+| "Newest live" lookups | Every `attributes->>'Job Make Method'`-family lookup selects the survivor via `status != 'Consumed'` (exactly one live row); never by `createdAt` recency | The flip inverts the age signal (survivor becomes the OLDER row). Sites enumerated in the plan (issue `:1165`, MES `operations.service.ts:51,:1151`, `inventory.service.ts:1367`, JobHeader/JobsTable, print-job resolvers, issue routes). |+| Multi-tenancy / auth | No new tables, no RLS, no schema change; all writes stay inside the existing edge-function transactions with existing `companyId` scoping | Heuristics 1–4 satisfied by construction; heuristics 5–6 N/A (no new forms/modules). |+| Tests | New Deno tests colocated with the edge functions asserting WHICH id gets: Consumed status, Consumption ledger, allocation row, merged-back quantity | Zero regression coverage exists today and 10 of the breakage modes are silent. |++## Data Model Changes++**None.** No migration, no `generate:types`. The convention lives entirely in:+- edge-function code (`packages/database/supabase/functions/{post-picking,issue,post-stock-transfer,post-shipment}`),+- `apps/erp/app/modules/quality/quality-disposition.server.ts`,+- JSONB `trackedEntity.attributes` keys (`"Split From Entity ID"` new, `"Split Entity ID"` no longer written on entities, still written on Split **activity** attributes),+- a new `trackedActivity.type` value `'Merge'` (TEXT column — no enum).++Verified: no SQL function/view/trigger references `'Split'` or `"Split Entity ID"`.++## API / Service Changes++### Writers (the flip itself)++1. **`post-picking` `case "batch"`** — child = departing lineside lot: Split edges, 2-row+ ledger, Transfer pair on child, Pick activity input on child,+ `pickingListLineTrackedEntity` upsert keyed on child.+2. **`post-picking` `unpickBatch`** — target the allocated child (qty from allocation+ row), merge back into parent, delete Split; `unpickSerial` untouched.+3. **`post-picking` `returnTrackedAllocationRemainder`** — walk unchanged (seed = child,+ forward walk still superset); per returning entity apply merge-on-return; allocation+ decrement stays keyed on the allocated (child) id. Untracked path untouched.+4. **`issue` `trackedEntitiesToOperation`** — child = consumed portion: Consumed status,+ Consume input, Consumption ledger, `splitEntities[].newId` all on child; parent only+ decremented. MTO no-ledger branch keeps parity.+5. **`issue` `maintenanceDispatchTrackedEntities`** — same, plus+ `maintenanceDispatchItemTrackedEntity` junction gets child; align its bin resolution+ with `resolveTrackedEntityBin` (pre-existing inconsistency).+6. **`post-stock-transfer` `case "batch"`** — child departs to `toStorageUnitId`;+ `stockTransferLine.trackedEntityId = child`; `unpickBatch` merge-back re-detected via+ child's `Split From` pointer + scoped activity lookup.+7. **`post-shipment` SO + PO blocks** — child = shipped portion (Consumed, shipment+ attrs); parent retains id + keeps NO shipment attributes (deletes the dead+ `updatedAttributesObj` code by making the live path do what it intended);+ `splitEntityIds` becomes the retained-parent ids (see labels decision).+8. **`quality-disposition.subdivideBatchEntity`** — pointer + edges + 2-row ledger+ aligned (identity polarity already correct).++### Readers++- `production.service.ts` `getTrackedEntityByJobId` / `getTrackedEntitiesByJobId`: add+ `Split From` null-filter (traveler PDFs, job routes).+- `assign-serial-numbers`: seed filter excludes both pointer keys.+- MES `inventory.service.ts` `getPickedTrackedEntitiesForMaterial`: docstring + semantics+ (allocated ids are now the lineside children — still valid picker options).+- MES `IssueMaterialModal`: lighter confirmation, Convert/Scrap retarget, scan mapping+ parent→allocated child.+- `apps/mes/app/routes/x+/issue-tracked-entity.tsx`, ERP+ `maintenance+/$dispatchId.add-and-issue.tsx`: drop Split auto-print.+- Stock-transfer routes (`$id.line.quantity.tsx`, `$id.scan.$lineId.tsx`): swap label+ roles (child = new Entity label, parent = reprint).+- `shipment+/$shipmentId.post.tsx` + `file+/shipment+/$id.labels[.]{zpl,pdf}.tsx`:+ retained-parent label resolution.+- "Newest live" audit across the §Design-Decisions list.+- `ExpiryTracePopover.tsx`: "Split from another batch — Parent {id}" reads the child's+ `Split From` pointer (finally correct).++## UI Changes++Companion display fixes (separate PR, shippable first — they help historical data too):++1. `InventoryActivity.tsx`: label from `itemTrackingType` (kill the `qty > 1 ? "batch" :+ "serial"` heuristic, 6 sites); hide `documentType: 'Batch Split'` rows from the feed+ (internal bookkeeping — the Transfer/Consumption rows tell the story).+2. `InventoryStorageUnits.tsx` (+ its quantities source): group rows by+ (`readableId`, storage unit), summed quantity, expandable to fragments.+3. Traceability sidebar + graph: filter/relabel self-loop Split rows (historical data+ keeps them forever under forward-only).++## Acceptance Criteria++All on a batch-tracked item; `X` = shelf entity id before the action.++- [ ] Pick 1 from an 8 kg lot: shelf row keeps id `X` at qty 7 (same `createdAt`), a new+ entity at qty 1 sits at the lineside bin with `"Split From Entity ID" = X`, the+ picking-list allocation references the new id, Split activity edges are+ input `X`@1 → output child@1, ledger shows exactly −1/+1 `Batch Split` at the+ warehouse bin + the Transfer pair on the child.+- [ ] Issue 0.5 of that child: child-of-child qty 0.5 is Consumed with the Consumption+ ledger row; the lineside survivor keeps the child id at 0.5 Available; MES shows the+ one-line confirmation and does NOT print a label or show the split screen.+- [ ] Job completes: the 0.5 lineside leftover merges into `X` (7 → 7.5) with a Merge+ activity; no new Available fragment exists; picking-list header status unchanged.+- [ ] Unpick the batch pick: `X` back to 8, allocation row gone, Split activity gone,+ child Consumed@0; ledger transfer reversed at the correct magnitude.+- [ ] Stock-transfer 2 of `X` to bin B: `X` stays in source bin at qty−2; new entity qty 2+ at B; `stockTransferLine.trackedEntityId` = new id; unpicking that line merges back+ into `X` and works on a multi-line transfer.+- [ ] Ship partial lot: retained shelf entity keeps `X` + no shipment attributes; shipped+ child is Consumed; auto-print and the labels download route emit labels for the+ RETAINED lot(s) only.+- [ ] Serial-number assignment on a job whose output batch was split still assigns+ (seed filter matches exactly 1).+- [ ] Traveler PDF prints the surviving lot id.+- [ ] Availability picker: after the pick, lot `X` shows 7 available at the warehouse;+ FEFO/FIFO position unchanged from before the pick.+- [ ] Scanning the shelf label (id `X`) in the MES issue modal resolves to the allocated+ lineside child for that operation.+- [ ] Full-quantity draw still produces no Split.+- [ ] Historical fragments still render, return, and consume correctly (forward-only).+- [ ] Deno tests cover: which id gets Consumed/ledger/allocation in `issue`;+ pick-split + unpick round-trip in `post-picking`; transfer-split + merge-back in+ `post-stock-transfer`.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Partial flip in `issue` (entity half flipped, Consumed/ledger half not) marks the shelf remainder Consumed → double-counted on-hand | High | Flip each writer as one atomic edit; Deno test asserts the consumed id; acceptance #2. |+| Stock-transfer unpick merge-back silently stops detecting splits | High | Re-detection via child pointer + scoped lookup; acceptance #5 includes multi-line. |+| Allocation/netting mismatch hides shelf availability | High | Child-keyed allocation + RPC no-change argument (children live in excluded lineside bins); acceptance #9. |+| MES picked-lot suggestions / scan point at warehouse stock | High | Child-keyed allocations + parent→child scan mapping; acceptance #11. |+| "Newest live" heuristics select the wrong row once the survivor is the older one | Med | Status-based selection rule; per-site audit task in the plan. |+| Serial assignment no-ops (seed filter matches 2) | Med | Dual-key null filter; acceptance #7. |+| Wrong-magnitude unpick (uses `trackedEntity.quantity`) | Med | Quantity from allocation/line rows; acceptance #4. |+| Deploy skew between edge functions and apps briefly inverts label roles | Low | App consumers resolve role from `Split From` attribute, not positional assumption. |+| Mixed-history confusion (old fragments + new convention) | Low | Forward-only decision; filters handle both keys; display grouping collapses old noise. |+| Merge-on-return books into a moved/consumed parent | Low | Merge guarded (Available + same lot + same bin), else standalone fallback. |++## Open Questions++> All resolved with Sid before this spec was written (AskUserQuestion, 2026-08-04).++- [x] Merge-on-return vs keep-separate — **Answer:** merge into parent when parent is+ Available/same-lot/same-bin; standalone fragment fallback. Merge activity for+ genealogy.+- [x] Destination-bin auto-merge on stock transfer — **Answer:** no, v1 forward-only per+ (lot, arrival); revisit later.+- [x] MES split ceremony — **Answer:** replace with a lighter one-line confirmation+ ("issued q, r remains"); no label print; Convert/Scrap retarget to the surviving+ lineside entity.+- [x] Historical fragments — **Answer:** forward-only, no data migration.++## Changelog++- 2026-08-04: Created after code-verified blast-radius sweep (5 writers, 10 silent-risk+ sites, no SQL coupling, no test coverage) + desk research+ (`.ai/research/batch-split-identity.md`) + 4 user-resolved questions. Companion display+ fixes scoped as a separate first PR.diff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.mdindex 9263fe7379..ca8441f47f 100644--- a/.claude/rules/traceability-model.md+++ b/.claude/rules/traceability-model.md@@ -109,20 +109,39 @@ takes `p_sort_method` (`Default|FEFO|FIFO|LIFO`) — but its internal `ORDER BY`guaranteed through PostgREST (SQL-function inlining), so callers that need a specificorder sort in the app (MES `sortLotsByPickMethod` in `apps/mes/app/services/allocation.ts`).+**Split identity convention (batch only; spec `.ai/specs/2026-08-04-batch-split-identity-flip.md`):**+on a partial batch draw of quantity `q` from `parent`, the **shelf/source entity KEEPS its id**+and is decremented by `q`; a **NEW `child` entity** (same `readableId`, attributes cloned ++`"Split From Entity ID": parent.id`) holds `q` and is what departs (lineside / other bin /+consumed / shipped). The Split activity records input `parent`@`q` → output `child`@`q` (no+survivor self-loop), and the ledger gets exactly **two** net-zero `Batch Split` rows+(−`q` parent, +`q` child) at the parent's `resolveTrackedEntityBin` bin. The legacy pre-flip+convention (original departs, `"Split Entity ID"` tagged on the survivor) still exists on+historical rows — filters that isolate the live root entity exclude BOTH pointer keys. The+shared record builder is `functions/shared/batch-split.ts` (`buildBatchSplitRecords` /+`buildMergeRecords`), used by every writer: `post-picking` (batch), `issue`+(`trackedEntitiesToOperation` + `maintenanceDispatchTrackedEntities`), `post-stock-transfer`+(batch), `post-shipment` (SO + PO — PO posts genealogy only, no ledger), and ERP+`quality-disposition.subdivideBatchEntity`. Serial paths never split. Exception: the+PO-sourced `post-shipment` split posts no `itemLedger` (matches pre-flip behavior).+**Pick → consume → return lifecycle (batch/serial):** a **pick** (`post-picking`) is an-`itemLedger` Transfer warehouse→lineside; **consumption** (`issue` `trackedEntitiesToOperation`)-posts a negative Consumption row and, on partial use, **splits** the entity — the un-consumed-remainder becomes a NEW `trackedEntity` (a Split descendant), NOT the originally-picked one, and-`pickingListLineTrackedEntity` is not updated. Consumption/split rows are booked against the-entity's actual on-hand bin (`resolveTrackedEntityBin`), not an arbitrary ledger row. The-**return** of the un-consumed remainder runs via `post-picking`'s sweep cases-`returnJobRemainders` (at job complete — both policies) / `returnOperationRemainders` (at-operation Done, only when `companySettings.returnPickedMaterialTiming = 'operation'`): the-tracked path walks the picked entity's split lineage and transfers each lineage entity's-remaining lineside on-hand back to source, decrementing the `pickingListLineTrackedEntity`-allocation but booking the line-level return on **`pickingListLine.quantityReturned`** (NOT-decrementing `quantityPicked` — that would fire `update_picking_list_status` and demote a-Completed/Partial header). Untracked materials return per jobMaterial:+`itemLedger` Transfer warehouse→lineside (the departing lineside lot is the split CHILD, and+`pickingListLineTrackedEntity` records the CHILD id); **consumption** (`issue`+`trackedEntitiesToOperation`) posts a negative Consumption row and, on partial use, **splits**+the entity — the CONSUMED portion becomes the NEW `child` (`status: 'Consumed'`), the survivor+keeps its id at lineside. Consumption/split rows are booked against the entity's actual on-hand+bin (`resolveTrackedEntityBin`), not an arbitrary ledger row. The **return** of the un-consumed+remainder runs via `post-picking`'s sweep cases `returnJobRemainders` (at job complete — both+policies) / `returnOperationRemainders` (at operation Done, only when+`companySettings.returnPickedMaterialTiming = 'operation'`): the tracked path walks the picked+entity's split lineage and, for each lineage entity with lineside on-hand, **merges** it back+into its `"Split From Entity ID"` parent when the parent is Available/same-lot/same-bin (a+`type: 'Merge'` activity + net Transfer), else transfers it back as a standalone lot. It+decrements the `pickingListLineTrackedEntity` allocation but books the line-level return on+**`pickingListLine.quantityReturned`** (NOT decrementing `quantityPicked` — that would fire+`update_picking_list_status` and demote a Completed/Partial header). Untracked materials return+per jobMaterial:`max(0, Σ(picked − returned) − max(quantityIssued, owed))`, newest-line-first — never a binsweep (the lineside bin is shared per work center). Spec:`.ai/specs/2026-08-04-picked-material-return-timing.md`.diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 97834e1dfc..652ea63587 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -2241,12 +2241,16 @@ export async function getTrackedEntityByJobId(};}+ // Survivors carry NEITHER pointer key: the legacy key marks old departed+ // originals, the new key marks split children — filtering both returns+ // exactly the live root entity across mixed-convention history.const result = await client.from("trackedEntity").select("*").eq("attributes ->> Job Make Method", jobMakeMethod.data.id).eq("companyId", jobMakeMethod.data.companyId).is("attributes ->> Split Entity ID", null)+ .is("attributes ->> Split From Entity ID", null).limit(1);return {@@ -2277,7 +2281,8 @@ export async function getTrackedEntitiesByJobId(.select("*").eq("attributes ->> Job Make Method", jobMakeMethod.data.id).eq("companyId", jobMakeMethod.data.companyId)- .is("attributes ->> Split Entity ID", null);+ .is("attributes ->> Split Entity ID", null)+ .is("attributes ->> Split From Entity ID", null);}/**diff --git a/apps/erp/app/modules/quality/quality-disposition.server.ts b/apps/erp/app/modules/quality/quality-disposition.server.tsindex e315efea7f..0780e37290 100644--- a/apps/erp/app/modules/quality/quality-disposition.server.ts+++ b/apps/erp/app/modules/quality/quality-disposition.server.ts@@ -1,8 +1,9 @@-import type { Database } from "@carbon/database";+import type { Database, Json } from "@carbon/database";import type { KyselyTx } from "@carbon/database/client";import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";-+import { nanoid } from "nanoid";import { getDatabaseClient } from "~/services/database.server";+import { buildBatchSplitRecords } from "../../../../../packages/database/supabase/functions/shared/batch-split.ts";import { isIssueLocked } from "./quality.models";import { errResult, type Result } from "./quality.server";@@ -154,13 +155,14 @@ export async function assignEntitiesToIssueItem(args: {// 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-// (trackedActivity "Split" + inputs/outputs + net-zero "Batch Split" itemLedger,+// (trackedActivity "Split" + input/output + net-zero "Batch Split" itemLedger,// which leaves on-hand unchanged).//-// NOTE: the same lot-subdivision + genealogy also lives in the MES issue edge-// function (packages/database/supabase/functions/issue/index.ts, case-// "trackedEntitiesToOperation"). They can't share code across the app/Deno-// boundary today — keep the two in sync if the genealogy shape changes.+// NOTE: the split record contract (pointer attribute, edge shape, 2-row ledger+// pair) is the shared builder at+// packages/database/supabase/functions/shared/batch-split.ts, imported here+// directly — the same one the issue/post-picking/post-stock-transfer/+// post-shipment edge functions use. Don't hand-roll a divergent shape.// The storage unit a tracked entity currently holds stock in, derived from its// item-ledger rows by net on-hand per bin. Batch-split ledger entries MUST be@@ -236,33 +238,63 @@ async function subdivideBatchEntity(nowIso} = args;- const newEntity = await trx- .insertInto("trackedEntity")- .values({+ // The bin the source lot actually holds stock in — split ledger entries book+ // against it so per-storage-unit on-hand stays consistent (see helper note).+ const sourceLedgerRows = await trx+ .selectFrom("itemLedger")+ .select(["storageUnitId", "quantity"])+ .where("trackedEntityId", "=", source.id)+ .where("companyId", "=", companyId)+ .execute();+ const storageUnitId = resolveHoldingStorageUnit(sourceLedgerRows);++ const split = buildBatchSplitRecords({+ parent: {+ id: source.id,readableId: source.readableId,- sourceDocumentId: source.sourceDocumentId,+ quantity: entityQty,+ // Matches what this function always stamped on subdivision lots.sourceDocument: "Item",+ sourceDocumentId: source.sourceDocumentId,sourceDocumentReadableId: source.sourceDocumentReadableId,- quantity: moveQty,- status: source.status ?? "Available",- attributes: source.attributes,itemId: source.itemId ?? source.sourceDocumentId,expirationDate: source.expirationDate ?? null,- companyId,- createdBy: userId+ attributes: source.attributes as Record<string, unknown> | null+ },+ drawQuantity: moveQty,+ childId: nanoid(),+ splitActivityId: nanoid(),+ activitySourceDocument: "Non-Conformance",+ activitySourceDocumentId: nonConformanceId,+ bin: { storageUnitId, locationId },+ itemLedgerItemId: itemId,+ companyId,+ userId,+ postingDate: nowIso.slice(0, 10),+ childStatus: "Available"+ });++ const newEntityId = split.childEntityInsert.id;++ await trx+ .insertInto("trackedEntity")+ .values({+ ...split.childEntityInsert,+ // Non-null in the node Insert type; the builder types them nullable.+ sourceDocument: "Item",+ sourceDocumentId: source.sourceDocumentId,+ attributes: split.childEntityInsert.attributes as Json,+ // NC-linked lots may be On Hold — the subdivided half inherits the+ // source's status, not a blanket Available.+ status: source.status ?? "Available"})- .returning(["id"])- .executeTakeFirstOrThrow();+ .execute();+ // The retained lot is only decremented — no pointer is written on it; the+ // child carries "Split From Entity ID" instead.await trx.updateTable("trackedEntity")- .set({- quantity: keepQty,- attributes: {- ...((source.attributes as Record<string, unknown>) ?? {}),- "Split Entity ID": newEntity.id- }- })+ .set({ quantity: keepQty }).where("id", "=", source.id).where("companyId", "=", companyId).execute();@@ -279,118 +311,46 @@ async function subdivideBatchEntity(.values({nonConformanceItemId: newRowId,nonConformanceId,- trackedEntityId: newEntity.id,+ trackedEntityId: newEntityId,quantity: moveQty,companyId,createdBy: userId}).execute();- const activity = await trx+ await trx.insertInto("trackedActivity").values({- type: "Split",- sourceDocument: "Non-Conformance",- sourceDocumentId: nonConformanceId,+ ...split.activityInsert,sourceDocumentReadableId: readableNc,attributes: {+ ...split.activityInsert.attributes,"Non-Conformance": nonConformanceId,- "Original Quantity": entityQty,- "Split Quantity": moveQty,- "Remaining Quantity": keepQty,- "Split Entity ID": newEntity.id,Employee: userId- },- companyId,- createdBy: userId+ }})- .returning(["id"])- .executeTakeFirstOrThrow();+ .execute();await trx.insertInto("trackedActivityInput")- .values({- trackedActivityId: activity.id,- trackedEntityId: source.id,- quantity: entityQty,- companyId,- createdBy: userId- })+ .values(split.activityInputInsert).execute();await trx.insertInto("trackedActivityOutput")- .values([- {- trackedActivityId: activity.id,- trackedEntityId: source.id,- quantity: keepQty,- companyId,- createdBy: userId- },- {- trackedActivityId: activity.id,- trackedEntityId: newEntity.id,- quantity: moveQty,- companyId,- createdBy: userId- }- ])+ .values(split.activityOutputInsert).execute();- // The bin the source lot actually holds stock in — split ledger entries book- // against it so per-storage-unit on-hand stays consistent (see helper note).- const sourceLedgerRows = await trx- .selectFrom("itemLedger")- .select(["storageUnitId", "quantity"])- .where("trackedEntityId", "=", source.id)- .where("companyId", "=", companyId)- .execute();- const storageUnitId = resolveHoldingStorageUnit(sourceLedgerRows);-await trx.insertInto("itemLedger")- .values([- {+ .values(+ split.ledgerInserts.map((ledger) => ({+ ...ledger,+ // Non-null in the node Insert type; the builder types it nullable.itemId,- locationId,- storageUnitId,- entryType: "Negative Adjmt." as const,- documentType: "Batch Split" as const,- documentId: activity.id,- quantity: -entityQty,- trackedEntityId: source.id,- companyId,- createdBy: userId,comment: `NC ${readableNc} batch split`- },- {- itemId,- locationId,- storageUnitId,- entryType: "Positive Adjmt." as const,- documentType: "Batch Split" as const,- documentId: activity.id,- quantity: keepQty,- trackedEntityId: source.id,- companyId,- createdBy: userId,- comment: `NC ${readableNc} batch split`- },- {- itemId,- locationId,- storageUnitId,- entryType: "Positive Adjmt." as const,- documentType: "Batch Split" as const,- documentId: activity.id,- quantity: moveQty,- trackedEntityId: newEntity.id,- companyId,- createdBy: userId,- comment: `NC ${readableNc} batch split`- }- ])+ }))+ ).execute();}diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsxindex dd77ec2ff3..b9b3502842 100644--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx@@ -58,16 +58,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {) ?? [];}+ // Labels are for the RETAINED shelf lots, not the shipped portions. New+ // convention: the shipped child carries "Split From Entity ID" → its parent+ // is the retained lot. Legacy rows: the shipped original carries+ // "Split Entity ID" → the remainder it points at is the retained lot.const itemEntityIds = filteredTracking- ?.filter(- (tracking) =>- "Split Entity ID" in (tracking.attributes as TrackedEntityAttributes)- )- ?.map(- (tracking) =>- (tracking.attributes as TrackedEntityAttributes)["Split Entity ID"] ??- ""- )+ ?.flatMap((tracking) => {+ const attributes = (tracking.attributes ?? {}) as TrackedEntityAttributes;+ const retainedId =+ attributes["Split From Entity ID"] ?? attributes["Split Entity ID"];+ return retainedId ? [retainedId] : [];+ }).sort((a, b) => a.localeCompare(b)).filter(Boolean);diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsxindex 13f7d46f42..b1fd041bf5 100644--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx@@ -58,16 +58,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {) ?? [];}+ // Labels are for the RETAINED shelf lots, not the shipped portions. New+ // convention: the shipped child carries "Split From Entity ID" → its parent+ // is the retained lot. Legacy rows: the shipped original carries+ // "Split Entity ID" → the remainder it points at is the retained lot.const itemEntityIds = filteredTracking- ?.filter(- (tracking) =>- "Split Entity ID" in (tracking.attributes as TrackedEntityAttributes)- )- ?.map(- (tracking) =>- (tracking.attributes as TrackedEntityAttributes)["Split Entity ID"] ??- ""- )+ ?.flatMap((tracking) => {+ const attributes = (tracking.attributes ?? {}) as TrackedEntityAttributes;+ const retainedId =+ attributes["Split From Entity ID"] ?? attributes["Split Entity ID"];+ return retainedId ? [retainedId] : [];+ }).sort((a, b) => a.localeCompare(b)).filter(Boolean);diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsxindex 46977b657b..fc1c96fd35 100644--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx@@ -1,7 +1,6 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -102,21 +101,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const splitEntities = issue.data?.splitEntities || [];- if (splitEntities.length > 0) {- try {- for (const split of splitEntities) {- await trigger("print-job", {- sourceDocument: "Split",- sourceDocumentId: split.newId,- companyId,- userId- });- }- } catch (e) {- logger.error("Auto-print for split entities failed", { error: e });- }- }+ // No label print on issue splits: the split child is CONSUMED into the+ // dispatch and consumed portions get no label; the surviving entity keeps+ // its existing label.} else {// Inventory itemconst issue = await serviceRole.functions.invoke("issue", {diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsxindex 3b5157d148..6ad374163b 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx@@ -305,13 +305,16 @@ export async function action({ request, params }: ActionFunctionArgs) {logger.error("Auto-print failed", { error: e });}- // Auto-print labels for batch split entities+ // Auto-print labels for batch split entities. splitEntityIds carries the+ // RETAINED shelf lots (their quantity changed in the split) — existing+ // entities being reprinted, hence sourceDocument "Entity". The shipped+ // child departed Consumed and gets no label.const splitEntityIds = postShipment.data?.splitEntityIds || [];if (splitEntityIds.length > 0) {try {for (const entityId of splitEntityIds) {await trigger("print-job", {- sourceDocument: "Split",+ sourceDocument: "Entity",sourceDocumentId: entityId,companyId,userIddiff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsxindex 0fc320e760..f82070b5b3 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx@@ -124,14 +124,18 @@ export async function action({ request, params }: ActionFunctionArgs) {if (transferResult?.splitEntityId) {try {+ // Post-flip, splitEntityId is the DEPARTING child that physically+ // arrives at the destination bin — it gets a fresh Entity label. The+ // payload entity is the shelf parent whose quantity changed — reprint.+ // (Under legacy deploy skew the roles invert, but both entities still+ // need Entity labels, so printing both ids is role-agnostic.)await trigger("print-job", {- sourceDocument: "Split",+ sourceDocument: "Entity",sourceDocumentId: transferResult.splitEntityId,companyId,userId,locationId: locationId || undefined});- // Reprint the original batch too — its quantity changed in the splitif (trackedEntityId) {await trigger("print-job", {sourceDocument: "Entity",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.tsxindex 1f66b6f236..fb4511f1f1 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@@ -192,14 +192,18 @@ export async function action({ request, params }: ActionFunctionArgs) {if (transferResult?.splitEntityId) {try {+ // Post-flip, splitEntityId is the DEPARTING child that physically+ // arrives at the destination bin — it gets a fresh Entity label. The+ // payload entity is the shelf parent whose quantity changed — reprint.+ // (Under legacy deploy skew the roles invert, but both entities still+ // need Entity labels, so printing both ids is role-agnostic.)await trigger("print-job", {- sourceDocument: "Split",+ sourceDocument: "Entity",sourceDocumentId: transferResult.splitEntityId,companyId,userId,locationId: locationId || undefined});- // Reprint the original batch too — its quantity changed in the splitif (trackedEntityId) {await trigger("print-job", {sourceDocument: "Entity",diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsxindex bfbeffd528..86f20d6582 100644--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx@@ -1,10 +1,5 @@import { useCarbon } from "@carbon/auth";-import {- Input as FormInput,- Number as FormNumberInput,- Hidden,- ValidatedForm-} from "@carbon/form";+import { Number as FormNumberInput, Hidden, ValidatedForm } from "@carbon/form";import {Alert,AlertDescription,@@ -40,35 +35,30 @@ import {TabsContent,TabsList,TabsTrigger,- toast,- useDisclosure+ toast} from "@carbon/react";import { getItemReadableId } from "@carbon/utils";import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import { useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {- LuArrowRightLeft,LuCheck,LuChevronDown,LuChevronUp,LuCirclePlus,- LuGitBranch,LuList,LuQrCode,- LuScale,- LuTrash,LuUndo2,LuX} from "react-icons/lu";import { useFetcher } from "react-router";-import { PrintButton } from "~/components";import type {getBatchNumbersForItem,getSerialNumbersForItem,SuggestedAllocationLot} from "~/services/inventory.service";-import { convertEntityValidator, issueValidator } from "~/services/models";+import { issueValidator } from "~/services/models";import type { JobMaterial, TrackedInput } from "~/services/types";import { useItems } from "~/stores";import { path } from "~/utils/path";@@ -134,6 +124,7 @@ export function IssueMaterialModal({onClose: () => void;}) {const { carbon } = useCarbon();+ const { t } = useLingui();const [items] = useItems();const numberFormatter = useNumberFormatter({ maximumFractionDigits: 4 });@@ -415,6 +406,26 @@ export function IssueMaterialModal({usePickedAllocation(shouldLoadPickedAllocation ? (material?.id ?? undefined) : undefined);++ // Scanning the SHELF label must issue the allocated lineside child, not the+ // warehouse lot: after a partial pick the shelf entity keeps its id (and its+ // printed label) while the picked portion is a child entity staged at+ // lineside. Without this mapping, a shelf-label scan would consume the+ // warehouse parent at the wrong bin. Only remaps when the scanned id is not+ // itself an allocated lot and a picked child points back at it.+ const resolveScannedBatchId = useCallback(+ (scannedId: string) => {+ if (!scannedId || pickedAllocation.length === 0) return scannedId;+ if (pickedAllocation.some((lot) => lot.trackedEntityId === scannedId)) {+ return scannedId;+ }+ return (+ pickedAllocation.find((lot) => lot.splitFromEntityId === scannedId)+ ?.trackedEntityId ?? scannedId+ );+ },+ [pickedAllocation]+ );// Prefer the actual picks; fall back to the suggestion only when nothing's// been picked yet (allocated-but-not-picked) or when there's no picking list.// Wait for the picked-allocation request to resolve before falling back, so a@@ -525,16 +536,6 @@ export function IssueMaterialModal({const hasExpiredSelection =expiredSerialIds.length > 0 || expiredBatchIds.length > 0;- // Split entities result state (for batch splitting)- const [splitEntitiesResult, setSplitEntitiesResult] = useState<- {- newId: string;- originalId: string;- quantity: number;- readableId?: string;- }[]- >([]);-// Fetchersconst fetcher = useFetcher<{success: boolean;@@ -544,16 +545,12 @@ export function IssueMaterialModal({newId: string;quantity: number;readableId?: string;+ remainingQuantity?: number;}>;}>();const unconsumeFetcher = useFetcher<{ success: boolean; message: string }>();const inventoryFetcher = useFetcher<{ success: boolean; message: string }>();- // Sub-modals for batch splitting- const convertDisclosure = useDisclosure();- const scrapDisclosure = useDisclosure();- const [trackedEntity, setTrackedEntity] = useState<string | null>(null);-// Fetch item details when item is selected (only when no material provided)const handleItemChange = useCallback(async (itemId: string) => {@@ -1053,15 +1050,27 @@ export function IssueMaterialModal({fetcher.data.splitEntities &&fetcher.data.splitEntities.length > 0) {- setSplitEntitiesResult(- fetcher.data.splitEntities.map((entity) => ({- newId: entity.newId,- originalId: entity.originalId,- readableId: entity.readableId,- quantity: entity.quantity- }))- );- toast.success(fetcher.data.message);+ // A partial issue split the lot: the consumed portion departed as a+ // new child entity and the surviving lineside lot kept its id (and+ // its label). A one-line confirmation replaces the old full-screen+ // split ceremony — nothing to print, nothing to act on.+ for (const split of fetcher.data.splitEntities) {+ const lotLabel =+ split.readableId ||+ getItemReadableId(items, material?.itemId) ||+ "batch";+ const issuedQuantity = numberFormatter.format(split.quantity);+ const remainingQuantity =+ split.remainingQuantity !== undefined+ ? numberFormatter.format(split.remainingQuantity)+ : null;+ toast.success(+ remainingQuantity !== null+ ? t`Issued ${issuedQuantity} of ${lotLabel} — ${remainingQuantity} remains`+ : t`Issued ${issuedQuantity} of ${lotLabel}`+ );+ }+ onClose();} else {onClose();if (fetcher.data.message) {@@ -1072,7 +1081,15 @@ export function IssueMaterialModal({toast.error(fetcher.data.message);}}- }, [fetcher.state, fetcher.data, onClose]);+ }, [+ fetcher.state,+ fetcher.data,+ onClose,+ items,+ material?.itemId,+ numberFormatter,+ t+ ]);useEffect(() => {if (unconsumeFetcher.data?.success) {@@ -1114,76 +1131,9 @@ export function IssueMaterialModal({)}</ModalHeader>- {splitEntitiesResult.length > 0 ? (- // Show split entities result- <ModalBody>- <Alert variant="default" className="mb-4">- <LuGitBranch className="mr-2" />- <AlertTitle>Batch Split Occurred</AlertTitle>- <AlertDescription>- <div className="flex flex-col gap-2">- <p>A new batch entity was created from a split:</p>- <ul className="list-disc list-inside space-y-1">- {splitEntitiesResult.map((split) => (- <li key={split.newId} className="flex flex-col text-sm">- <span className="text-md font-semibold">- {split.readableId ??- getItemReadableId(items, material?.itemId) ??- "Material"}- </span>- <div className="flex gap-2 items-center">- <span className="font-mono flex gap-1 items-center">- <LuQrCode />- {split.newId}- </span>- <span className="font-mono text-xs text-muted-foreground flex gap-1 items-center truncate">- <LuScale />- {numberFormatter.format(split.quantity)}- </span>- </div>- <div className="flex gap-2 mt-4">- <PrintButton- sourceDocument="Split"- sourceDocumentId={split.newId}- locationId={locationId}- context="workCenter"- workCenterId={workCenterId}- fileRoutes={{- pdf: path.to.file.trackedEntityLabelPdf,- zpl: path.to.file.trackedEntityLabelZpl- }}- />- <Button- variant="secondary"- leftIcon={<LuArrowRightLeft />}- onClick={() => {- setTrackedEntity(split.newId);- convertDisclosure.onOpen();- }}- >- Convert- </Button>- <Button- variant="secondary"- leftIcon={<LuTrash />}- onClick={() => {- setTrackedEntity(split.newId);- scrapDisclosure.onOpen();- }}- >- Scrap- </Button>- </div>- </li>- ))}- </ul>- </div>- </AlertDescription>- </Alert>- </ModalBody>- ) : trackingType === "Inventory" ||- trackingType === "Non-Inventory" ||- trackingType === null ? (+ {trackingType === "Inventory" ||+ trackingType === "Non-Inventory" ||+ trackingType === null ? (// Untracked item (Inventory or Non-Inventory, e.g. consumables and// services) - use ValidatedForm; the issue edge function skips the// itemLedger for Non-Inventory items but still posts the WIP cost@@ -1635,7 +1585,12 @@ export function IssueMaterialModal({autoFocus={index === 0}value={batch.id}onChange={(e) => {- const newValue = e.target.value;+ // A shelf-label scan resolves to its+ // allocated lineside child (see+ // resolveScannedBatchId).+ const newValue = resolveScannedBatchId(+ e.target.value+ );updateBatchNumber({...batch,id: newValue@@ -1652,7 +1607,7 @@ export function IssueMaterialModal({}}onBlur={(e) => {validateBatchInput(- e.target.value,+ resolveScannedBatchId(e.target.value),index);}}@@ -1891,273 +1846,56 @@ export function IssueMaterialModal({</div></ModalBody><ModalFooter>- {splitEntitiesResult.length > 0 ? (- <Button variant="primary" size="lg" onClick={onClose}>- Close+ <Button variant="secondary" size="lg" onClick={onClose}>+ Cancel+ </Button>+ {activeTab === "unconsume" ? (+ <Button+ variant="destructive"+ size="lg"+ onClick={+ trackingType === "Serial"+ ? handleUnconsumeSerial+ : handleUnconsumeBatch+ }+ isLoading={unconsumeFetcher.state !== "idle"}+ isDisabled={+ unconsumeFetcher.state !== "idle" ||+ (trackingType === "Serial"+ ? selectedTrackedInputs.length === 0+ : !unconsumedBatch)+ }+ >+ Unconsume</Button>) : (- <>- <Button variant="secondary" size="lg" onClick={onClose}>- Cancel- </Button>- {activeTab === "unconsume" ? (- <Button- variant="destructive"- size="lg"- onClick={- trackingType === "Serial"- ? handleUnconsumeSerial- : handleUnconsumeBatch- }- isLoading={unconsumeFetcher.state !== "idle"}- isDisabled={- unconsumeFetcher.state !== "idle" ||- (trackingType === "Serial"- ? selectedTrackedInputs.length === 0- : !unconsumedBatch)- }- >- Unconsume- </Button>- ) : (- <Button- variant="primary"- size="lg"- onClick={- trackingType === "Serial"- ? handleSubmitSerial- : handleSubmitBatch- }- isLoading={fetcher.state !== "idle"}- isDisabled={- fetcher.state !== "idle" ||- !selectedItemId ||- isLoadingItem- }- >- Issue- </Button>- )}- </>+ <Button+ variant="primary"+ size="lg"+ onClick={+ trackingType === "Serial"+ ? handleSubmitSerial+ : handleSubmitBatch+ }+ isLoading={fetcher.state !== "idle"}+ isDisabled={+ fetcher.state !== "idle" ||+ !selectedItemId ||+ isLoadingItem+ }+ >+ Issue+ </Button>)}</ModalFooter></>)}-- {/* Footer for split entities result */}- {splitEntitiesResult.length > 0 && (- <ModalFooter>- <Button variant="primary" size="lg" onClick={onClose}>- Close- </Button>- </ModalFooter>- )}</ModalContent></Modal>-- {/* Sub-modals for batch splitting */}- {convertDisclosure.isOpen && (- <ConvertSplitModal- trackedEntity={trackedEntity}- itemType={material?.itemType ?? "Part"}- onCancel={() => {- convertDisclosure.onClose();- setTrackedEntity(null);- }}- onSuccess={(convertedEntity) => {- setSplitEntitiesResult((prev) =>- prev.map((entity) =>- entity.newId === convertedEntity.trackedEntityId- ? {- ...entity,- readableId: convertedEntity.readableId,- quantity: convertedEntity.quantity- }- : entity- )- );- convertDisclosure.onClose();- setTrackedEntity(null);- }}- />- )}- {scrapDisclosure.isOpen && (- <ScrapSplitModal- materialId={material?.id!}- parentTrackedEntityId={parentId ?? ""}- trackedEntity={trackedEntity}- onCancel={() => {- scrapDisclosure.onClose();- setTrackedEntity(null);- }}- onSuccess={() => {- scrapDisclosure.onClose();- setTrackedEntity(null);- onClose();- }}- />- )}</>);}-// Sub-modal for converting split batch entities-function ConvertSplitModal({- trackedEntity,- itemType,- onCancel,- onSuccess-}: {- trackedEntity: string | null;- itemType: string | null;- onCancel: () => void;- onSuccess: (convertedEntity: {- trackedEntityId: string;- readableId: string;- quantity: number;- }) => void;-}) {- const fetcher = useFetcher<{- success: boolean;- message: string;- convertedEntity?: {- trackedEntityId: string;- readableId: string;- quantity: number;- };- }>();-- useEffect(() => {- if (fetcher.data?.success && fetcher.data.convertedEntity) {- toast.success("Entity converted successfully");- onSuccess(fetcher.data.convertedEntity);- } else if (fetcher.data?.success === false) {- toast.error(fetcher.data.message || "Failed to convert entity");- }- }, [fetcher.data, onSuccess]);-- if (!trackedEntity) return null;-- return (- <Modal open onOpenChange={onCancel}>- <ModalContent>- <ModalHeader>- <ModalTitle>- Convert to New {itemType === "Material" ? "Size" : "Revision"}- </ModalTitle>- <ModalDescription>- Convert this tracked entity into a quantity of 1 of a new size.- </ModalDescription>- </ModalHeader>- <ValidatedForm- method="post"- action={path.to.convertEntity(trackedEntity)}- defaultValues={{- trackedEntityId: trackedEntity,- newRevision: "",- quantity: 1- }}- validator={convertEntityValidator}- fetcher={fetcher}- >- <Hidden name="trackedEntityId" />- <ModalBody>- <div className="flex flex-col gap-4">- <FormInput- name="newRevision"- label={`New ${itemType === "Material" ? "Size" : "Revision"}`}- autoFocus- />- <FormNumberInput- name="quantity"- label="Quantity"- minValue={0.001}- />- </div>- </ModalBody>- <ModalFooter>- <Button variant="secondary" size="lg" onClick={onCancel}>- Cancel- </Button>- <Button- isLoading={fetcher.state !== "idle"}- isDisabled={fetcher.state !== "idle"}- type="submit"- size="lg"- variant="primary"- >- Convert- </Button>- </ModalFooter>- </ValidatedForm>- </ModalContent>- </Modal>- );-}--// Sub-modal for scrapping split batch entities-function ScrapSplitModal({- materialId,- parentTrackedEntityId,- trackedEntity,- onCancel,- onSuccess-}: {- materialId: string;- parentTrackedEntityId: string;- trackedEntity: string | null;- onCancel: () => void;- onSuccess: () => void;-}) {- const fetcher = useFetcher<{ success: boolean; message: string }>();-- useEffect(() => {- if (fetcher.data?.success) {- onSuccess();- }- }, [fetcher.data?.success, onSuccess]);-- if (!trackedEntity) return null;-- return (- <Modal open onOpenChange={onCancel}>- <ModalContent>- <ModalHeader>- <ModalTitle>Are you sure you want to scrap this batch?</ModalTitle>- <ModalDescription>- The remaining quantity will be removed from inventory and issued to- the job- </ModalDescription>- </ModalHeader>- <ModalFooter>- <Button variant="secondary" size="lg" onClick={onCancel}>- Cancel- </Button>- <fetcher.Form- method="post"- action={path.to.scrapEntity(- materialId,- trackedEntity,- parentTrackedEntityId- )}- >- <Button- isLoading={fetcher.state !== "idle"}- isDisabled={fetcher.state !== "idle"}- type="submit"- size="lg"- variant="destructive"- >- Scrap- </Button>- </fetcher.Form>- </ModalFooter>- </ModalContent>- </Modal>- );-}--// Hook for fetching serial numbersfunction useSerialNumbers(itemId?: string) {const serialNumbersFetcher =useFetcher<Awaited<ReturnType<typeof getSerialNumbersForItem>>>();diff --git a/apps/mes/app/routes/x+/issue-tracked-entity.tsx b/apps/mes/app/routes/x+/issue-tracked-entity.tsxindex c516b95bae..b62d0a081e 100644--- a/apps/mes/app/routes/x+/issue-tracked-entity.tsx+++ b/apps/mes/app/routes/x+/issue-tracked-entity.tsx@@ -1,7 +1,6 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";@@ -78,42 +77,9 @@ export async function action({ request }: ActionFunctionArgs) {const splitEntities = issue.data?.splitEntities || [];const warning = issue.data?.warning as string | undefined;- // Auto-print labels for split entities- if (splitEntities.length > 0) {- try {- let locationId: string | undefined;- let workCenterId: string | undefined;- if (jobOperationId) {- const { data: op } = await serviceRole- .from("jobOperation")- .select("workCenterId")- .eq("id", jobOperationId)- .single();- workCenterId = op?.workCenterId ?? undefined;- }- if (workCenterId) {- const { data: wc } = await serviceRole- .from("workCenter")- .select("locationId")- .eq("id", workCenterId)- .single();- locationId = wc?.locationId ?? undefined;- }-- for (const split of splitEntities) {- await trigger("print-job", {- sourceDocument: "Split",- sourceDocumentId: split.newId,- companyId,- userId,- locationId,- workCenterId- });- }- } catch (e) {- log.error("Auto-print for split entities failed", { error: e });- }- }+ // No label print on issue: the split child is CONSUMED (it departed into the+ // job) and consumed portions get no label; the surviving lineside entity+ // keeps its existing label.return {success: true,diff --git a/apps/mes/app/services/allocation.ts b/apps/mes/app/services/allocation.tsindex b851462592..cfef23e472 100644--- a/apps/mes/app/services/allocation.ts+++ b/apps/mes/app/services/allocation.ts@@ -11,6 +11,12 @@ export type SuggestedAllocationLot = {expirationDate: string | null;storageUnitId: string | null;storageUnitName: string | null;+ /**+ * The shelf parent this lot was split from at pick time+ * ("Split From Entity ID"), when the source loads it. Lets the Issue modal+ * resolve a scanned shelf label to its allocated lineside child.+ */+ splitFromEntityId?: string | null;};export type PickMethodSortMethod = "Default" | "FEFO" | "FIFO" | "LIFO";diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.tsindex e791bb7ef1..38e662c56a 100644--- a/apps/mes/app/services/inventory.service.ts+++ b/apps/mes/app/services/inventory.service.ts@@ -405,9 +405,11 @@ export async function getPickedQuantitiesByJobMaterial(* as `getPickedQuantitiesByJobMaterial`: only "In Progress"/"Completed" lists, and* never a Cancelled line. Shaped as `SuggestedAllocationLot[]` so the Issue modal* can seed it through the same path the no-picking-list suggestion uses. On a- * partial-batch pick the original entity keeps the picked qty on the lineside- * shelf (still `Available`), so these ids are valid picker options. Never throws- * (returns []).+ * partial-batch pick the SHELF entity keeps its id and the allocation records the+ * departing CHILD staged at the lineside bin (Available, tagged+ * "Split From Entity ID" = shelf parent) — so these ids are the lineside lots the+ * operator actually consumes, and `splitFromEntityId` lets the Issue modal map a+ * scanned shelf label to its allocated child. Never throws (returns []).*/export async function getPickedTrackedEntitiesForMaterial(client: SupabaseClient<Database>,@@ -416,7 +418,7 @@ export async function getPickedTrackedEntitiesForMaterial(const { data, error } = await client.from("pickingListLine").select(- "companyId, pickingList!inner(status), pickingListLineTrackedEntity(trackedEntityId, quantityPicked, trackedEntity(readableId, expirationDate))"+ "companyId, pickingList!inner(status), pickingListLineTrackedEntity(trackedEntityId, quantityPicked, trackedEntity(readableId, expirationDate, attributes))").eq("jobMaterialId", args.jobMaterialId).eq("companyId", args.companyId)@@ -437,14 +439,17 @@ export async function getPickedTrackedEntitiesForMaterial(const entity = picked.trackedEntity as {readableId: string | null;expirationDate: string | null;+ attributes: Record<string, unknown> | null;} | null;+ const splitFrom = entity?.attributes?.["Split From Entity ID"];byEntity.set(picked.trackedEntityId, {trackedEntityId: picked.trackedEntityId,readableId: entity?.readableId ?? null,quantity,expirationDate: entity?.expirationDate ?? null,storageUnitId: null,- storageUnitName: null+ storageUnitName: null,+ splitFromEntityId: typeof splitFrom === "string" ? splitFrom : null});}}diff --git a/packages/database/supabase/functions/assign-serial-numbers/index.ts b/packages/database/supabase/functions/assign-serial-numbers/index.tsindex 484b1e7894..cbef7a0a8d 100644--- a/packages/database/supabase/functions/assign-serial-numbers/index.ts+++ b/packages/database/supabase/functions/assign-serial-numbers/index.ts@@ -85,8 +85,10 @@ serve(async (req: Request) => {// 5. The root make-method seed entity for this job. The job-insert// interceptor tags it with the Job id; sub-assembly seeds also carry a- // Job Material id, and consumption remainders carry a Split Entity ID —- // exclude both so we only touch the root make method's seed.+ // Job Material id, and split fragments carry a pointer key — the+ // legacy "Split Entity ID" (old convention: departed original) or+ // "Split From Entity ID" (new convention: split child). Exclude all+ // so we only touch the root make method's seed.const seeds = await trx.selectFrom("trackedEntity").selectAll()@@ -94,6 +96,7 @@ serve(async (req: Request) => {.where(sql<boolean>`attributes->>'Job' = ${jobId}`).where(sql<boolean>`attributes->>'Job Material' IS NULL`).where(sql<boolean>`attributes->>'Split Entity ID' IS NULL`)+ .where(sql<boolean>`attributes->>'Split From Entity ID' IS NULL`).orderBy("createdAt", "asc")// Lock the seed row for the duration of the transaction so concurrent// invocations for the same job serialize here: the second waits, thendiff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex 639c721b1e..1c700e2220 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -15,6 +15,7 @@ import { requirePermissions } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";import { TrackedEntityAttributes, credit, debit, journalReference } from "../lib/utils.ts";+import { buildBatchSplitRecords } from "../shared/batch-split.ts";import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";import { getNextSerialNumbers } from "../shared/get-next-serial-number.ts";@@ -2187,6 +2188,7 @@ serve(async (req: Request) => {newId: string;readableId: string;quantity: number;+ remainingQuantity: number;}> = [];// Process each child tracked entity@@ -2199,174 +2201,117 @@ serve(async (req: Request) => {}const { trackedEntityId, quantity } = child;- // If quantities don't match, split the batch+ // Partial consume → split: the lineside entity keeps its id and+ // is decremented; a NEW child entity carries the consumed+ // quantity. EVERYTHING below (Consumed status, Consume input,+ // 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) {- const remainingQuantity =- Number(trackedEntity.quantity) - quantity;- const newTrackedEntityId = nanoid();-- console.log("Split quantities:", {- childQuantity: Number(trackedEntity.quantity),- availableQuantity: quantity,- remainingQuantity,+ const consumedChildId = nanoid();+ consumedEntityId = consumedChildId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id!,+ readableId: trackedEntity.readableId,+ quantity: Number(trackedEntity.quantity),+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ itemId:+ trackedEntity.itemId ?? trackedEntity.sourceDocumentId,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null+ },+ drawQuantity: quantity,+ childId: consumedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Job Material",+ activitySourceDocumentId: actualMaterialId,+ bin: {+ storageUnitId: resolveTrackedEntityBin(+ itemLedgers,+ trackedEntityId+ ),+ locationId: job?.locationId ?? null+ },+ itemLedgerItemId: trackedEntity.sourceDocumentId,+ companyId,+ userId,+ postingDate: new Date().toISOString().slice(0, 10),+ // Created Available; the shared status update below flips the+ // child to Consumed in the same transaction.+ childStatus: "Available",+ extraChildAttributes: {+ ...(jobOperationStepId+ ? { "Job Operation Step": jobOperationStepId }+ : {}),+ ...(unitNumber !== undefined ? { Unit: unitNumber } : {})+ }});- // Track split entity for return+ // Track split entity for the MES confirmation: quantity = what+ // was consumed (the child), remainingQuantity = what the+ // surviving lineside entity still holds.splitEntities.push({originalId: trackedEntityId,- newId: newTrackedEntityId,+ newId: consumedChildId,readableId: trackedEntity.sourceDocumentReadableId ?? "",- quantity: remainingQuantity,+ quantity,+ remainingQuantity: split.parentUpdate.quantity,});- // Create split activity- const splitActivityId = nanoid();await trx.insertInto("trackedActivity")- .values({- id: splitActivityId,- type: "Split",- sourceDocument: "Job Material",- sourceDocumentId: actualMaterialId,- attributes: {- "Original Quantity": Number(trackedEntity.quantity),- "Consumed Quantity": quantity,- "Remaining Quantity": remainingQuantity,- "Split Entity ID": newTrackedEntityId,- },- companyId,- createdBy: userId,- })+ .values(split.activityInsert).execute();- // Record original entity as input- await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: trackedEntity.id!,- quantity: Number(trackedEntity.quantity),- companyId,- createdBy: userId,- })- .execute();-- // Create new tracked entity for remaining quantityawait trx.insertInto("trackedEntity")- .values({- id: newTrackedEntityId,- readableId: trackedEntity.readableId,- sourceDocumentId: trackedEntity.sourceDocumentId,- sourceDocument: "Item",- sourceDocumentReadableId:- trackedEntity.sourceDocumentReadableId,- quantity: remainingQuantity,- status: trackedEntity.status ?? "Available",- attributes: trackedEntity.attributes,- itemId: trackedEntity.itemId ?? trackedEntity.sourceDocumentId,- expirationDate: trackedEntity.expirationDate ?? null,- companyId,- createdBy: userId,- })+ .values(split.childEntityInsert).execute();- // Update original entity attributes with split referenceawait trx- .updateTable("trackedEntity")- .set({- quantity: quantity,- attributes: {- ...((trackedEntity.attributes as Record<string, unknown>) ??- {}),- "Split Entity ID": newTrackedEntityId,- },- })- .where("id", "=", trackedEntityId)+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert).execute();- // Record outputs from splitawait trx.insertInto("trackedActivityOutput")- .values([- {- trackedActivityId: splitActivityId!,- trackedEntityId: newTrackedEntityId!,- quantity: remainingQuantity,- companyId,- createdBy: userId,- },- {- trackedActivityId: splitActivityId!,- trackedEntityId: trackedEntity.id!,- quantity: quantity,- companyId,- createdBy: userId,- },- ])+ .values(split.activityOutputInsert).execute();- // Create item ledger entries for split- console.log("Item ledger split entries:", {- parentQuantity: -Number(trackedEntity.quantity),- quantity,- remainingQuantity,- });+ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", trackedEntityId)+ .execute();+ // MTO skips ONLY the ledger inserts; entity/activity writes+ // above still happen.if (jobMaterial?.methodType !== "Make to Order") {- itemLedgerInserts.push(- {- entryType: "Negative Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- companyId,- itemId: trackedEntity.sourceDocumentId,- quantity: -Number(trackedEntity.quantity),- locationId: job?.locationId,- storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),- trackedEntityId: trackedEntity.id!,- createdBy: userId,- },- {- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- companyId,- itemId: trackedEntity.sourceDocumentId,- quantity: quantity,- locationId: job?.locationId,- storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),- trackedEntityId: trackedEntity.id!,- createdBy: userId,- },- {- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- companyId,- itemId: trackedEntity.sourceDocumentId,- quantity: remainingQuantity,- locationId: job?.locationId,- storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),- trackedEntityId: newTrackedEntityId,- createdBy: userId,- }- );+ itemLedgerInserts.push(...split.ledgerInserts);}}- // Update tracked entity status to consumed+ // Consume the drawn entity — the split child, or the whole+ // entity on a full draw.await trx.updateTable("trackedEntity").set({status: "Consumed",})- .where("id", "=", trackedEntityId)+ .where("id", "=", consumedEntityId).execute();trackedActivityInputs.push({trackedActivityId: activityId,- trackedEntityId,+ trackedEntityId: consumedEntityId,quantity,companyId,createdBy: userId,@@ -2381,8 +2326,10 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: -quantity,locationId: job?.locationId,+ // The split child has no rows in the pre-transaction ledger+ // snapshot — it sits at the parent's resolved bin.storageUnitId: resolveTrackedEntityBin(itemLedgers, trackedEntityId),- trackedEntityId,+ trackedEntityId: consumedEntityId,createdBy: userId,});}@@ -3215,6 +3162,7 @@ serve(async (req: Request) => {newId: string;readableId: string;quantity: number;+ remainingQuantity: number;}> = [];// Process each child tracked entity@@ -3227,164 +3175,109 @@ serve(async (req: Request) => {}const { trackedEntityId, quantity } = child;- // If quantities don't match, split the batch+ // Book against the entity's ACTUAL bin (net on-hand), not an+ // arbitrary first ledger row — aligns with the job-consumption+ // path above.+ const entityBin = resolveTrackedEntityBin(+ itemLedgers,+ trackedEntityId+ );++ // Partial consume → split: the lineside entity keeps its id and+ // is decremented; a NEW child entity carries the consumed+ // quantity. EVERYTHING below (Consumed status, Consume input,+ // Maintenance Consumption ledger, junction row) books against+ // the child.+ let consumedEntityId = trackedEntityId;if (Number(trackedEntity.quantity) !== quantity) {- const remainingQuantity =- Number(trackedEntity.quantity) - quantity;- const newTrackedEntityId = nanoid();+ const consumedChildId = nanoid();+ consumedEntityId = consumedChildId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id!,+ readableId: trackedEntity.readableId,+ quantity: Number(trackedEntity.quantity),+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ itemId:+ trackedEntity.itemId ?? trackedEntity.sourceDocumentId,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null+ },+ drawQuantity: quantity,+ childId: consumedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Maintenance Dispatch Item",+ activitySourceDocumentId: maintenanceDispatchItemId,+ bin: {+ storageUnitId: entityBin,+ locationId+ },+ itemLedgerItemId: trackedEntity.sourceDocumentId,+ companyId,+ userId,+ postingDate: new Date().toISOString().slice(0, 10),+ // Created Available; the shared status update below flips the+ // child to Consumed in the same transaction.+ childStatus: "Available"+ });- // Track split entity for returnsplitEntities.push({originalId: trackedEntityId,- newId: newTrackedEntityId,+ newId: consumedChildId,readableId: trackedEntity.sourceDocumentReadableId ?? "",- quantity: remainingQuantity,+ quantity,+ remainingQuantity: split.parentUpdate.quantity,});- // Create split activity- const splitActivityId = nanoid();await trx.insertInto("trackedActivity")- .values({- id: splitActivityId,- type: "Split",- sourceDocument: "Maintenance Dispatch Item",- sourceDocumentId: maintenanceDispatchItemId,- attributes: {- "Original Quantity": Number(trackedEntity.quantity),- "Consumed Quantity": quantity,- "Remaining Quantity": remainingQuantity,- "Split Entity ID": newTrackedEntityId,- },- companyId,- createdBy: userId,- })+ .values(split.activityInsert).execute();- // Record original entity as input- await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: trackedEntity.id!,- quantity: Number(trackedEntity.quantity),- companyId,- createdBy: userId,- })- .execute();-- // Create new tracked entity for remaining quantityawait trx.insertInto("trackedEntity")- .values({- id: newTrackedEntityId,- readableId: trackedEntity.readableId,- sourceDocumentId: trackedEntity.sourceDocumentId,- sourceDocument: "Item",- sourceDocumentReadableId:- trackedEntity.sourceDocumentReadableId,- quantity: remainingQuantity,- status: trackedEntity.status ?? "Available",- attributes: trackedEntity.attributes,- itemId: trackedEntity.itemId ?? trackedEntity.sourceDocumentId,- expirationDate: trackedEntity.expirationDate ?? null,- companyId,- createdBy: userId,- })+ .values(split.childEntityInsert).execute();- // Update original entity quantityawait trx- .updateTable("trackedEntity")- .set({- quantity: quantity,- attributes: {- ...((trackedEntity.attributes as Record<string, unknown>) ??- {}),- "Split Entity ID": newTrackedEntityId,- },- })- .where("id", "=", trackedEntityId)+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert).execute();- // Record outputs from splitawait trx.insertInto("trackedActivityOutput")- .values([- {- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: remainingQuantity,- companyId,- createdBy: userId,- },- {- trackedActivityId: splitActivityId,- trackedEntityId: trackedEntity.id!,- quantity: quantity,- companyId,- createdBy: userId,- },- ])+ .values(split.activityOutputInsert).execute();- // Create item ledger entries for split- const existingLedger = itemLedgers.find(- (l) => l.trackedEntityId === trackedEntityId- );+ await trx+ .updateTable("trackedEntity")+ .set(split.parentUpdate)+ .where("id", "=", trackedEntityId)+ .execute();- itemLedgerInserts.push(- {- entryType: "Negative Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- companyId,- itemId: trackedEntity.sourceDocumentId,- quantity: -Number(trackedEntity.quantity),- locationId,- storageUnitId: existingLedger?.storageUnitId,- trackedEntityId: trackedEntity.id!,- createdBy: userId,- },- {- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- companyId,- itemId: trackedEntity.sourceDocumentId,- quantity: quantity,- locationId,- storageUnitId: existingLedger?.storageUnitId,- trackedEntityId: trackedEntity.id!,- createdBy: userId,- },- {- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- companyId,- itemId: trackedEntity.sourceDocumentId,- quantity: remainingQuantity,- locationId,- storageUnitId: existingLedger?.storageUnitId,- trackedEntityId: newTrackedEntityId,- createdBy: userId,- }- );+ itemLedgerInserts.push(...split.ledgerInserts);}- // Update tracked entity status to consumed+ // Consume the drawn entity — the split child, or the whole+ // entity on a full draw.await trx.updateTable("trackedEntity").set({status: "Consumed",})- .where("id", "=", trackedEntityId)+ .where("id", "=", consumedEntityId).execute();trackedActivityInputs.push({trackedActivityId: activityId,- trackedEntityId,+ trackedEntityId: consumedEntityId,quantity,companyId,createdBy: userId,@@ -3393,17 +3286,12 @@ serve(async (req: Request) => {// Add junction table entryjunctionInserts.push({maintenanceDispatchItemId,- trackedEntityId,+ trackedEntityId: consumedEntityId,quantity,companyId,createdBy: userId,});- // Create consumption item ledger entry- const existingLedger = itemLedgers.find(- (l) => l.trackedEntityId === trackedEntityId- );-itemLedgerInserts.push({entryType: "Consumption",documentType: "Maintenance Consumption",@@ -3413,8 +3301,10 @@ serve(async (req: Request) => {itemId: trackedEntity.sourceDocumentId,quantity: -quantity,locationId,- storageUnitId: existingLedger?.storageUnitId,- trackedEntityId,+ // The split child has no rows in the pre-transaction ledger+ // snapshot — it sits at the parent's resolved bin.+ storageUnitId: entityBin,+ trackedEntityId: consumedEntityId,createdBy: userId,});}diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.tsindex bb6ce9463f..ecf18994a6 100644--- a/packages/database/supabase/functions/lib/utils.ts+++ b/packages/database/supabase/functions/lib/utils.ts@@ -13,6 +13,7 @@ export interface TrackedEntityAttributes {"Shipment Line"?: string;Shipment?: string;"Split Entity ID"?: string;+ "Split From Entity ID"?: string;Shelf?: string;}diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.tsindex 3d936d2fe2..4ba56650dd 100644--- a/packages/database/supabase/functions/post-picking/index.ts+++ b/packages/database/supabase/functions/post-picking/index.ts@@ -3,9 +3,15 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { getLocalTimeZone, today as getToday } from "npm:@internationalized/date";import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";+import { sql } from "kysely";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import type { Database } from "../lib/types.ts";+import { resolveTrackedEntityBin } from "../issue/resolve-tracked-entity-bin.ts";+import {+ buildBatchSplitRecords,+ buildMergeRecords+} from "../shared/batch-split.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -400,133 +406,71 @@ serve(async (req: Request) => {const transferQuantity = quantity;const inserts: ItemLedgerInsert[] = [];- // Split the batch when picking less than the whole entity.+ // 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) {- const remainingQuantity = entityQuantity - transferQuantity;- const newTrackedEntityId = nanoid();- splitEntityId = newTrackedEntityId;+ const childId = nanoid();+ splitEntityId = childId;+ pickedEntityId = childId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id,+ readableId: trackedEntity.readableId,+ quantity: entityQuantity,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null+ },+ drawQuantity: transferQuantity,+ childId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Picking List",+ activitySourceDocumentId: pickingListId,+ bin: { storageUnitId: fromStorageUnitId, locationId },+ itemLedgerItemId: line.itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Available"+ });- const splitActivityId = nanoid();await trx.insertInto("trackedActivity")- .values({- id: splitActivityId,- type: "Split",- sourceDocument: "Picking List",- sourceDocumentId: pickingListId,- attributes: {- "Original Quantity": entityQuantity,- "Transfer Quantity": transferQuantity,- "Remaining Quantity": remainingQuantity,- "Split Entity ID": newTrackedEntityId- },- companyId,- createdBy: userId- })+ .values(split.activityInsert).execute();await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId,- quantity: entityQuantity,- companyId,- createdBy: userId- })+ .insertInto("trackedEntity")+ .values(split.childEntityInsert).execute();await trx- .insertInto("trackedEntity")- .values({- id: newTrackedEntityId,- readableId: trackedEntity.readableId,- sourceDocument: trackedEntity.sourceDocument,- sourceDocumentId: trackedEntity.sourceDocumentId,- sourceDocumentReadableId: trackedEntity.sourceDocumentReadableId,- quantity: remainingQuantity,- status: "Available",- attributes: trackedEntity.attributes,- itemId: trackedEntity.itemId ?? null,- expirationDate: trackedEntity.expirationDate ?? null,- companyId,- createdBy: userId- })+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert).execute();await trx.insertInto("trackedActivityOutput")- .values([- {- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: remainingQuantity,- companyId,- createdBy: userId- },- {- trackedActivityId: splitActivityId,- trackedEntityId,- quantity: transferQuantity,- companyId,- createdBy: userId- }- ])+ .values(split.activityOutputInsert).execute();await trx.updateTable("trackedEntity")- .set({- quantity: transferQuantity,- attributes: {- ...(trackedEntity.attributes as Record<string, unknown>),- "Split Entity ID": newTrackedEntityId- }- })+ .set(split.parentUpdate).where("id", "=", trackedEntityId).execute();- inserts.push(- {- postingDate: today,- itemId: line.itemId,- quantity: -entityQuantity,- locationId,- storageUnitId: fromStorageUnitId,- entryType: "Negative Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId,- createdBy: userId,- companyId- },- {- postingDate: today,- itemId: line.itemId,- quantity: transferQuantity,- locationId,- storageUnitId: fromStorageUnitId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId,- createdBy: userId,- companyId- },- {- postingDate: today,- itemId: line.itemId,- quantity: remainingQuantity,- locationId,- storageUnitId: fromStorageUnitId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: newTrackedEntityId,- createdBy: userId,- companyId- }- );+ inserts.push(...split.ledgerInserts);}const activityId = nanoid();@@ -552,7 +496,7 @@ serve(async (req: Request) => {.insertInto("trackedActivityInput").values({trackedActivityId: activityId,- trackedEntityId,+ trackedEntityId: pickedEntityId,quantity: transferQuantity,companyId,createdBy: userId@@ -570,7 +514,7 @@ serve(async (req: Request) => {entryType: "Transfer",documentType: "Direct Transfer",documentId: pickingListId,- trackedEntityId,+ trackedEntityId: pickedEntityId,createdBy: userId,companyId},@@ -583,7 +527,7 @@ serve(async (req: Request) => {entryType: "Transfer",documentType: "Direct Transfer",documentId: pickingListId,- trackedEntityId,+ trackedEntityId: pickedEntityId,createdBy: userId,companyId}@@ -605,12 +549,14 @@ serve(async (req: Request) => {.execute();// Record which lot this line picked (drives picked-lot display,- // unpick, and the picker's allocation-dedup).+ // unpick, and the picker's allocation-dedup). On a split the picked+ // lot is the departing CHILD — the lineside entity the operator+ // consumes — never the shelf survivor.await trx.insertInto("pickingListLineTrackedEntity").values({pickingListLineId,- trackedEntityId,+ trackedEntityId: pickedEntityId,quantity: transferQuantity,quantityPicked: transferQuantity})@@ -633,8 +579,7 @@ serve(async (req: Request) => {break;}- case "unpickSerial":- case "unpickBatch": {+ case "unpickSerial": {const {pickingListId,pickingListLineId,@@ -742,6 +687,237 @@ serve(async (req: Request) => {break;}+ case "unpickBatch": {+ const {+ pickingListId,+ pickingListLineId,+ trackedEntityId,+ locationId,+ userId,+ companyId+ } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ const line = await trx+ .selectFrom("pickingListLine")+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ const trackedEntity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", trackedEntityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ // The unpick quantity is what THIS line picked of the entity — from+ // the allocation row, never trackedEntity.quantity: post-flip the+ // allocated entity is the departing child, and once consumption+ // starts its current quantity no longer equals what was picked.+ const allocation = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .selectAll()+ .executeTakeFirst();++ if (!allocation) {+ throw new Error(+ `Cannot unpick batch: no allocation row for picking list line ${pickingListLineId} and tracked entity ${trackedEntityId}`+ );+ }++ const unpickQuantity = Number(allocation.quantityPicked);++ const activity = await trx+ .selectFrom("trackedActivity")+ .innerJoin(+ "trackedActivityInput",+ "trackedActivity.id",+ "trackedActivityInput.trackedActivityId"+ )+ .where("trackedActivity.type", "=", "Pick")+ .where("trackedActivity.sourceDocument", "=", "Picking List")+ .where("trackedActivity.sourceDocumentId", "=", pickingListId)+ .where("trackedActivityInput.trackedEntityId", "=", trackedEntityId)+ .where("trackedActivity.companyId", "=", companyId)+ .selectAll("trackedActivity")+ .executeTakeFirstOrThrow();++ // Reverse the Transfer pair at the picked magnitude.+ const inserts: ItemLedgerInsert[] = [+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: -unpickQuantity,+ locationId,+ storageUnitId: line.toStorageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: unpickQuantity,+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ }+ ];++ // Merge-back undo: post-flip the picked entity is a Split child+ // whose parent stayed on the shelf. Fold the quantity back into the+ // parent and delete the Split so genealogy reads as if the pick+ // never happened. Legacy allocations (no Split From pointer, or a+ // parent that no longer matches) skip this — the entity simply+ // returns to the source bin as its own lot, today's behavior.+ const attrs = (trackedEntity.attributes ?? {}) as Record<+ string,+ unknown+ >;+ const parentId = attrs["Split From Entity ID"];+ if (typeof parentId === "string" && parentId) {+ const parent = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", parentId)+ .where("companyId", "=", companyId)+ .selectAll()+ .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`+ );+ }++ const splitActivity = await trx+ .selectFrom("trackedActivity")+ .where("type", "=", "Split")+ .where(+ sql<boolean>`attributes->>'Split Entity ID' = ${trackedEntityId}`+ )+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ await trx+ .updateTable("trackedEntity")+ .set({ quantity: Number(parent.quantity) + unpickQuantity })+ .where("id", "=", parent.id)+ .execute();++ await trx+ .updateTable("trackedEntity")+ .set(+ childRemaining === 0+ ? { quantity: 0, status: "Consumed" }+ : { quantity: childRemaining }+ )+ .where("id", "=", trackedEntityId)+ .execute();++ // Net out the original split pair at the source bin. Keep the+ // child's entity row — itemLedger.trackedEntityId history stays+ // intact (the FK is ON DELETE SET NULL; deleting would null it).+ inserts.push(+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: -unpickQuantity,+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivity?.id ?? pickingListId,+ trackedEntityId,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: unpickQuantity,+ locationId,+ storageUnitId: line.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivity?.id ?? pickingListId,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId+ }+ );++ // Clean undo: the Split never happened.+ if (splitActivity) {+ await trx+ .deleteFrom("trackedActivityOutput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .execute();+ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .execute();+ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", splitActivity.id!)+ .execute();+ }+ }+ }++ await trx.insertInto("itemLedger").values(inserts).execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", activity.id!)+ .execute();+ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", activity.id!)+ .execute();++ await trx+ .updateTable("pickingListLine")+ .set({+ quantityPicked: Math.max(+ 0,+ Number(line.quantityPicked ?? 0) - unpickQuantity+ ),+ status: "Pending",+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", pickingListLineId)+ .where("companyId", "=", companyId)+ .execute();++ // Drop the recorded lot so it's pickable again + display clears.+ await trx+ .deleteFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", pickingListLineId)+ .where("trackedEntityId", "=", trackedEntityId)+ .execute();++ await restoreJobMaterialSource(trx, line, userId);+ });+ break;+ }+case "returnPickedRemainder": {const { pickingListLineId, trackedEntityId, locationId, userId, companyId } =validatedPayload;@@ -1025,8 +1201,11 @@ async function returnTrackedAllocationRemainder(frontier = next;}- // Transfer each lineage entity's remaining lineside on-hand back to- // the warehouse source bin.+ // Transfer each lineage entity's remaining lineside on-hand back to the+ // warehouse source bin. A split child whose parent still sits Available at+ // the source bin MERGES back into the parent (no standalone fragment);+ // anything ineligible falls back to today's standalone return — never+ // block a return on merge eligibility.const inserts: ItemLedgerInsert[] = [];let totalReturned = 0;for (const entityId of lineage) {@@ -1040,20 +1219,124 @@ async function returnTrackedAllocationRemainder(.executeTakeFirst();const onHand = Number(onHandRow?.qty ?? 0);if (onHand <= 0) continue;- inserts.push(- ...transferPair({- today,- itemId: line.itemId,- quantity: onHand,- locationId,- fromStorageUnitId: lineside,- toStorageUnitId: source,- documentId: line.pickingListId,- trackedEntityId: entityId,- userId,- companyId- })- );++ const entity = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", entityId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();+ const parentId = ((entity?.attributes ?? {}) as Record<string, unknown>)[+ "Split From Entity ID"+ ];++ let merged = false;+ if (entity && typeof parentId === "string" && parentId) {+ const parent = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", parentId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (+ parent &&+ parent.status === "Available" &&+ parent.readableId === entity.readableId &&+ onHand <= Number(entity.quantity)+ ) {+ const parentLedgers = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", parent.id)+ .where("companyId", "=", companyId)+ .select(["trackedEntityId", "storageUnitId", "quantity"])+ .execute();++ if (resolveTrackedEntityBin(parentLedgers, parent.id) === source) {+ const merge = buildMergeRecords({+ child: { id: entity.id, quantity: Number(entity.quantity) },+ parent: { id: parent.id, quantity: Number(parent.quantity) },+ mergeQuantity: onHand,+ mergeActivityId: nanoid(),+ companyId,+ userId+ });++ // Physical move: −r on the child at lineside, +r on the parent at+ // the source bin — same Transfer shape the sweep books today.+ inserts.push(+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: -onHand,+ locationId,+ storageUnitId: lineside,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: line.pickingListId,+ trackedEntityId: entity.id,+ createdBy: userId,+ companyId+ },+ {+ postingDate: today,+ itemId: line.itemId,+ quantity: onHand,+ locationId,+ storageUnitId: source,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: line.pickingListId,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId+ }+ );++ await trx+ .insertInto("trackedActivity")+ .values(merge.activityInsert)+ .execute();+ await trx+ .insertInto("trackedActivityInput")+ .values(merge.activityInputInsert)+ .execute();+ await trx+ .insertInto("trackedActivityOutput")+ .values(merge.activityOutputInsert)+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set(merge.parentUpdate)+ .where("id", "=", parent.id)+ .execute();+ await trx+ .updateTable("trackedEntity")+ .set(merge.childUpdate)+ .where("id", "=", entity.id)+ .execute();++ merged = true;+ }+ }+ }++ if (!merged) {+ inserts.push(+ ...transferPair({+ today,+ itemId: line.itemId,+ quantity: onHand,+ locationId,+ fromStorageUnitId: lineside,+ toStorageUnitId: source,+ documentId: line.pickingListId,+ trackedEntityId: entityId,+ userId,+ companyId+ })+ );+ }totalReturned += onHand;}diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.tsindex ea857187f5..5c1cc9a523 100644--- a/packages/database/supabase/functions/post-shipment/index.ts+++ b/packages/database/supabase/functions/post-shipment/index.ts@@ -7,6 +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 { calculateCOGS } from "../shared/calculate-cogs.ts";import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";@@ -740,7 +741,10 @@ serve(async (req: Request) => {trackedEntity.quantity !== undefined &&shipmentLine.shippedQuantity < trackedEntity.quantity) {- // Need to split the batch+ // Partial shipment → split. The shelf entity keeps its id+ // and is only decremented (split loop below); the SHIPPED+ // portion departs as a new Consumed child. No Consumed+ // update on the parent here.trackedEntitySplits[trackedEntity.id] = {originalEntityId: trackedEntity.id,originalQuantity: trackedEntity.quantity,@@ -758,6 +762,7 @@ serve(async (req: Request) => {itemId: trackedEntity.itemId ?? null,expirationDate: trackedEntity.expirationDate ?? null,};+ return acc;}acc[trackedEntity.id] = {@@ -843,7 +848,10 @@ serve(async (req: Request) => {.where("id", "=", shipmentId).execute();- if (Object.keys(trackedEntityUpdates).length > 0) {+ if (+ Object.keys(trackedEntityUpdates).length > 0 ||+ Object.keys(trackedEntitySplits).length > 0+ ) {const trackedActivity = await trx.insertInto("trackedActivity").values({@@ -864,214 +872,133 @@ serve(async (req: Request) => {const trackedActivityId = trackedActivity[0].id;- // Handle batch splits first+ // Handle batch splits first: the shelf entity keeps its id+ // and is decremented; the SHIPPED portion departs as a new+ // Consumed child carrying the shipment attributes.for await (const splitInfo of Object.values(trackedEntitySplits)) {- // Create a split activity- const splitActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Split",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- "Original Quantity": splitInfo.originalQuantity,- "Shipped Quantity": splitInfo.shippedQuantity,- "Remaining Quantity": splitInfo.remainingQuantity,- },- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();-- const splitActivityId = splitActivity[0].id!;+ const shipmentLine = shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );- // Record the original entity as input to the split- await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.originalQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .execute();+ const shippedChildId = nanoid();+ const parentAttributes = (splitInfo.attributes ??+ {}) as Record<string, unknown>;- // Create a new tracked entity for the remaining quantity- const newTrackedEntity = await trx- .insertInto("trackedEntity")- .values({+ const split = buildBatchSplitRecords({+ parent: {+ id: splitInfo.originalEntityId,readableId: splitInfo.readableId,- quantity: splitInfo.remainingQuantity,- status: "Available",+ quantity: splitInfo.originalQuantity,sourceDocument: splitInfo.sourceDocument,sourceDocumentId: splitInfo.sourceDocumentId,sourceDocumentReadableId:splitInfo.sourceDocumentReadableId,- attributes: splitInfo.attributes as unknown as Json,itemId: splitInfo.itemId,expirationDate: splitInfo.expirationDate,- companyId: splitInfo.companyId,- createdBy: userId,+ attributes: parentAttributes,+ },+ drawQuantity: splitInfo.shippedQuantity,+ childId: shippedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Shipment",+ activitySourceDocumentId: shipmentId,+ bin: {+ storageUnitId: shipmentLine?.storageUnitId ?? null,+ locationId,+ },+ itemLedgerItemId: shipmentLine?.itemId ?? null,+ companyId: splitInfo.companyId,+ userId,+ postingDate: today,+ childStatus: "Consumed",+ });++ await trx+ .insertInto("trackedActivity")+ .values({+ ...split.activityInsert,+ attributes: split.activityInsert+ .attributes as unknown as Json,+ sourceDocumentReadableId: shipment.data.shipmentId,createdAt: today,})- .returning(["id"]).execute();- const newTrackedEntityId = newTrackedEntity[0].id!;- splitEntityIds.push(newTrackedEntityId);-- // Update the original entity's attributes to include the split entity ID- const originalEntity = await trx- .selectFrom("trackedEntity")- .select(["attributes"])- .where("id", "=", splitInfo.originalEntityId)- .executeTakeFirst();-- if (originalEntity) {- const updatedAttributes = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- "Split Entity ID": newTrackedEntityId,- };-- // Remove Shipment and Shipment Line attributes from the new entity- const updatedAttributesObj = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- };-- // Delete shipment-related attributes- delete updatedAttributesObj["Shipment"];- delete updatedAttributesObj["Shipment Line"];- delete updatedAttributesObj["Shipment Line Index"];-- // Add the split entity reference- updatedAttributesObj["Split Entity ID"] =- newTrackedEntityId;-- // Update the original entity with the reference to the new split entity- await trx- .updateTable("trackedEntity")- .set({- attributes: updatedAttributes,- })- .where("id", "=", splitInfo.originalEntityId)- .execute();- }-- // Record the new entity as output from the splitawait trx- .insertInto("trackedActivityOutput")+ .insertInto("trackedEntity").values({- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: splitInfo.remainingQuantity,- companyId: splitInfo.companyId,- createdBy: userId,+ ...split.childEntityInsert,+ attributes: split.childEntityInsert+ .attributes as unknown as Json,createdAt: today,}).execute();- // Record the shipped portion as output (will be consumed by shipment)+ await trx+ .insertInto("trackedActivityInput")+ .values({ ...split.activityInputInsert, createdAt: today })+ .execute();+await trx.insertInto("trackedActivityOutput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.shippedQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ .values({ ...split.activityOutputInsert, createdAt: today })+ .execute();++ // The retained parent is only decremented and LOSES the+ // shipment attributes — they belong to the shipped child.+ const retainedAttributes = { ...parentAttributes };+ delete retainedAttributes["Shipment"];+ delete retainedAttributes["Shipment Line"];+ delete retainedAttributes["Shipment Line Index"];++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: split.parentUpdate.quantity,+ attributes: retainedAttributes as unknown as Json,})+ .where("id", "=", splitInfo.originalEntityId).execute();- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.itemId!,- quantity: -splitInfo.originalQuantity,- locationId: locationId,- storageUnitId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.storageUnitId,- entryType: "Negative Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- createdBy: userId,- companyId,- });+ itemLedgerInserts.push(...split.ledgerInserts);- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.itemId!,- quantity: splitInfo.shippedQuantity,- locationId: locationId,- storageUnitId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.storageUnitId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- createdBy: userId,- companyId,- });+ // The shipment's own ledger rows (built per line above)+ // and its activity input book against the shipped child.+ for (const ledger of itemLedgerInserts) {+ if (+ ledger.documentType === "Sales Shipment" &&+ ledger.trackedEntityId === splitInfo.originalEntityId+ ) {+ ledger.trackedEntityId = shippedChildId;+ }+ }- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.itemId!,- quantity: splitInfo.remainingQuantity,- locationId: locationId,- storageUnitId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.storageUnitId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: newTrackedEntityId,- createdBy: userId,- companyId,- });+ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: shippedChildId,+ quantity: splitInfo.shippedQuantity,+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }++ // Auto-print/labels retarget to the RETAINED parent (its+ // quantity changed); the shipped child needs no label.+ splitEntityIds.push(splitInfo.originalEntityId);}- // Now handle the shipment consumption+ // Now handle the shipment consumption (full-quantity lots)for await (const [id, update] of Object.entries(trackedEntityUpdates)) {@@ -1453,7 +1380,10 @@ serve(async (req: Request) => {trackedEntity.quantity !== undefined &&shipmentLine.shippedQuantity < trackedEntity.quantity) {- // Need to split the batch+ // Partial shipment → split. The shelf entity keeps its id+ // and is only decremented (split loop below); the SHIPPED+ // portion departs as a new Consumed child. No update on+ // the parent here.trackedEntitySplits[trackedEntity.id] = {originalEntityId: trackedEntity.id,originalQuantity: trackedEntity.quantity,@@ -1471,6 +1401,7 @@ serve(async (req: Request) => {itemId: trackedEntity.itemId ?? null,expirationDate: trackedEntity.expirationDate ?? null,};+ return acc;}acc[trackedEntity.id] = {@@ -1502,7 +1433,10 @@ serve(async (req: Request) => {.where("id", "=", shipmentId).execute();- if (Object.keys(trackedEntityUpdates).length > 0) {+ if (+ Object.keys(trackedEntityUpdates).length > 0 ||+ Object.keys(trackedEntitySplits).length > 0+ ) {const trackedActivity = await trx.insertInto("trackedActivity").values({@@ -1523,136 +1457,123 @@ serve(async (req: Request) => {const trackedActivityId = trackedActivity[0].id;- // Handle batch splits first+ // Handle batch splits first: the shelf entity keeps its id+ // and is decremented; the SHIPPED portion departs as a new+ // Consumed child carrying the shipment attributes. This PO-+ // sourced path posts NO itemLedger for the split (matching the+ // pre-flip behavior — a PO/subcontract shipment's inventory+ // movement is not booked here); only genealogy + quantities.for await (const splitInfo of Object.values(trackedEntitySplits)) {- // Create a split activity- const splitActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Split",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- "Original Quantity": splitInfo.originalQuantity,- "Shipped Quantity": splitInfo.shippedQuantity,- "Remaining Quantity": splitInfo.remainingQuantity,- },- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();-- const splitActivityId = splitActivity[0].id!;+ const shipmentLine = shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );- // Record the original entity as input to the split- await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.originalQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .execute();+ const shippedChildId = nanoid();+ const parentAttributes = (splitInfo.attributes ??+ {}) as Record<string, unknown>;- // Create a new tracked entity for the remaining quantity- const newTrackedEntity = await trx- .insertInto("trackedEntity")- .values({+ const split = buildBatchSplitRecords({+ parent: {+ id: splitInfo.originalEntityId,readableId: splitInfo.readableId,- quantity: splitInfo.remainingQuantity,- status: "Available",+ quantity: splitInfo.originalQuantity,sourceDocument: splitInfo.sourceDocument,sourceDocumentId: splitInfo.sourceDocumentId,sourceDocumentReadableId:splitInfo.sourceDocumentReadableId,- attributes: splitInfo.attributes as unknown as Json,itemId: splitInfo.itemId,expirationDate: splitInfo.expirationDate,- companyId: splitInfo.companyId,- createdBy: userId,+ attributes: parentAttributes,+ },+ drawQuantity: splitInfo.shippedQuantity,+ childId: shippedChildId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Shipment",+ activitySourceDocumentId: shipmentId,+ bin: {+ storageUnitId: shipmentLine?.storageUnitId ?? null,+ locationId: shipment.data.locationId,+ },+ itemLedgerItemId: shipmentLine?.itemId ?? null,+ companyId: splitInfo.companyId,+ userId,+ postingDate: today,+ childStatus: "Consumed",+ });++ await trx+ .insertInto("trackedActivity")+ .values({+ ...split.activityInsert,+ attributes: split.activityInsert+ .attributes as unknown as Json,+ sourceDocumentReadableId: shipment.data.shipmentId,createdAt: today,})- .returning(["id"]).execute();- const newTrackedEntityId = newTrackedEntity[0].id!;- splitEntityIds.push(newTrackedEntityId);-- // Update the original entity's attributes to include the split entity ID- const originalEntity = await trx- .selectFrom("trackedEntity")- .select(["attributes"])- .where("id", "=", splitInfo.originalEntityId)- .executeTakeFirst();-- if (originalEntity) {- const updatedAttributes = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- "Split Entity ID": newTrackedEntityId,- };-- // Remove Shipment and Shipment Line attributes from the new entity- const updatedAttributesObj = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- };-- // Delete shipment-related attributes- delete updatedAttributesObj["Shipment"];- delete updatedAttributesObj["Shipment Line"];- delete updatedAttributesObj["Shipment Line Index"];-- // Add the split entity reference- updatedAttributesObj["Split Entity ID"] =- newTrackedEntityId;-- // Update the original entity with the reference to the new split entity- await trx- .updateTable("trackedEntity")- .set({- attributes: updatedAttributes,- })- .where("id", "=", splitInfo.originalEntityId)- .execute();- }-- // Record the new entity as output from the splitawait trx- .insertInto("trackedActivityOutput")+ .insertInto("trackedEntity").values({- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: splitInfo.remainingQuantity,- companyId: splitInfo.companyId,- createdBy: userId,+ ...split.childEntityInsert,+ attributes: split.childEntityInsert+ .attributes as unknown as Json,createdAt: today,}).execute();- // Record the shipped portion as output (will be consumed by shipment)+ await trx+ .insertInto("trackedActivityInput")+ .values({ ...split.activityInputInsert, createdAt: today })+ .execute();+await trx.insertInto("trackedActivityOutput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.shippedQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ .values({ ...split.activityOutputInsert, createdAt: today })+ .execute();++ // The retained parent is only decremented and LOSES the+ // shipment attributes — they belong to the shipped child.+ const retainedAttributes = { ...parentAttributes };+ delete retainedAttributes["Shipment"];+ delete retainedAttributes["Shipment Line"];+ delete retainedAttributes["Shipment Line Index"];++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: split.parentUpdate.quantity,+ attributes: retainedAttributes as unknown as Json,})+ .where("id", "=", splitInfo.originalEntityId).execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: shippedChildId,+ quantity: splitInfo.shippedQuantity,+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }++ // Auto-print/labels retarget to the RETAINED parent (its+ // quantity changed); the shipped child needs no label.+ splitEntityIds.push(splitInfo.originalEntityId);}- // Now handle the shipment consumption+ // Now handle the shipment consumption (full-quantity lots)for await (const [id, update] of Object.entries(trackedEntityUpdates)) {diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.tsindex 60a7bae6fb..d761aa9555 100644--- a/packages/database/supabase/functions/post-stock-transfer/index.ts+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts@@ -3,9 +3,11 @@ import { format } from "https://deno.land/[email protected]/datetime/mod.ts";import { getLocalTimeZone, parseDate, today } from "npm:@internationalized/date";import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";import { z } from "https://deno.land/x/[email protected]/mod.ts";+import { sql } from "kysely";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";import type { Database } from "../lib/types.ts";+import { buildBatchSplitRecords } from "../shared/batch-split.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -451,141 +453,71 @@ serve(async (req: Request) => {const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =[];- // Handle batch splitting if needed+ // Split the batch when transferring less than the whole entity: the+ // 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) {- // Need to split the batch- const remainingQuantity = entityQuantity - transferQuantity;- const newTrackedEntityId = nanoid();- splitEntityId = newTrackedEntityId;+ const childId = nanoid();+ splitEntityId = childId;+ transferredEntityId = childId;++ const split = buildBatchSplitRecords({+ parent: {+ id: trackedEntity.id,+ readableId: trackedEntity.readableId,+ quantity: entityQuantity,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ itemId: trackedEntity.itemId ?? null,+ expirationDate: trackedEntity.expirationDate ?? null,+ attributes: trackedEntity.attributes as Record<+ string,+ unknown+ > | null,+ },+ drawQuantity: transferQuantity,+ childId,+ splitActivityId: nanoid(),+ activitySourceDocument: "Stock Transfer",+ activitySourceDocumentId: stockTransferId,+ bin: { storageUnitId: fromStorageUnitId, locationId },+ itemLedgerItemId: stockTransferLine.itemId,+ companyId,+ userId,+ postingDate: today,+ childStatus: "Available",+ });- // Create split activity- const splitActivityId = nanoid();await trx.insertInto("trackedActivity")- .values({- id: splitActivityId,- type: "Split",- sourceDocument: "Stock Transfer",- sourceDocumentId: stockTransferId,- attributes: {- "Original Quantity": entityQuantity,- "Transfer Quantity": transferQuantity,- "Remaining Quantity": remainingQuantity,- "Split Entity ID": newTrackedEntityId,- },- companyId,- createdBy: userId,- })+ .values(split.activityInsert).execute();- // Record original entity as input to splitawait trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: trackedEntityId,- quantity: entityQuantity,- companyId,- createdBy: userId,- })+ .insertInto("trackedEntity")+ .values(split.childEntityInsert).execute();- // Create new tracked entity for remaining quantityawait trx- .insertInto("trackedEntity")- .values({- id: newTrackedEntityId,- readableId: trackedEntity.readableId,- sourceDocument: trackedEntity.sourceDocument,- sourceDocumentId: trackedEntity.sourceDocumentId,- sourceDocumentReadableId:- trackedEntity.sourceDocumentReadableId,- quantity: remainingQuantity,- status: "Available",- attributes: trackedEntity.attributes,- itemId: trackedEntity.itemId ?? null,- expirationDate: trackedEntity.expirationDate ?? null,- companyId,- createdBy: userId,- })+ .insertInto("trackedActivityInput")+ .values(split.activityInputInsert).execute();- // Record outputs from splitawait trx.insertInto("trackedActivityOutput")- .values([- {- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: remainingQuantity,- companyId,- createdBy: userId,- },- {- trackedActivityId: splitActivityId,- trackedEntityId: trackedEntityId,- quantity: transferQuantity,- companyId,- createdBy: userId,- },- ])+ .values(split.activityOutputInsert).execute();- // Update original entity with split reference and new quantityawait trx.updateTable("trackedEntity")- .set({- quantity: transferQuantity,- attributes: {- ...(trackedEntity.attributes as Record<string, unknown>),- "Split Entity ID": newTrackedEntityId,- },- })+ .set(split.parentUpdate).where("id", "=", trackedEntityId).execute();- // Create item ledger entries for split- itemLedgerInserts.push(- {- postingDate: today,- itemId: stockTransferLine.itemId,- quantity: -entityQuantity,- locationId: locationId,- storageUnitId: fromStorageUnitId,- entryType: "Negative Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: trackedEntityId,- createdBy: userId,- companyId,- },- {- postingDate: today,- itemId: stockTransferLine.itemId,- quantity: transferQuantity,- locationId: locationId,- storageUnitId: fromStorageUnitId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: trackedEntityId,- createdBy: userId,- companyId,- },- {- postingDate: today,- itemId: stockTransferLine.itemId,- quantity: remainingQuantity,- locationId: locationId,- storageUnitId: fromStorageUnitId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: newTrackedEntityId,- createdBy: userId,- companyId,- }- );+ itemLedgerInserts.push(...split.ledgerInserts);}// Create transfer activity@@ -612,12 +544,13 @@ serve(async (req: Request) => {}).execute();- // Record tracked entity as input to transfer+ // Record the DEPARTING entity (split child, or the whole entity on+ // a full-quantity transfer) as input to the transfer.await trx.insertInto("trackedActivityInput").values({trackedActivityId: transferActivityId,- trackedEntityId: trackedEntityId,+ trackedEntityId: transferredEntityId,quantity: transferQuantity,companyId,createdBy: userId,@@ -638,7 +571,7 @@ serve(async (req: Request) => {entryType: "Transfer",documentType: "Direct Transfer",documentId: stockTransferId,- trackedEntityId: trackedEntityId,+ trackedEntityId: transferredEntityId,createdBy: userId,companyId,},@@ -651,7 +584,7 @@ serve(async (req: Request) => {entryType: "Transfer",documentType: "Direct Transfer",documentId: stockTransferId,- trackedEntityId: trackedEntityId,+ trackedEntityId: transferredEntityId,createdBy: userId,companyId,}@@ -665,11 +598,12 @@ serve(async (req: Request) => {.execute();}- // Update stock transfer line with picked quantity+ // Update stock transfer line with picked quantity — the line+ // references the entity that physically arrives at the destination.await trx.updateTable("stockTransferLine").set({- trackedEntityId,+ trackedEntityId: transferredEntityId,fromStorageUnitId: fromStorageUnitId,pickedQuantity: transferQuantity,updatedBy: userId,@@ -859,16 +793,114 @@ serve(async (req: Request) => {const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =[];- // Check if this entity was created from a split operation- const splitEntityId = (- trackedEntity.attributes as Record<string, unknown>- )?.["Split Entity ID"] as string | undefined;+ const entityAttributes = (trackedEntity.attributes ?? {}) as Record<+ string,+ unknown+ >;+ // New convention: the line's entity is a split CHILD carrying a+ // back-pointer to the parent that stayed at the source bin.+ const splitFromParentId = entityAttributes["Split From Entity ID"] as+ | string+ | undefined;+ // Legacy convention (pre-flip rows): the departed ORIGINAL carries a+ // forward pointer to the remainder entity it left behind.+ const legacyRemainderId = entityAttributes["Split Entity ID"] as+ | string+ | undefined;++ if (splitFromParentId) {+ // Merge the child fully back into its parent and delete the Split+ // — a clean undo, as if the partial transfer never happened.+ const parent = await trx+ .selectFrom("trackedEntity")+ .where("id", "=", splitFromParentId)+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirstOrThrow();++ await trx+ .updateTable("trackedEntity")+ .set({+ quantity: Number(parent.quantity) + transferQuantity,+ })+ .where("id", "=", parent.id)+ .execute();++ // Drain the child (don't delete it — ledger history keeps the FK).+ await trx+ .updateTable("trackedEntity")+ .set({+ status: "Consumed",+ quantity: 0,+ })+ .where("id", "=", trackedEntityId)+ .execute();++ itemLedgerInserts.push(+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: -transferQuantity, // drain the child at the destination+ locationId: locationId,+ storageUnitId: stockTransferLine.toStorageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: trackedEntityId,+ createdBy: userId,+ companyId,+ },+ {+ postingDate: today,+ itemId: stockTransferLine.itemId,+ quantity: transferQuantity, // restore the parent at the source+ locationId: locationId,+ storageUnitId: stockTransferLine.fromStorageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Direct Transfer",+ documentId: stockTransferId!,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId,+ }+ );++ // Delete the Split activity that minted the child — scoped to the+ // entity AND this transfer (a bare sourceDocumentId lookup grabs+ // a sibling line's split on multi-line transfers).+ const splitActivity = await trx+ .selectFrom("trackedActivity")+ .where("type", "=", "Split")+ .where("sourceDocument", "=", "Stock Transfer")+ .where("sourceDocumentId", "=", stockTransferId)+ .where(+ sql<boolean>`attributes->>'Split Entity ID' = ${trackedEntityId}`+ )+ .where("companyId", "=", companyId)+ .selectAll()+ .executeTakeFirst();++ if (splitActivity) {+ await trx+ .deleteFrom("trackedActivityOutput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .execute();++ await trx+ .deleteFrom("trackedActivityInput")+ .where("trackedActivityId", "=", splitActivity.id!)+ .execute();- if (splitEntityId) {+ await trx+ .deleteFrom("trackedActivity")+ .where("id", "=", splitActivity.id!)+ .execute();+ }+ } else if (legacyRemainderId) {// This entity was created from a split, need to merge it backconst originalEntity = await trx.selectFrom("trackedEntity")- .where("id", "=", splitEntityId)+ .where("id", "=", legacyRemainderId).where("companyId", "=", companyId).selectAll().executeTakeFirstOrThrow();@@ -876,16 +908,16 @@ serve(async (req: Request) => {const originalQuantity =Number(originalEntity.quantity) + transferQuantity;- const remainingQuantity = (- trackedEntity.attributes as Record<string, unknown>- )?.["Remaining Quantity"] as number | undefined;-- // Find the split activity+ // Find the split activity — scoped to the remainder entity this+ // pointer names, not just the transfer (multi-line safety).const splitActivity = await trx.selectFrom("trackedActivity").where("type", "=", "Split").where("sourceDocument", "=", "Stock Transfer").where("sourceDocumentId", "=", stockTransferId)+ .where(+ sql<boolean>`attributes->>'Split Entity ID' = ${legacyRemainderId}`+ ).where("companyId", "=", companyId).selectAll().executeTakeFirstOrThrow();@@ -897,7 +929,7 @@ serve(async (req: Request) => {status: "Consumed",quantity: 0,})- .where("id", "=", splitEntityId)+ .where("id", "=", legacyRemainderId).execute();// Mark the split entity as consumed (don't delete it)@@ -948,7 +980,7 @@ serve(async (req: Request) => {entryType: "Negative Adjmt.",documentType: "Direct Transfer",documentId: stockTransferId!,- trackedEntityId: splitEntityId,+ trackedEntityId: legacyRemainderId,createdBy: userId,companyId,}@@ -984,11 +1016,6 @@ serve(async (req: Request) => {.execute();// Create reverse item ledger entries to undo the transfer- // Use the correct trackedEntityId based on whether this was a split operation- // For split operations, use the original entity (splitEntityId)- // For direct operations, use the trackedEntityId- const finalTrackedEntityId = splitEntityId || trackedEntityId;-itemLedgerInserts.push({postingDate: today,itemId: stockTransferLine.itemId,@@ -998,7 +1025,7 @@ serve(async (req: Request) => {entryType: "Transfer",documentType: "Direct Transfer",documentId: stockTransferId,- trackedEntityId: finalTrackedEntityId,+ trackedEntityId: trackedEntityId,createdBy: userId,companyId,});@@ -1012,7 +1039,7 @@ serve(async (req: Request) => {entryType: "Transfer",documentType: "Direct Transfer",documentId: stockTransferId,- trackedEntityId: finalTrackedEntityId,+ trackedEntityId: trackedEntityId,createdBy: userId,companyId,});diff --git a/packages/database/supabase/functions/shared/batch-split.test.ts b/packages/database/supabase/functions/shared/batch-split.test.tsnew file mode 100644index 0000000000..2883ce6696--- /dev/null+++ b/packages/database/supabase/functions/shared/batch-split.test.ts@@ -0,0 +1,193 @@+import {+ assertEquals,+ assertThrows+} from "https://deno.land/[email protected]/testing/asserts.ts";+import {+ type BatchSplitInput,+ buildBatchSplitRecords,+ buildMergeRecords+} from "./batch-split.ts";++const splitInput = (+ overrides: Partial<BatchSplitInput> = {}+): BatchSplitInput => ({+ parent: {+ id: "parent-1",+ readableId: "2026/09",+ quantity: 8,+ sourceDocument: "Item",+ sourceDocumentId: "item-1",+ sourceDocumentReadableId: "SD08810001",+ itemId: "item-1",+ expirationDate: "2026-12-31",+ attributes: { Receipt: "receipt-1", Supplier: "supplier-1" },+ ...(overrides.parent ?? {})+ },+ drawQuantity: 1,+ childId: "child-1",+ splitActivityId: "split-1",+ activitySourceDocument: "Picking List",+ activitySourceDocumentId: "pl-1",+ bin: { storageUnitId: "shelf-a", locationId: "loc-1" },+ itemLedgerItemId: "item-1",+ companyId: "co-1",+ userId: "user-1",+ postingDate: "2026-08-04",+ childStatus: "Available",+ ...overrides+});++Deno.test("child (not parent) carries Split From Entity ID", () => {+ const r = buildBatchSplitRecords(splitInput());+ assertEquals(r.childEntityInsert.attributes["Split From Entity ID"], "parent-1");+ // Parent attributes are untouched — the update only decrements quantity.+ assertEquals(r.parentUpdate, { quantity: 7 });+});++Deno.test("child clones parent attributes minus stale pointer keys", () => {+ const r = buildBatchSplitRecords(+ splitInput({+ parent: {+ id: "parent-1",+ readableId: "2026/09",+ quantity: 8,+ sourceDocument: "Item",+ sourceDocumentId: "item-1",+ sourceDocumentReadableId: "SD08810001",+ itemId: "item-1",+ expirationDate: null,+ attributes: {+ Receipt: "receipt-1",+ "Split Entity ID": "old-forward",+ "Split From Entity ID": "old-back"+ }+ }+ })+ );+ assertEquals(r.childEntityInsert.attributes.Receipt, "receipt-1");+ assertEquals(r.childEntityInsert.attributes["Split Entity ID"], undefined);+ assertEquals(+ r.childEntityInsert.attributes["Split From Entity ID"],+ "parent-1"+ );+});++Deno.test("extra child attributes are applied on top of inherited ones", () => {+ const r = buildBatchSplitRecords(+ splitInput({+ extraChildAttributes: { "Job Operation Step": "step-1", Shipment: "sh-1" }+ })+ );+ assertEquals(r.childEntityInsert.attributes["Job Operation Step"], "step-1");+ assertEquals(r.childEntityInsert.attributes.Shipment, "sh-1");+ assertEquals(r.childEntityInsert.attributes.Receipt, "receipt-1");+});++Deno.test("child inherits identity fields and takes the drawn quantity", () => {+ const r = buildBatchSplitRecords(splitInput({ drawQuantity: 2.5 }));+ assertEquals(r.childEntityInsert.id, "child-1");+ assertEquals(r.childEntityInsert.readableId, "2026/09");+ assertEquals(r.childEntityInsert.quantity, 2.5);+ assertEquals(r.childEntityInsert.status, "Available");+ assertEquals(r.childEntityInsert.itemId, "item-1");+ assertEquals(r.childEntityInsert.expirationDate, "2026-12-31");+ assertEquals(r.parentUpdate.quantity, 5.5);+});++Deno.test("exactly one activity output and it is the child", () => {+ const r = buildBatchSplitRecords(splitInput());+ assertEquals(r.activityInputInsert.trackedEntityId, "parent-1");+ assertEquals(r.activityInputInsert.quantity, 1);+ assertEquals(r.activityOutputInsert.trackedEntityId, "child-1");+ assertEquals(r.activityOutputInsert.quantity, 1);+ assertEquals(r.activityInsert.type, "Split");+ assertEquals(r.activityInsert.attributes, {+ "Original Quantity": 8,+ "Drawn Quantity": 1,+ "Remaining Quantity": 7,+ "Split Entity ID": "child-1"+ });+});++Deno.test("ledger rows net to zero: −q on parent, +q on child, at the parent's bin", () => {+ const r = buildBatchSplitRecords(splitInput());+ const [minus, plus] = r.ledgerInserts;+ assertEquals(minus.quantity, -1);+ assertEquals(minus.trackedEntityId, "parent-1");+ assertEquals(minus.entryType, "Negative Adjmt.");+ assertEquals(plus.quantity, 1);+ assertEquals(plus.trackedEntityId, "child-1");+ assertEquals(plus.entryType, "Positive Adjmt.");+ assertEquals(minus.quantity + plus.quantity, 0);+ for (const row of r.ledgerInserts) {+ assertEquals(row.documentType, "Batch Split");+ assertEquals(row.documentId, "split-1");+ assertEquals(row.storageUnitId, "shelf-a");+ assertEquals(row.locationId, "loc-1");+ assertEquals(row.itemId, "item-1");+ assertEquals(row.postingDate, "2026-08-04");+ }+});++Deno.test("throws on drawQuantity <= 0", () => {+ assertThrows(() => buildBatchSplitRecords(splitInput({ drawQuantity: 0 })));+ assertThrows(() => buildBatchSplitRecords(splitInput({ drawQuantity: -1 })));+});++Deno.test("throws on drawQuantity >= parent quantity (full draw is not a split)", () => {+ assertThrows(() => buildBatchSplitRecords(splitInput({ drawQuantity: 8 })));+ assertThrows(() => buildBatchSplitRecords(splitInput({ drawQuantity: 9 })));+});++Deno.test("merge: quantities move child → parent, edges are input child / output parent", () => {+ const r = buildMergeRecords({+ child: { id: "child-1", quantity: 0.5 },+ parent: { id: "parent-1", quantity: 7 },+ mergeQuantity: 0.5,+ mergeActivityId: "merge-1",+ companyId: "co-1",+ userId: "user-1"+ });+ assertEquals(r.activityInsert.type, "Merge");+ assertEquals(r.activityInputInsert.trackedEntityId, "child-1");+ assertEquals(r.activityOutputInsert.trackedEntityId, "parent-1");+ assertEquals(r.activityInputInsert.quantity, 0.5);+ assertEquals(r.activityOutputInsert.quantity, 0.5);+ assertEquals(r.parentUpdate, { quantity: 7.5 });+});++Deno.test("merge: child is Consumed when drained to zero", () => {+ const r = buildMergeRecords({+ child: { id: "child-1", quantity: 0.5 },+ parent: { id: "parent-1", quantity: 7 },+ mergeQuantity: 0.5,+ mergeActivityId: "merge-1",+ companyId: "co-1",+ userId: "user-1"+ });+ assertEquals(r.childUpdate, { quantity: 0, status: "Consumed" });+});++Deno.test("merge: partial merge leaves the child Available with the remainder", () => {+ const r = buildMergeRecords({+ child: { id: "child-1", quantity: 2 },+ parent: { id: "parent-1", quantity: 7 },+ mergeQuantity: 0.5,+ mergeActivityId: "merge-1",+ companyId: "co-1",+ userId: "user-1"+ });+ assertEquals(r.childUpdate, { quantity: 1.5 });+});++Deno.test("merge: throws when mergeQuantity exceeds child quantity or is <= 0", () => {+ const base = {+ child: { id: "child-1", quantity: 1 },+ parent: { id: "parent-1", quantity: 7 },+ mergeActivityId: "merge-1",+ companyId: "co-1",+ userId: "user-1"+ };+ assertThrows(() => buildMergeRecords({ ...base, mergeQuantity: 2 }));+ assertThrows(() => buildMergeRecords({ ...base, mergeQuantity: 0 }));+});diff --git a/packages/database/supabase/functions/shared/batch-split.ts b/packages/database/supabase/functions/shared/batch-split.tsnew file mode 100644index 0000000000..59b785964d--- /dev/null+++ b/packages/database/supabase/functions/shared/batch-split.ts@@ -0,0 +1,280 @@+// 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.+//+// 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+// is decremented; a NEW child entity departs with q, tagged+// "Split From Entity ID": parent.id. The Split activity records input+// parent@q → output child@q (never a survivor self-loop), and the ledger gets+// 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).++export type BatchSplitInput = {+ parent: {+ id: string;+ readableId: string | null;+ quantity: number;+ sourceDocument: string | null;+ sourceDocumentId: string | null;+ sourceDocumentReadableId: string | null;+ itemId: string | null;+ expirationDate: string | null;+ attributes: Record<string, unknown> | null;+ };+ /** q — must be > 0 and < parent.quantity (full draws never split) */+ drawQuantity: number;+ /** caller-supplied nanoid for the departing child entity */+ childId: string;+ /** caller-supplied nanoid for the Split activity */+ splitActivityId: string;+ /** e.g. "Picking List" */+ activitySourceDocument: string;+ activitySourceDocumentId: string;+ /** the parent's resolved bin — both ledger rows book here */+ bin: { storageUnitId: string | null; locationId: string | null };+ /** itemId for the ledger rows */+ itemLedgerItemId: string | null;+ companyId: string;+ userId: string;+ /** yyyy-MM-dd */+ postingDate: string;+ childStatus: "Available" | "Consumed";+ extraChildAttributes?: Record<string, unknown>;+};++type LedgerRecord = {+ postingDate: string;+ itemId: string | null;+ quantity: number;+ locationId: string | null;+ storageUnitId: string | null;+ entryType: "Negative Adjmt." | "Positive Adjmt.";+ documentType: "Batch Split";+ documentId: string;+ trackedEntityId: string;+ createdBy: string;+ companyId: string;+};++type ActivityEdgeRecord = {+ trackedActivityId: string;+ trackedEntityId: string;+ quantity: number;+ companyId: string;+ createdBy: string;+};++export function buildBatchSplitRecords(input: BatchSplitInput): {+ childEntityInsert: {+ id: string;+ readableId: string | null;+ sourceDocument: string | null;+ sourceDocumentId: string | null;+ sourceDocumentReadableId: string | null;+ quantity: number;+ status: "Available" | "Consumed";+ attributes: Record<string, unknown>;+ itemId: string | null;+ expirationDate: string | null;+ companyId: string;+ createdBy: string;+ };+ parentUpdate: { quantity: number };+ activityInsert: {+ id: string;+ type: "Split";+ sourceDocument: string;+ sourceDocumentId: string;+ attributes: Record<string, unknown>;+ companyId: string;+ createdBy: string;+ };+ activityInputInsert: ActivityEdgeRecord;+ activityOutputInsert: ActivityEdgeRecord;+ ledgerInserts: [LedgerRecord, LedgerRecord];+} {+ const {+ parent,+ drawQuantity,+ childId,+ splitActivityId,+ activitySourceDocument,+ activitySourceDocumentId,+ bin,+ itemLedgerItemId,+ companyId,+ userId,+ postingDate,+ childStatus,+ extraChildAttributes+ } = input;++ // The callers' split gates (full draws take the no-split fast path) should+ // make these unreachable — loud beats silent.+ if (drawQuantity <= 0) {+ throw new Error(+ `buildBatchSplitRecords: drawQuantity must be > 0, got ${drawQuantity}`+ );+ }+ if (drawQuantity >= parent.quantity) {+ throw new Error(+ `buildBatchSplitRecords: drawQuantity (${drawQuantity}) must be < parent quantity (${parent.quantity}) — a full draw is not a split`+ );+ }++ // Clone the parent's attributes minus any stale pointer keys; the child+ // carries the one true back-pointer to its parent.+ const {+ "Split Entity ID": _staleForwardPointer,+ "Split From Entity ID": _staleBackPointer,+ ...inheritedAttributes+ } = (parent.attributes ?? {}) as Record<string, unknown>;++ return {+ childEntityInsert: {+ id: childId,+ readableId: parent.readableId,+ sourceDocument: parent.sourceDocument,+ sourceDocumentId: parent.sourceDocumentId,+ sourceDocumentReadableId: parent.sourceDocumentReadableId,+ quantity: drawQuantity,+ status: childStatus,+ attributes: {+ ...inheritedAttributes,+ "Split From Entity ID": parent.id,+ ...extraChildAttributes+ },+ itemId: parent.itemId,+ expirationDate: parent.expirationDate,+ companyId,+ createdBy: userId+ },+ parentUpdate: { quantity: parent.quantity - drawQuantity },+ activityInsert: {+ id: splitActivityId,+ type: "Split",+ sourceDocument: activitySourceDocument,+ sourceDocumentId: activitySourceDocumentId,+ attributes: {+ "Original Quantity": parent.quantity,+ "Drawn Quantity": drawQuantity,+ "Remaining Quantity": parent.quantity - drawQuantity,+ "Split Entity ID": childId+ },+ companyId,+ createdBy: userId+ },+ activityInputInsert: {+ trackedActivityId: splitActivityId,+ trackedEntityId: parent.id,+ quantity: drawQuantity,+ companyId,+ createdBy: userId+ },+ activityOutputInsert: {+ trackedActivityId: splitActivityId,+ trackedEntityId: childId,+ quantity: drawQuantity,+ companyId,+ createdBy: userId+ },+ ledgerInserts: [+ {+ postingDate,+ itemId: itemLedgerItemId,+ quantity: -drawQuantity,+ locationId: bin.locationId,+ storageUnitId: bin.storageUnitId,+ entryType: "Negative Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: parent.id,+ createdBy: userId,+ companyId+ },+ {+ postingDate,+ itemId: itemLedgerItemId,+ quantity: drawQuantity,+ locationId: bin.locationId,+ storageUnitId: bin.storageUnitId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: childId,+ createdBy: userId,+ companyId+ }+ ]+ };+}++export function buildMergeRecords(input: {+ child: { id: string; quantity: number };+ parent: { id: string; quantity: number };+ mergeQuantity: number;+ mergeActivityId: string;+ companyId: string;+ userId: string;+}): {+ activityInsert: {+ id: string;+ type: "Merge";+ attributes: Record<string, unknown>;+ companyId: string;+ createdBy: string;+ };+ activityInputInsert: ActivityEdgeRecord;+ activityOutputInsert: ActivityEdgeRecord;+ parentUpdate: { quantity: number };+ childUpdate: { quantity: number; status?: "Consumed" };+} {+ const { child, parent, mergeQuantity, mergeActivityId, companyId, userId } =+ input;++ if (mergeQuantity <= 0) {+ throw new Error(+ `buildMergeRecords: mergeQuantity must be > 0, got ${mergeQuantity}`+ );+ }+ if (mergeQuantity > child.quantity) {+ throw new Error(+ `buildMergeRecords: mergeQuantity (${mergeQuantity}) exceeds child quantity (${child.quantity})`+ );+ }++ const childRemaining = child.quantity - mergeQuantity;++ return {+ activityInsert: {+ id: mergeActivityId,+ type: "Merge",+ attributes: {+ "Merged Quantity": mergeQuantity,+ "Merged From Entity ID": child.id+ },+ companyId,+ createdBy: userId+ },+ activityInputInsert: {+ trackedActivityId: mergeActivityId,+ trackedEntityId: child.id,+ quantity: mergeQuantity,+ companyId,+ createdBy: userId+ },+ activityOutputInsert: {+ trackedActivityId: mergeActivityId,+ trackedEntityId: parent.id,+ quantity: mergeQuantity,+ companyId,+ createdBy: userId+ },+ parentUpdate: { quantity: parent.quantity + mergeQuantity },+ childUpdate:+ childRemaining === 0+ ? { quantity: 0, status: "Consumed" }+ : { quantity: childRemaining }+ };+}diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.poindex 9d818a02e4..9545cc74d6 100644--- a/packages/locale/locales/de/mes.po+++ b/packages/locale/locales/de/mes.po@@ -569,6 +569,12 @@ msgstr "Material ausgeben"msgid "Issue Type"msgstr "Problemtyp"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Freigegeben {issuedQuantity} von {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Freigegeben {issuedQuantity} von {lotLabel} — {remainingQuantity} verbleibt"+msgid "Item"msgstr "Artikel"diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.poindex b82bbd707f..8639cdbaf7 100644--- a/packages/locale/locales/en/mes.po+++ b/packages/locale/locales/en/mes.po@@ -569,6 +569,12 @@ msgstr "Issue Material"msgid "Issue Type"msgstr "Issue Type"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Issued {issuedQuantity} of {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgid "Item"msgstr "Item"diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.poindex 2a68d38767..c58e0b2376 100644--- a/packages/locale/locales/es/mes.po+++ b/packages/locale/locales/es/mes.po@@ -569,6 +569,12 @@ msgstr "Emitir material"msgid "Issue Type"msgstr "Tipo de Problema"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Emitido {issuedQuantity} de {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Emitido {issuedQuantity} de {lotLabel} — quedan {remainingQuantity}"+msgid "Item"msgstr "Artículo"diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.poindex fe581dd267..3cec95da07 100644--- a/packages/locale/locales/fr/mes.po+++ b/packages/locale/locales/fr/mes.po@@ -569,6 +569,12 @@ msgstr "Distribuer le matériau"msgid "Issue Type"msgstr "Type de problème"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Émis {issuedQuantity} sur {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Émis {issuedQuantity} sur {lotLabel} — {remainingQuantity} reste"+msgid "Item"msgstr "Article"diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.poindex adb67fdfab..a88d52d2f6 100644--- a/packages/locale/locales/hi/mes.po+++ b/packages/locale/locales/hi/mes.po@@ -569,6 +569,12 @@ msgstr "सामग्री जारी करें"msgid "Issue Type"msgstr "समस्या प्रकार"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "{issuedQuantity} का {lotLabel} जारी किया"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "{issuedQuantity} का {lotLabel} जारी किया — {remainingQuantity} बाकी है"+msgid "Item"msgstr "वस्तु"diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.poindex 17fa3da63c..c41513767a 100644--- a/packages/locale/locales/it/mes.po+++ b/packages/locale/locales/it/mes.po@@ -569,6 +569,12 @@ msgstr "Preleva Materiale"msgid "Issue Type"msgstr "Tipo di Problema"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Emesso {issuedQuantity} di {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Emesso {issuedQuantity} di {lotLabel} — restano {remainingQuantity}"+msgid "Item"msgstr "Articolo"diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.poindex bf4d2ab30d..c106555ce7 100644--- a/packages/locale/locales/ja/mes.po+++ b/packages/locale/locales/ja/mes.po@@ -569,6 +569,12 @@ msgstr "材料払出"msgid "Issue Type"msgstr "問題タイプ"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "{lotLabel} から {issuedQuantity} を発行しました"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "{lotLabel} から {issuedQuantity} を発行しました — {remainingQuantity} が残っています"+msgid "Item"msgstr "品目"diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.poindex 2757a6d8ed..487dd96a7e 100644--- a/packages/locale/locales/ko/mes.po+++ b/packages/locale/locales/ko/mes.po@@ -569,6 +569,12 @@ msgstr "자재 출고"msgid "Issue Type"msgstr "이슈 유형"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "{issuedQuantity}를 {lotLabel}에서 발급함"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "{issuedQuantity}를 {lotLabel}에서 발급함 — {remainingQuantity}가 남음"+msgid "Item"msgstr "품목"diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.poindex 9e09acb8c0..d562d16f0c 100644--- a/packages/locale/locales/pl/mes.po+++ b/packages/locale/locales/pl/mes.po@@ -569,6 +569,12 @@ msgstr "Wydaj materiał"msgid "Issue Type"msgstr "Typ problemu"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Wydane {issuedQuantity} z {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Wydane {issuedQuantity} z {lotLabel} — pozostaje {remainingQuantity}"+msgid "Item"msgstr "Pozycja"diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.poindex fa099b052e..b68088f286 100644--- a/packages/locale/locales/pt/mes.po+++ b/packages/locale/locales/pt/mes.po@@ -569,6 +569,12 @@ msgstr "Emitir Material"msgid "Issue Type"msgstr "Tipo de Problema"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Emitido {issuedQuantity} de {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Emitido {issuedQuantity} de {lotLabel} — {remainingQuantity} permanece"+msgid "Item"msgstr "Item"diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.poindex 0966318414..19c130485c 100644--- a/packages/locale/locales/ru/mes.po+++ b/packages/locale/locales/ru/mes.po@@ -569,6 +569,12 @@ msgstr "Выдать материал"msgid "Issue Type"msgstr "Тип проблемы"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Выпущено {issuedQuantity} из {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Выпущено {issuedQuantity} из {lotLabel} — осталось {remainingQuantity}"+msgid "Item"msgstr "Номенклатура"diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.poindex 0f12ee8ce8..6a8207a8fb 100644--- a/packages/locale/locales/tr/mes.po+++ b/packages/locale/locales/tr/mes.po@@ -569,6 +569,12 @@ msgstr "Malzeme Çıkart"msgid "Issue Type"msgstr "Sorun Türü"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "Çıkış Yapılan {issuedQuantity} / {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "Çıkış Yapılan {issuedQuantity} / {lotLabel} — {remainingQuantity} Kaldı"+msgid "Item"msgstr "Ürün"diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.poindex b4ea93b591..8409082ff3 100644--- a/packages/locale/locales/zh/mes.po+++ b/packages/locale/locales/zh/mes.po@@ -569,6 +569,12 @@ msgstr "发放物料"msgid "Issue Type"msgstr "问题类型"+msgid "Issued {issuedQuantity} of {lotLabel}"+msgstr "已发放 {issuedQuantity} 个 {lotLabel}"++msgid "Issued {issuedQuantity} of {lotLabel} — {remainingQuantity} remains"+msgstr "已发放 {issuedQuantity} 个 {lotLabel} — 还剩 {remainingQuantity} 件"+msgid "Item"msgstr "物料"diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.tsindex 51c5cc76da..e713c1d2c2 100644--- a/packages/utils/src/types.ts+++ b/packages/utils/src/types.ts@@ -49,6 +49,7 @@ export interface TrackedEntityAttributes {"Shipment Line"?: string;Shipment?: string;"Split Entity ID"?: string;+ "Split From Entity ID"?: string;"Stock Transfer Line"?: string;"Stock Transfer"?: string;expirationDate?: string;