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): picked-material return timing (job vs operation) (#1320)
Sid644838281d77
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 8e8be1ed56..eab6222e10 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -594,6 +594,16 @@ Format: `Context → Problem → Rule → Applies to`**Applies to:** `packages/react/src/Number.tsx`; every `formatOptions={{ ... }}` call site in `apps/erp` / `apps/mes` (~144); `packages/form/src/components/{Number,NumberControlled,ArrayNumeric}.tsx`, whose `rest.formatOptions ?? ({ ... })` default also allocates a fresh object each render.+## Returns must not decrement pickingListLine.quantityPicked — the status trigger demotes terminal headers++**Context:** Building the picked-material return sweep (spec `.ai/specs/2026-08-04-picked-material-return-timing.md`). The original `returnPickedRemainder` case in `post-picking` decremented `pickingListLine.quantityPicked` when flushing un-consumed staged stock back to the warehouse at job complete.++**Problem:** `update_picking_list_status` (AFTER UPDATE ROW on `pickingListLine`, newest body `20260728120100`) fires on any `quantityPicked` change. After the decrement the line satisfies `quantityPicked < quantityToPick`, so the trigger's work-remains branch moves a `Completed`/`Partial` picking-list header back to **In Progress** — the automatic job-complete sweep was silently reopening completed picking lists. The demotion is CORRECT for an operator unpick (work regression); it is wrong for a post-completion return.++**Rule:** Book returns on `pickingListLine.quantityReturned` (added `20260804111631`) and leave `quantityPicked` as gross-picked; net staged at lineside = `quantityPicked − quantityReturned`. Only genuine unpicks (operator reversing work) may decrement `quantityPicked`. Any new writer of `pickingListLine.quantityPicked`/`status` must first check what `update_picking_list_status` will do with the change. `pickingListLineTrackedEntity` allocations are different — returns DO decrement those (availability RPCs net them out; no trigger watches that table).++**Applies to:** `packages/database/supabase/functions/post-picking/index.ts` (all return/unpick cases), `update_picking_list_status` migrations, any code mutating `pickingListLine` quantities.+## Audit FK snapshots: constraint-less columns are invisible to schema discovery; junction targets need hops**Context:** Audit-log diffs resolve FK ids into frozen display names ("Location: Chicago → Dallas") via `get_foreign_key_map` + `fkDisplayRegistry` (`packages/database/src/audit.config.ts`, handler in `packages/jobs/src/inngest/functions/events/{audit,fk-snapshots}.ts`). Found while fixing "audit log shows location id instead of name" (2026-08).diff --git a/.ai/plans/2026-08-04-picked-material-return-timing.md b/.ai/plans/2026-08-04-picked-material-return-timing.mdnew file mode 100644index 0000000000..61ac425c5d--- /dev/null+++ b/.ai/plans/2026-08-04-picked-material-return-timing.md@@ -0,0 +1,86 @@+# Plan: Picked-material return timing (job vs operation)++Spec: `.ai/specs/2026-08-04-picked-material-return-timing.md`+Research: `.ai/research/material-staging-return-timing.md`++Owed formula (final): `owed = (jobMaterial.estimatedQuantity ÷ job.quantity) × op.quantityComplete`+(includes scrap allowance). Op scope only; job scope owed = 0 (backflush ran first).++## Tasks++- [x] **T1 — Migration** `packages/database/supabase/migrations/<ts>_picked-material-return-timing.sql`+ - `companySettings.returnPickedMaterialTiming TEXT NOT NULL DEFAULT 'job' CHECK IN ('job','operation')`+ - `pickingListLine.quantityReturned NUMERIC NOT NULL DEFAULT 0`+ - `backflush_job_materials` verbatim fork of `20260713190909:131` + lineside clamp:+ after bin resolution, if bin has `workCenterId`, clamp qty to+ `GREATEST(SUM(itemLedger.quantity) WHERE itemId/storageUnitId/locationId/companyId AND trackedEntityId IS NULL, 0)`; `CONTINUE` at ≤ 0.+ - Verify: SQL review. **User runs `pnpm db:migrate`** (regenerates types). Never rebuild DB.++- [x] **T2 — post-picking edge fn** `packages/database/supabase/functions/post-picking/index.ts`+ - Extract `returnTrackedAllocationRemainder(trx, ...)` from `returnPickedRemainder` body+ (:737-903): line update becomes `quantityReturned += totalReturned` (drop `quantityPicked`+ decrement + status reset :884-900; keep allocation decrement/delete :853-882); drop+ unconditional `restoreJobMaterialSource` (:902) — repoint decided per material by sweep.+ - New `returnUntrackedMaterialRemainder(trx, ...)`: per-jobMaterial returnable =+ `max(0, Σ(line.picked − line.returned) − max(quantityIssued, owed))`, newest-first line+ allocation, per-line cap picked−returned, target bin `line.storageUnitId` → pickMethod+ default → NULL; untracked transfer pairs (hand-built inserts, transferPair requires+ trackedEntityId); increment `quantityReturned`.+ - New cases `returnOperationRemainders {jobOperationId,userId,companyId}` (reads+ `returnPickedMaterialTiming`, no-op on 'job'; owed per formula; lines WHERE+ jobOperationId=op, line status ≠ Cancelled, list not Draft/Cancelled) and+ `returnJobRemainders {jobId,userId,companyId}` (guard job.status='Completed'; owed=0;+ all non-Cancelled lines incl. NULL-op). Both derive locationId from job; conditional+ repoint: job scope always restore; op scope restore only when net lineside ≤ 0.+ - Keep legacy `returnPickedRemainder` case as wrapper.+ - Verify: `pnpm run lint`.++- [x] **T3 — MES wiring**+ - `apps/mes/app/services/operations.service.ts`: replace+ `returnAllocatedRemaindersAtJobComplete` (:213-277) with `returnPickedRemainders`:+ read op.jobId + job.status → Completed ? `returnJobRemainders` : `returnOperationRemainders`;+ keep log-on-error. `finishJobOperation:195` call unchanged.+ - `apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx`: after postings succeed,+ re-read op status; if 'Done' → `returnPickedRemainders(serviceRole, ...)`.+ - Verify: `pnpm exec turbo run typecheck --filter=mes` (post-migrate), `pnpm run lint`.++- [x] **T4 — ERP wiring**+ - `production.service.ts`: add `returnPickedRemainders` (op) + `returnPickedJobRemainders`+ (job) helpers, barrel export.+ - `x+/job+/methods+/operation.status.tsx`: after update success, status==='Done' →+ op sweep via `getCarbonServiceRole()`.+ - `x+/job+/$jobId.complete.tsx`: after RPC success → job sweep; failure = warning flash,+ completion stands (sweep idempotent).+ - `$jobId.status.tsx` direct-Completed bypass: comment only.+ - Verify: `pnpm exec turbo run typecheck --filter=erp` (post-migrate), `pnpm run lint`.++- [x] **T5 — Settings surface (ERP)**+ - `settings.models.ts`: `returnPickedMaterialTimings = ["job","operation"] as const` + validator.+ - `settings.service.ts`: `updateReturnPickedMaterialTimingSetting`.+ - `x+/settings+/inventory.tsx`: intent case + ChoiceSelect card (incompletePickingListPolicy+ pattern). `pnpm lingui:extract` after.+ - Verify: typecheck erp (post-migrate), lint.++- [x] **T6 — Net-picked consumers**+ - MES `getPickedQuantitiesByJobMaterial` (inventory.service.ts:363): expose+ `quantityReturned`; staged-at-lineside math uses picked − returned.+ - Optional ERP PickingListLines "Returned" column.++- [x] **T7 — Docs/rules sync**+ - `.claude/rules/traceability-model.md` (pick→consume→return paragraph),+ `.claude/rules/inventory-system.md`, `.ai/lessons.md` entry (quantityPicked decrement+ trips status trigger — use quantityReturned for returns).++## Gate (after user runs `pnpm db:migrate`)++`pnpm exec turbo run typecheck --filter=@carbon/database --filter=erp --filter=mes`+`pnpm run lint`+Manual /test: pick → partial issue → op Done under 'operation' → remainder returned,+header stays Completed → complete job → backflush clamped + final sweep + storageUnitId restored.++## Risks (accepted)++- Untracked newest-first allocation is bookkeeping, not physical truth.+- Op un-Done after sweep: not reversed; re-pick.+- Crash between completion and sweep: strands until re-invoke (idempotent) — same as today.+- Deploy edge fn before app (legacy case kept for skew).diff --git a/.ai/playbooks/picked-material-return-timing.md b/.ai/playbooks/picked-material-return-timing.mdnew file mode 100644index 0000000000..1f808fc455--- /dev/null+++ b/.ai/playbooks/picked-material-return-timing.md@@ -0,0 +1,72 @@+# Picked-Material Return Timing (job vs operation)++Last tested: 2026-08-04+Routes: ERP `/x/settings/inventory`, `/x/picking-list/schedule`, `/x/picking-list/<id>/details`,+`/x/job/<id>/details`; MES `/x/operation/<opId>`++## Prerequisites+- Migration `20260804111631` applied (`returnPickedMaterialTiming`, `quantityReturned`).+- A Make item whose method has ≥1 operation on a work center, one untracked BOM+ material (per-unit 1) with warehouse stock in a bin. For an OP-scope test the+ method needs 2 operations and the jobMaterial must be assigned to op 1+ (`jobMaterial.jobOperationId` — no BOM UI for this yet; set via SQL fixture).+- MES login is separate (same DEV_BYPASS email at `MES_URL/login`; retry the+ target URL after login — first redirect can bounce).++## Steps++### 1. Policy setting (ERP Inventory settings)+- Card "Returning unused picked material" = the **4th** ChoiceSelect / 4th Save+ on the page. Hidden input `input[name=returnPickedMaterialTiming]` is truth.+- Options: "At job completion" (`job`, default) / "At operation completion"+ (`operation`). Submit that form via requestSubmit → toast "Material return+ timing updated"; persists across reload.++### 2. Stage material+- Create job (qty 2) → Release (confirm dialog "Release Job").+- `/x/picking-list/schedule` → check "Select J00000N" → button+ "Generate Picking List 1" → redirects to the list details → click **Pick**+ (line badge → 2/2, list header Completed; jobMaterial.storageUnitId → lineside).++### 3. Produce partially + finish op (MES)+- `/x/operation/<opId>`: big emerald submit button = Start (op → In Progress).+- 1st `button.bg-accent` = "Log completed" modal → fill qty 1 → "Log Completed"+ (inserts productionQuantity; auto-backflushes untracked → quantityIssued 1;+ Consumption ledger row AT the lineside bin).+- 2nd `button.bg-accent` = action sheet → "Finish" → "Finish Anyways" (1 < 2).+- CAUTION: the sidebar "Add Inventory"/"End Operations" buttons are NOT the+ completion flow (manual adjustment / end-events).++### 4. Expected outcomes+- **policy=operation, op 1 of 2 finishes (job stays In Progress):** immediate+ Transfer pair lineside→source for `picked − max(issued, owed)` where+ `owed = (estimatedQuantity ÷ job qty) × op quantityComplete`;+ `pickingListLine.quantityReturned` += returned; `quantityPicked` UNCHANGED+ (gross); list header stays Completed/Partial (no In Progress demotion);+ jobMaterial.storageUnitId restored to source when nothing staged remains.+- **policy=job, op finishes (non-last):** NO return (quantityReturned stays 0).+- **last op finishes (either policy) or ERP job Complete button:** job completes+ → backflush tops up from lineside → job-scope sweep returns the rest.+- ERP Complete dialog: quantity field prefills 0 — fill the real completed qty+ (react-aria: fill + blur before requestSubmit "Complete Job").+- ERP picking-list line shows a "Returned N" secondary badge (LuUndo2 icon).++## Verification queries+```sql+SELECT "quantityPicked","quantityReturned",status FROM "pickingListLine" WHERE id='...';+SELECT "entryType",quantity,"storageUnitId" FROM "itemLedger" ORDER BY "createdAt";+-- lineside bin should net to 0 after job completion; source bin = initial − consumed+```++## Selector Notes+- MES op controls are unlabeled: emerald submit = Start; `button.bg-accent`[0] =+ Log completed; `button.bg-accent`[1] = action sheet (Scrap/Rework/Finish/…).+- Settings ChoiceSelects have no accessible labels — target by position or the+ hidden input name.+- Job release/complete confirm dialogs: buttons "Release Job" / "Complete Job".++## Common Failures+- MES first navigation lands on /login even with ERP cookies — log in there+ once, then re-open the operation URL.+- ERP job operations table Qty-Complete cell editor would not open via+ click/dblclick in agent-browser — use the MES Log-completed flow instead.diff --git a/.ai/research/material-staging-return-timing.md b/.ai/research/material-staging-return-timing.mdnew file mode 100644index 0000000000..64599aa4e7--- /dev/null+++ b/.ai/research/material-staging-return-timing.md@@ -0,0 +1,175 @@+# Material Staging Return Timing Research: Best Practices Survey++## Summary++Surveyed how SAP (ECC WM + S/4HANA EWM), Dynamics 365 SCM, NetSuite, Katana,+Fulcrum, ProShop, Epicor Kinetic, and Fishbowl handle staged/picked production+material and the return of the unconsumed remainder to the warehouse — with+focus on WHEN the return happens (operation completion vs order/job completion+vs manual) and how backflush interacts. Key finding: **no surveyed system+auto-returns staged material at operation completion.** The market splits into+(a) manual-return-only (SAP, D365, NetSuite, Epicor, Fishbowl, Fulcrum) and+(b) automatic return at **order completion** (Katana — the only auto-return+found, matching Carbon's current behavior). The industry's actual policy lever+is **consumption timing** (D365 flushing principles, Epicor per-operation+backflush), not return timing. Epicor is a direct counter-signal to+per-operation return: since 2022.2, completing an operation *forfeits*+returnability (WIP assumed fully consumed). SAP's answer to leftover staged+stock is structural: cross-order staging (remainder stays at the PSA, netted+by the next order's staging run) plus an explicit "Clear Production Supply+Area" transaction run after the order finishes.++## Competitors Surveyed++- **SAP ECC WM / S/4HANA EWM** — enterprise reference; richest staging model (PSA, control cycles, PMR)+- **Dynamics 365 SCM** — production input locations + the flushing-principle policy vocabulary+- **NetSuite (WMS + WIP/Routings)** — WIP bins, pick reversal, per-operation backflush+- **Epicor Kinetic** — job-shop reference; explicit Issue/Return Material transactions+- **Katana MRP** — the only system with automatic return-at-completion+- **Fulcrum** — modern MES-first; pick = immediate consume+- **Fishbowl** — pick = relocate to manufacturing location (closest to Carbon's lineside model)+- **ProShop ERP** — public docs too thin to confirm transaction mechanics++## Key Consensus Patterns++### 1. Staged material stays on-hand; consumption is a separate later event++- **SAP**: WM 319 moves stock to interim storage type 100 / PSA bin — WM-internal only, no IM posting; still unrestricted, valuated, on-hand. Consumption = 261 at confirmation/backflush.+- **D365**: raw-material-picking work moves stock to the production input location with status Picked — still on-hand until a picking-list journal posts (exception: "Available at location" flushing principle, where arrival = consumption).+- **NetSuite**: WMS work-order picking is a bin transfer into a WIP bin — on-hand until Work Order Issue/build.+- **Fishbowl**: pick relocates to the WO's "manufacturing location"; finish consumes.+- **Counter-model**: Fulcrum (pick = immediate issue) and Epicor (Issue Material = STK-MTL into WIP cost bucket, off inventory).+- **Rationale**: keeping staged stock on-hand keeps returns cheap (a reverse transfer) and inventory truthful. Carbon's pick-as-Transfer-to-lineside matches the majority model.++### 2. No system auto-returns at operation completion; only Katana auto-returns at order completion++- **SAP**: no automatic return at operation confirmation, order confirmation, or TECO. EWM "Clear Production Supply Area" is run explicitly after the PMR completes AND no other PMR needs the product.+- **D365**: no return mechanism at RAF/End at all; community workaround = manual unpick + inventory movement.+- **NetSuite**: "Reverse Picks" any time before consumption — operator-initiated.+- **Epicor**: manual Return Material Entry (MTL-STK); and since 2022.2.3 an operation marked complete CLEARS its WIP — returns after op completion are blocked ("not enough qty in WIP"). Op completion is treated as "everything issued was consumed."+- **Katana**: automatic — "returns unused ingredients to inventory when the MO is marked Done."+- **Rationale**: at operation completion the system generally cannot know the remainder is surplus — later operations, rework, or the next order at the same line may need it. Order completion is the first moment "unconsumed" provably means "unneeded."++### 3. The configurable policy point is consumption timing, not return timing++- **D365**: flushing principle per BOM line — Start / Finish (order RAF or the tied operation's completion) / Available-at-location (pick = consume) / Manual.+- **Epicor**: per-material backflush flag; backflush fires per-operation at labor/qty reporting, at standard quantities.+- **NetSuite**: issue-then-complete vs completion-with-backflush; components tied to an operation backflush when that operation reports.+- **SAP**: staging type per control cycle (pick parts = exact order qty → minimal leftover; crate/release-order parts = intentional over-staging).+- **Rationale**: tightening consumption timing shrinks the staged-unconsumed window, making return timing mostly moot. A return-timing policy is unusual — Carbon adding one is ahead of the market (precedent: Katana's fixed-at-completion, made configurable).++### 4. Leftover-remainder handling is quantity-netting or structural, not per-op sweeps++- **SAP**: over-staged remainder stays at the PSA; the next staging run (MF60 / WM staging) NETS existing PSA stock against the new requirement — leftover gets consumed by the next order without a return trip. Cross-order staging is the recommended pattern when leftovers are common; single-order staged stock requires a reference-release step before reuse.+- **S/4 2020+**: partial quantity of single-order staged stock can be re-assigned to another order WITHOUT physically moving it back.+- **D365**: excess just sits at the input location as on-hand (community calls unreturned leftovers "shop floor inventory" — the anti-pattern name).+- **Rationale**: physical return trips are waste if the same line will need the item again soon; netting/reassignment beats round-tripping.++## Answers to Research Questions++1. **When does unconsumed staged material return?** — Manual everywhere except Katana (auto at MO Done). Never automatically at operation completion in any surveyed system. SAP/EWM formalizes the "after order finishes" moment with the Clear PSA transaction gated on "no other PMR needs the product."+2. **Industry terminology** — "return to stock", "material return" (Epicor: Return Material Entry), "pick reversal" (NetSuite), "unpick" (D365 "Stop and unpick"), "Clear Production Supply Area" / "de-staging" (SAP EWM), "reintegration" (Sage X3). For the staging place: PSA (SAP), production input location (D365), WIP bin (NetSuite), manufacturing location (Fishbowl) — Carbon's "lineside" fits.+3. **Backflush interaction** — backflush consumes FROM the staging location (SAP 261 from PSA; Epicor from backflush bin hierarchy incl. resource input warehouse; D365 Finish-principle proportional to reported qty). Nobody returns remainder as part of backflush; remainder stays staged. Epicor's post-2022.2 behavior (op completion clears WIP) is the sharpest edge: returning at op completion and backflushing at completion are in direct tension unless the return runs strictly AFTER all consumption for that operation is final.+4. **Return automatic or manual? Policy?** — Manual, except Katana. No system exposes a return-timing config. D365's flushing principles are the closest policy analog and are per-BOM-line, not global.+5. **Shared staging areas** — SAP explicitly supports shared PSAs across work centers/orders (cross-order staging = shared pool, no per-order reference). Netting handles contention. Single-order staging ring-fences stock at the price of a release step. Carbon's per-work-center lineside bin ≈ a shared PSA: per-operation return must not yank stock another job/operation at the same work center still needs.+6. **Partial consumption / batch splits** — SAP EWM supports partial-HU consumption and re-assignment without physical moves; batch staged stock consumed FIFO (BAdI-overridable). Carbon's split-lineage walk (`returnPickedRemainder`) is the equivalent mechanism.++## Competitor-Specific Details++### SAP+- PSA is master data (PK05), mapped to storage-location/bins; control cycles (LPK1) per material+PSA choose staging type 1 (pick parts, exact qty), 2 (crate), 3 (release-order), 4 (manual).+- 319 = staging transfer (no IM posting), 261 = consumption, 262 = return of issued-but-unused (works even after TECO), 311 = IM staging return path. 531 is by-product receipt — unrelated.+- KBA 3305001: EWM Post Consumption app allows consumption/reversal even at TECO — documented PP↔EWM status inconsistency.+- Leftover staged stock stays count-relevant (cycle counting on PSA slocs); guidance says clear PSAs before period-end.++### D365+- Flushing principles: Start (proportional to started qty; with MES can fire at operation start), Finish (proportional to RAF qty; fires at order RAF or tied operation's completion), Available at location (pick = consume, batch-posted picking list), Manual.+- "Stop and unpick" reverses Picked transactions but leaves material AT the input location — physical return is a separate mobile-device movement.+- Over-picking is a threshold-gated WMS feature with no downstream disposition handling.++### NetSuite+- WIP bins ("Use Bin in Manufacturing Mobile") stage picked components including excess, still on-hand.+- Reverse Picks: per-task reversal auto-creating a bin transfer back to source bins; any time before consumption.+- After issue: edit/delete the Work Order Issue (open period, order not closed). After build: Assembly Unbuild. WO Close is the hard lock.++### Epicor Kinetic+- Issue Material (STK-MTL) / Return Material Entry (MTL-STK), operator picks target warehouse/bin.+- Since 2022.2.3: operation completion clears that operation's WIP — Return Material afterward fails; Epicor calls it intended. Users work around by returning BEFORE completing the op.+- Backflush per-operation at labor/qty report, standard quantities only, not for lot/serial parts.++### Katana+- Picking = soft reservation (no location move). Consumption at MO Done from actuals.+- Auto-return: unused ingredients return to inventory at MO Done, linked to the MO for traceability. Over-consumption flips MO back to Partially picked.++### Fulcrum+- Pick = immediate inventory decrement + actual cost to job. Remnant return is a manual operator transaction (remnant sizes for sheet/bar).+- "Auto-pick material on job completion" setting = backflush-at-job-completion analog; skips materials with any existing pick.++### Fishbowl+- Pick moves stock to the WO's manufacturing location (on-hand); finish consumes; "any unused quantities remain in the manufacturing location and can either be moved back into their respective inventory locations or scrapped" — manual.++### ProShop+- Soft allocation to work orders documented; no public evidence of staging locations, return transactions, or backflush config. Unconfirmed.++## Recommended Approach for Carbon++1. **Keep return-at-job-completion as the default** (Katana pattern, Carbon's current behavior). It is the only proven auto-return timing; every enterprise system treats order-finish as the first safe "surplus is surplus" moment.+2. **Offer per-operation return as an opt-in company policy**, not the default — no competitor does it automatically, and Epicor actively forbids returns after op completion, so this is novel surface; gate it carefully. Model the setting on the existing `incompletePickingListPolicy` precedent.+3. **Guard the per-operation sweep with a "no remaining demand" check** (SAP Clear-PSA's "no other PMR needs the product" gate): only return a line's remainder when no other open operation/job at the same work center still requires that item, or scope strictly to the line's own picked-minus-consumed quantity — never sweep bin on-hand (Carbon's lineside bin is per-work-center = a shared PSA).+4. **Sequence return strictly after consumption is final for that operation** (Epicor tension): per-operation return must run after the operation's backflush/issues post, and job-completion backflush (`backflush_job_materials` top-up) must be accounted for — returning material the completion-time backflush still needs would break job costing. Restrict per-operation return to lines whose material is fully issued, or make completion-time backflush re-pull.+5. **Quantity attribution from line quantities, not bin stock** (SAP netting insight): untracked remainder = line `quantityPicked` − attributable consumption, clamped ≥ 0; tracked remainder = split-lineage lineside on-hand (existing `returnPickedRemainder` mechanism).+6. **Terminology**: "return to stock" / "material return" for UI copy; avoid inventing new terms.++## Sources++### SAP+- https://learning.sap.com/courses/production-integration-with-sap-s-4hana-ewm/clearing-the-production-supply-area+- https://learning.sap.com/courses/processes-in-sap-s-4hana-ewm/executing-the-production-supply-process+- https://help.sap.com/docs/SAP_EXTENDED_WAREHOUSE_MANAGEMENT/3d97bec9bf1649099384bb8167df3cf2/019deb535cbb5d1ee10000000a441470.html+- https://help.sap.com/docs/SAP_EXTENDED_WAREHOUSE_MANAGEMENT/3d97bec9bf1649099384bb8167df3cf2/8969c21268d2466985f0c810fae7e9a8.html+- https://help.sap.com/docs/SAP_ERP_SPV/e4d7eb053c62465885b669e169116aa6/ae5fbd534f22b44ce10000000a174cb4.html+- https://help.sap.com/docs/SAP_EXTENDED_WAREHOUSE_MANAGEMENT/3d97bec9bf1649099384bb8167df3cf2/911b39b24cce43cd82002d59df55279b.html+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/b2dee5e83e2446149294f9860a7c08f0/f48fc95360267214e10000000a174cb4.html+- https://userapps.support.sap.com/sap/support/knowledge/en/3305001+- https://www.saplogisticsexpert.com/sap-ewm-pp-integration-master-guide-to-production-staging-and-shopfloor-mapping/+- https://www.saplogisticsexpert.com/material-staging-for-production/+- https://itpfed.com/understanding-ewm-advanced-production-integration/+- https://community.sap.com/t5/enterprise-resource-planning-q-a/movement-types-involved-in-wm-pp/qaq-p/8956335+- https://community.sap.com/t5/enterprise-resource-planning-q-a/return-of-parts-after-teco/qaq-p/11744384+- https://community.sap.com/t5/supply-chain-management-q-a/ewm-clear-production-supply-area/qaq-p/12309402+- https://community.sap.com/t5/supply-chain-management-blogs-by-members/release-partial-quantity-of-single-order-staged-stock-enhancements-to/ba-p/13499790+- https://community.sap.com/t5/enterprise-resource-planning-q-a/storage-type-for-production-line-staging/qaq-p/11008093+- https://community.sap.com/t5/enterprise-resource-planning-q-a/movement-261-and-262/qaq-p/3579620++### D365+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/production-control/flushing-principles+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/warehousing/warehouse-work-policies+- https://www.loganconsulting.com/blog/understanding-over-picking-in-d365-supply-chain-management/+- https://community.dynamics.com/forums/thread/details/?threadid=ad55174e-1b7b-4581-b23b-884fda8ea459+- https://dynamicsuser.net/ax/f/users/80545/posting-negative-picking-list+- https://learn.microsoft.com/en-us/answers/questions/1348909/+- https://www.sikich.com/insight/using-dynamics-365-work-policies/++### NetSuite+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_164251896831.html+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_164251905118.html+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_0208122806.html+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_155993390806.html+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2321882.html+- https://netsuitechangelog.com/articles/pick-reversal-capabilities-in-netsuite-20232/+- https://www.anchorgroup.tech/blog/netsuite-wms-manufacturers++### SMB / point solutions+- https://support.katanamrp.com/en/articles/11172448-picking-ingredients-for-a-manufacturing-order-mo+- https://support.katanamrp.com/en/articles/5914331-completing-a-manufacturing-order-mo+- https://katanamrp.com/blog/ingredient-picking/+- https://fulcrumpro.com/manufacturing-software/job-tracking+- https://fulcrumpro.com/article/streamlining-real-time-inventory-capture-with-fulcrum+- https://docs.biscit.com/epicor-kinetic-warehouse/epicor-kinetic-warehouse-user-guide/issues-and-returns+- https://www.epiusers.help/t/return-material-from-job-not-enough-wip/95470+- https://www.mayantechs.com/post/backflush-in-epicor-kinetic-benefits-limitations-and-best-practices+- https://help.epicor.com/erp/102700/enu/standard/FeaturesSupplyChain/inv_materialbackflush.html+- https://help.fishbowlinventory.com/advanced/s/article/Work-Order+- https://help.fishbowlinventory.com/advanced/s/article/Picking+- https://proshoperp.com/erp-modules/inventory-management/+- https://communityhub.sage.com/us/sage_x3/b/sageerp_x3_product_support_blog/posts/is-it-possible-to-return-not-used-material-back-to-stockdiff --git a/.ai/specs/2026-08-04-picked-material-return-timing.md b/.ai/specs/2026-08-04-picked-material-return-timing.mdnew file mode 100644index 0000000000..27dde4ffa5--- /dev/null+++ b/.ai/specs/2026-08-04-picked-material-return-timing.md@@ -0,0 +1,151 @@+# Picked-Material Return Timing (job vs operation)++> Status: in-progress+> Author: Sid (design interview) + Claude+> Date: 2026-08-04++## TLDR++A pick in Carbon is a Transfer (warehouse bin → work center lineside bin), not a+consumption; the unconsumed remainder currently flushes back to the warehouse only when+the entire job completes — and only for batch/serial allocations, only when completion+runs through MES. This spec adds an opt-in company policy+`returnPickedMaterialTiming: 'job' (default) | 'operation'` that flushes each+operation's unconsumed remainder back when that operation completes, extends automatic+returns to untracked material (both timings), and fixes the ERP-side completion paths+that today never trigger any return. Consumed material never returns automatically.++Research: `.ai/research/material-staging-return-timing.md` — no competitor auto-returns+at operation completion (Katana auto-returns at MO completion only; Epicor blocks+post-op returns entirely), so the per-operation option is novel surface and is guarded:+an "owed backflush" hold-back keeps enough staged stock for completion-time backflush,+and the backflush itself gains a lineside on-hand clamp.++## Problem Statement++1. Operator picks 100 to lineside, operation consumes 50 → the leftover 50 sits at the+ lineside bin until the whole job completes. Shops that stage per-operation want the+ surplus back in the warehouse as soon as the operation is done.+2. Pre-existing gap: the job-complete sweep (`returnAllocatedRemaindersAtJobComplete`,+ MES) covers tracked allocations only — plain untracked inventory leftovers never+ return automatically at all.+3. Pre-existing gap: the sweep is wired only into MES `finishJobOperation`. Jobs+ completed from the ERP "Complete" button, ops set Done from ERP dropdowns/kanban,+ and the MES complete-passed (inspection) path complete jobs with no sweep.+4. Pre-existing bug (found during design): the sweep decrements+ `pickingListLine.quantityPicked`, which fires `update_picking_list_status` and+ demotes Completed/Partial picking-list headers back to In Progress.++## Proposed Solution++One shared sweep implemented as two new cases in the `post-picking` edge function —+`returnOperationRemainders { jobOperationId }` and `returnJobRemainders { jobId }` —+each performing the full tracked + untracked return in one Kysely transaction, invoked+from every completion call site (MES + ERP). Returns book `quantityReturned` on the+picking-list line instead of decrementing `quantityPicked`, so the status trigger never+fires for returns.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Policy scope | Company-wide `companySettings.returnPickedMaterialTiming` `'job'` (default) \| `'operation'` | User-resolved. Precedent: `incompletePickingListPolicy`. Default preserves current behavior (Katana pattern; only proven auto-return timing). |+| Untracked material | Auto-returns under BOTH timings | User-resolved. Closes the tracked-only gap; the motivating scenario is quantity-based. |+| Return amount at op-Done | Full unconsumed remainder; op completed qty is final | User-resolved. Owed hold-back protects completion-time backflush. |+| Owed formula | `owed = (estimatedQuantity ÷ job.quantity) × op.quantityComplete` — includes scrap allowance | User-resolved (follow-up question). Per-unit-only would let the scrap allowance return early → clamped backflush → understated COGS. |+| ERP gap | Fixed in same feature; one choke point | User-resolved. |+| Choke point | Two new `post-picking` cases, not a new edge fn, not event-system | post-picking owns transferPair/lineage-walk/pool; event system is async (~3–5s, unseeded-config = never) — unacceptable for inventory correctness. |+| Policy read | `returnOperationRemainders` reads the setting itself, no-ops on `'job'`; op-Done sites invoke unconditionally | Guard lives in one place. `returnJobRemainders` ignores policy (catch-all both timings) but requires `job.status = 'Completed'`. |+| Trigger-flip fix | New `pickingListLine.quantityReturned NUMERIC NOT NULL DEFAULT 0`; returns stop touching `quantityPicked`/status | Trigger only reacts to `quantityPicked`/`status` → returns become invisible to it. `quantityPicked` = gross picked; net at lineside = picked − returned. Unpick keeps its decrement (work regression → demotion is correct). |+| Tracked allocations | `pickingListLineTrackedEntity` keeps existing decrement/delete-at-0 | Availability RPCs net allocations out; freezing rows would make returned lots un-re-allocatable. No trigger watches that table. |+| Untracked remainder math | Per jobMaterial: `returnable = max(0, Σ(line.picked − line.returned) − max(quantityIssued, owed))`; allocated newest-first across that material's lines; per-line cap = picked − returned | No per-line consumption attribution exists (single `quantityIssued` counter, N lines per material). Never bin-swept — lineside bin is shared per work center. |+| Return target bin (untracked) | `line.storageUnitId` → `pickMethod.defaultStorageUnitId` → NULL (location-level) | Mirrors pick-from-unassigned; never strands stock. |+| Backflush clamp | Fork `backflush_job_materials` verbatim; clamp issue qty to net untracked on-hand at the resolved bin, only when the bin is lineside (`storageUnit.workCenterId IS NOT NULL`) | Safety net for races/manual transfers; warehouse-bin behavior unchanged for legacy costing. |+| `jobMaterial.storageUnitId` repoint | Sweep repoints conditionally: job scope always; op scope only when net lineside ≤ 0 | Held-back (owed) stock must stay consumable at lineside by completion backflush. Fixes the latent unconditional-repoint bug inside the sweep path; unpick cases untouched. |+| Op-scope line selection | `pickingListLine.jobOperationId = op` AND line status ≠ Cancelled AND list not Draft/Cancelled; NULL-op lines wait for job completion | Line linkage = where stock was staged. Owed computed from the material's own op. |+| Multi-tenancy | Every new query scoped by `companyId`; edge fn keeps post-picking's existing auth model (verify_jwt; routes authorize) | Heuristics 1/4. No new tables → no new RLS. |++## Data Model Changes++One migration (`pnpm db:migrate:new picked-material-return-timing`):++```sql+ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "returnPickedMaterialTiming" TEXT NOT NULL DEFAULT 'job'+ CHECK ("returnPickedMaterialTiming" IN ('job', 'operation'));++ALTER TABLE "pickingListLine"+ ADD COLUMN IF NOT EXISTS "quantityReturned" NUMERIC NOT NULL DEFAULT 0;++-- backflush_job_materials: verbatim fork of 20260713190909 body + lineside on-hand+-- clamp (untracked rows only, bins with workCenterId set), floor 0, CONTINUE at <= 0.+```++No trigger change, no view change (`update_picking_list_status` untouched;+`outstandingQuantity` has no consumers; `pickingLists` view counts statuses only).++## API / Service Changes++- `post-picking` edge fn: extract tracked-return core (no `quantityPicked` decrement, no+ unconditional repoint), add `returnUntrackedMaterialRemainder`, add+ `returnOperationRemainders` / `returnJobRemainders` cases; keep legacy+ `returnPickedRemainder` case as thin wrapper for mid-deploy compatibility.+- MES `operations.service.ts`: `returnAllocatedRemaindersAtJobComplete` →+ `returnPickedRemainders` (single invoke; job scope when `job.status === 'Completed'`,+ else op scope).+- MES `inspection-lot.$id.complete-passed.tsx`: invoke sweep when the SQL auto-flip set+ the op Done.+- ERP `production.service.ts`: `returnPickedRemainders` / `returnPickedJobRemainders`+ helpers; wired in `operation.status.tsx` (on Done) and `$jobId.complete.tsx` (after+ RPC).+- ERP settings: `updateReturnPickedMaterialTimingSetting` + validator consts.+- MES `getPickedQuantitiesByJobMaterial`: expose `quantityReturned`; staged-at-lineside+ consumers use picked − returned.++## UI Changes++- ERP Inventory settings page: "Material return timing" ChoiceSelect card+ ("At job completion" / "At operation completion"), `incompletePickingListPolicy`+ pattern.+- Optional: "Returned" column in ERP PickingListLines.++## Acceptance Criteria++- [x] Policy `'operation'`: pick 100 untracked to lineside, op consumes 50, op → Done ⇒+ ledger shows Transfer lineside→source for the unconsumed remainder minus owed+ hold-back; picking-list header stays Completed/Partial.+- [x] Policy `'job'` (default): behavior unchanged at op-Done; at job completion BOTH+ tracked and untracked remainders return (untracked is new).+- [x] Job completed from ERP "Complete" button returns remainders (was: stranded).+- [ ] Op set Done from ERP dropdown/kanban triggers the op-scope sweep under+ `'operation'` policy.+- [ ] MES complete-passed (inspection) path job completion triggers the sweep.+- [x] Job-complete sweep no longer demotes Completed picking lists to In Progress.+- [x] Completion-time backflush never drives a lineside bin negative (clamp), and with+ scrap% > 0 the owed hold-back keeps backflush fully suppliable at job completion.+- [ ] Re-invoking any sweep is a no-op (idempotent).+- [x] Sweeps scoped by companyId throughout.++## Open Questions++- [x] Policy scope — **Answer:** company-wide `companySettings` column, default `'job'`+ (mirrors `incompletePickingListPolicy`).+- [x] Untracked material in scope — **Answer:** yes, auto-return under both timings;+ per-line/material quantity attribution, never bin sweep.+- [x] Return amount at op completion — **Answer:** full unconsumed remainder; op+ completed qty is final; backflush clamps.+- [x] ERP completion gap — **Answer:** fix in same feature via one shared choke point.+- [x] Owed formula scrap allowance (surfaced during design) — **Answer:** include it:+ `owed = (estimatedQuantity ÷ job.quantity) × op.quantityComplete`.++## Changelog++- 2026-08-04 — Spec written after research + grill (5 questions user-resolved).+ Implementation plan: `.ai/plans/2026-08-04-picked-material-return-timing.md`.+- 2026-08-04 — Implemented + migration applied + partially browser-verified+ (playbook `.ai/playbooks/picked-material-return-timing.md`): op-scope return+ with owed hold-back (job In Progress), job-scope return via MES finish AND the+ ERP Complete button, policy='job' no-op at op-Done, header non-demotion,+ "Returned N" badge, ledger closure (lineside nets to 0). Not yet exercised in+ browser: tracked (batch/serial) sweep path, ERP op-status-dropdown trigger,+ MES complete-passed trigger.diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.mdindex 1a98d1e47a..4a613d09ee 100644--- a/.claude/rules/mes-job-operation-ui.md+++ b/.claude/rules/mes-job-operation-ui.md@@ -36,12 +36,14 @@ redirects kinds it does not serve (no loops).`productionQuantity` (end calls `finishJobOperation`).- **`finishJobOperation`** (`operations.service.ts`) flips the op to `Done` (firingthe `sync_finish_job_operation` trigger that completes the job to inventory when- it's the last op). It then runs `returnAllocatedRemaindersAtJobComplete`: once- `job.status='Completed'`, it sweeps the job's tracked (batch/serial) picking-list- allocations and invokes the `post-picking` `returnPickedRemainder` case (via the- service-role client) to return each un-consumed lineside remainder to its- warehouse source. The SQL trigger can't call edge functions, so this is- orchestrated in TS.+ it's the last op). It then runs `returnPickedRemainders`: one `post-picking`+ sweep invoke (via the service-role client) — `returnJobRemainders` when+ `job.status='Completed'`, else `returnOperationRemainders` (which itself no-ops+ unless `companySettings.returnPickedMaterialTiming = 'operation'`). The sweep+ returns un-consumed lineside remainders (tracked AND untracked) to their+ warehouse source, booking `pickingListLine.quantityReturned`. The SQL trigger+ can't call edge functions, so this is orchestrated in TS. See+ `.ai/specs/2026-08-04-picked-material-return-timing.md`.## Componentsdiff --git a/.claude/rules/traceability-model.md b/.claude/rules/traceability-model.mdindex 98d90ad066..9263fe7379 100644--- a/.claude/rules/traceability-model.md+++ b/.claude/rules/traceability-model.md@@ -114,10 +114,18 @@ order sort in the app (MES `sortLotsByPickMethod` in `apps/mes/app/services/alloposts a negative Consumption row and, on partial use, **splits** the entity — the un-consumedremainder 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. At job-complete, `post-picking` `returnPickedRemainder` walks the picked entity's split lineage and-transfers each lineage entity's remaining lineside on-hand back to source (decrementing-`pickingListLineTrackedEntity`/`pickingListLine.quantityPicked`).+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:+`max(0, Σ(picked − returned) − max(quantityIssued, owed))`, newest-line-first — never a bin+sweep (the lineside bin is shared per work center). Spec:+`.ai/specs/2026-08-04-picked-material-return-timing.md`.**Gotcha:** the older `get_item_quantities_by_tracking_id` (`20260101163400`) still emitslegacy `shelfId` / `shelfName` and joins the `shelf` table — both column sets exist; checkdiff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsxindex b2ca8b5ad2..3870c0010d 100644--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx@@ -265,6 +265,9 @@ function PickingListLineItem({const itemName = item?.name ?? line.item?.name ?? "";const quantityToPick = Number(line.quantityToPick ?? 0);const quantityPicked = Number(line.quantityPicked ?? 0);+ const quantityReturned = Number(+ (line as { quantityReturned?: number | null }).quantityReturned ?? 0+ );const isPicked = quantityToPick > 0 && quantityPicked >= quantityToPick;const isShort = line.status === "Short";const isResolved = isPicked || isShort;@@ -375,6 +378,25 @@ function PickingListLineItem({))}</HStack>)}+ {quantityReturned > 0 && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge+ variant="secondary"+ className="gap-1 tabular-nums cursor-default"+ >+ <LuUndo2 />+ <Trans>Returned</Trans> {quantityReturned}+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-[240px]">+ <Trans>+ Unused picked material flushed back from the work center to the+ warehouse.+ </Trans>+ </TooltipContent>+ </Tooltip>+ )}{isTracked ? (<Badgevariant={isPicked ? "green" : quantityPicked > 0 ? "orange" : "red"}diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex ebe9c70c0a..97834e1dfc 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -2514,6 +2514,72 @@ export async function updateJobOperationStatus(.single();}+/**+ * Flush un-consumed picked material staged at lineside back to the warehouse+ * after an operation went 'Done'. If the operation was the last one, the SQL+ * interceptor has already completed the job — sweep the whole job (both+ * returnPickedMaterialTiming policies); otherwise sweep this operation's lines+ * (the post-picking edge function no-ops unless the policy is 'operation').+ * Pass a service-role client so the picking lines are readable regardless of+ * the caller's inventory permissions. Idempotent.+ */+export async function returnPickedRemaindersForOperation(+ client: SupabaseClient<Database>,+ args: { jobOperationId: string; userId: string; companyId: string }+) {+ const op = await client+ .from("jobOperation")+ .select("jobId")+ .eq("id", args.jobOperationId)+ .eq("companyId", args.companyId)+ .maybeSingle();+ const jobId = op.data?.jobId;+ if (!jobId) return { data: null, error: op.error };++ const job = await client+ .from("job")+ .select("status")+ .eq("id", jobId)+ .eq("companyId", args.companyId)+ .maybeSingle();+ if (!job.data) return { data: null, error: job.error };++ const body =+ job.data.status === "Completed"+ ? {+ type: "returnJobRemainders" as const,+ jobId,+ userId: args.userId,+ companyId: args.companyId+ }+ : {+ type: "returnOperationRemainders" as const,+ jobOperationId: args.jobOperationId,+ userId: args.userId,+ companyId: args.companyId+ };++ return client.functions.invoke("post-picking", { body });+}++/**+ * Job-scope sweep after an explicit job completion (the ERP Complete button).+ * The edge function guards on job.status = 'Completed' and is idempotent.+ */+export async function returnPickedRemaindersForJob(+ client: SupabaseClient<Database>,+ args: { jobId: string; userId: string; companyId: string }+) {+ return client.functions.invoke("post-picking", {+ body: {+ type: "returnJobRemainders",+ jobId: args.jobId,+ userId: args.userId,+ companyId: args.companyId+ }+ });+}+export async function updateJobOperationDueDate(client: SupabaseClient<Database>,id: string,diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex ac6d7c1c20..3ba3b166ba 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -219,6 +219,18 @@ export const incompletePickingListPolicyValidator = z.object({.default("warn")});+// When un-consumed picked material flushes back from the work-center lineside+// bin to the warehouse. 'job' (default) returns the remainder when the whole+// job completes; 'operation' returns each operation's remainder as soon as that+// operation is Done (holding back what completion-time backflush still needs).+export const returnPickedMaterialTimings = ["job", "operation"] as const;+export type ReturnPickedMaterialTiming =+ (typeof returnPickedMaterialTimings)[number];++export const returnPickedMaterialTimingValidator = z.object({+ returnPickedMaterialTiming: z.enum(returnPickedMaterialTimings).default("job")+});+export const updateLeadTimesOnReceiptValidator = z.object({updateLeadTimesOnReceipt: zfd.checkbox()});diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 42b19c007e..b6fbd82008 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -1515,6 +1515,17 @@ export async function updateIncompletePickingListPolicySetting(.eq("id", companyId);}+export async function updateReturnPickedMaterialTimingSetting(+ client: SupabaseClient<Database>,+ companyId: string,+ returnPickedMaterialTiming: "job" | "operation"+) {+ return client+ .from("companySettings")+ .update(sanitize({ returnPickedMaterialTiming }))+ .eq("id", companyId);+}+export async function upsertWebhook(client: SupabaseClient<Database>,webhook:diff --git a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.tsindex 747a49df34..20698e90a6 100644--- a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts@@ -3,7 +3,12 @@* Keep this list small; add only operations that must never run via /api/mcp.*/export const MCP_BLOCKED_TOOL_NAMES: readonly string[] = [- "settings_seedCompany"+ "settings_seedCompany",+ // Internal sweep orchestration invoked by job/operation completion flows.+ // Their args require a userId the MCP executor cannot inject (AuthField has+ // no such payload field), so direct calls would only ever fail validation.+ "production_returnPickedRemaindersForOperation",+ "production_returnPickedRemaindersForJob"];export function isMcpBlockedTool(name: string): boolean {diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 9914d472d7..260199e7c3 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-08-03T05:37:07.055Z",- "totalTools": 1410,+ "generated": "2026-08-04T14:07:12.782Z",+ "totalTools": 1411,"modules": 15,"tools": [{@@ -41306,6 +41306,37 @@]}},+ {+ "name": "settings_updateReturnPickedMaterialTimingSetting",+ "module": "settings",+ "classification": "WRITE",+ "description": "update return picked material timing setting",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "returnPickedMaterialTiming"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "returnPickedMaterialTiming": {+ "type": "string",+ "enum": [+ "job",+ "operation"+ ]+ }+ },+ "required": [+ "returnPickedMaterialTiming"+ ]+ }+ },{"name": "settings_upsertWebhook","module": "settings",diff --git a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx b/apps/erp/app/routes/x+/job+/$jobId.complete.tsxindex edaf0a2318..5ea24d10fa 100644--- a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx@@ -1,11 +1,15 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { jobCompleteValidator } from "~/modules/production";+import {+ jobCompleteValidator,+ returnPickedRemaindersForJob+} from "~/modules/production";import type { Handle } from "~/utils/handle";import { path, requestReferrer } from "~/utils/path";@@ -60,6 +64,28 @@ export async function action({ request, params }: ActionFunctionArgs) {// the sync_finish_job_operation interceptor, so the SQL function is the// single choke point for fulfillment.+ // Return picked-but-unconsumed material from lineside to the warehouse.+ // Runs after the RPC (backflush inside it must consume first). A sweep+ // failure never fails the completion — the sweep is idempotent and can be+ // re-triggered — so warn instead.+ const sweep = await returnPickedRemaindersForJob(getCarbonServiceRole(), {+ jobId,+ userId,+ companyId+ });+ if (sweep.error) {+ throw redirect(+ requestReferrer(request) ?? path.to.job(jobId),+ await flash(+ request,+ error(+ sweep.error,+ "Job completed, but returning picked material failed"+ )+ )+ );+ }+throw redirect(requestReferrer(request) ?? path.to.job(jobId),await flash(request, success("Job completed successfully"))diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsxindex 1109421ec4..904f42f615 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx@@ -122,6 +122,10 @@ export async function action({ request, params }: ActionFunctionArgs) {}}+ // A direct POST of status=Completed here bypasses complete_job_to_inventory+ // (no inventory receipt, no backflush) and therefore also skips the+ // picked-material return sweep. The UI never sends Completed to this route —+ // the Complete button uses $jobId.complete.tsx, which runs both.const update = await updateJobStatus(client, {id,status,diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.status.tsxindex 9428cce2ea..499e76511e 100644--- a/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx@@ -1,14 +1,18 @@import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import type { JobOperation } from "~/modules/production";-import { updateJobOperationStatus } from "~/modules/production";+import {+ returnPickedRemaindersForOperation,+ updateJobOperationStatus+} from "~/modules/production";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "production"});@@ -24,5 +28,29 @@ export async function action({ request }: ActionFunctionArgs) {);}+ if (status === "Done") {+ // Marking an operation Done may have completed the job via the SQL+ // interceptor. Return any picked-but-unconsumed material staged at+ // lineside; service role so the sweep can read picking lines regardless of+ // the caller's inventory permissions. Idempotent — a failure here doesn't+ // undo the status change, so surface it as a flash only.+ const sweep = await returnPickedRemaindersForOperation(+ getCarbonServiceRole(),+ { jobOperationId: id, userId, companyId }+ );+ if (sweep?.error) {+ return data(+ {},+ await flash(+ request,+ error(+ sweep.error,+ "Operation updated, but returning picked material failed"+ )+ )+ );+ }+ }+return {};}diff --git a/apps/erp/app/routes/x+/settings+/inventory.tsx b/apps/erp/app/routes/x+/settings+/inventory.tsxindex acf67a91d1..5c2561cc1c 100644--- a/apps/erp/app/routes/x+/settings+/inventory.tsx+++ b/apps/erp/app/routes/x+/settings+/inventory.tsx@@ -28,10 +28,12 @@ import { Trans, useLingui } from "@lingui/react/macro";import { useEffect } from "react";import {LuLayers,+ LuPackageCheck,LuShield,LuShieldCheck,LuTimerReset,- LuTriangleAlert+ LuTriangleAlert,+ LuUndo2} from "react-icons/lu";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useFetcher, useLoaderData } from "react-router";@@ -41,9 +43,11 @@ import {incompletePickingListPolicyValidator,kanbanOutputTypes,kanbanOutputValidator,+ returnPickedMaterialTimingValidator,shelfLifeSettingsValidator,updateIncompletePickingListPolicySetting,updateKanbanOutputSetting,+ updateReturnPickedMaterialTimingSetting,updateShelfLifeSettings} from "~/modules/settings";@@ -53,6 +57,7 @@ import { path } from "~/utils/path";type CalculatedInputScope = "AllInputs" | "ManagedInputsOnly";type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";type IncompletePickingListPolicy = "warn" | "error";+type ReturnPickedMaterialTiming = "job" | "operation";export const handle: Handle = {breadcrumb: msg`Inventory`,@@ -158,6 +163,31 @@ export async function action({ request }: ActionFunctionArgs) {success: true,message: "Picking list completion policy updated"};++ case "returnPickedMaterialTiming":+ const returnTimingValidation = await validator(+ returnPickedMaterialTimingValidator+ ).validate(formData);++ if (returnTimingValidation.error) {+ return { success: false, message: "Invalid form data" };+ }++ const returnTimingResult = await updateReturnPickedMaterialTimingSetting(+ client,+ companyId,+ returnTimingValidation.data.returnPickedMaterialTiming+ );+ if (returnTimingResult.error)+ return {+ success: false,+ message: returnTimingResult.error.message+ };++ return {+ success: true,+ message: "Material return timing updated"+ };}return { success: false, message: "Invalid form data" };@@ -341,6 +371,44 @@ export default function InventorySettingsRoute() {</CardFooter></ValidatedForm></Card>++ <Card>+ <ValidatedForm+ method="post"+ validator={returnPickedMaterialTimingValidator}+ defaultValues={{+ returnPickedMaterialTiming:+ (companySettings.returnPickedMaterialTiming as+ | ReturnPickedMaterialTiming+ | null+ | undefined) ?? "job"+ }}+ fetcher={fetcher}+ >+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Trans>Returning unused picked material</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Decide when material picked to a work center but not consumed+ flows back to the warehouse.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Hidden name="intent" value="returnPickedMaterialTiming" />+ <div className="flex flex-col gap-3 max-w-[640px]">+ <ReturnPickedMaterialTimingChoice />+ </div>+ </CardContent>+ <CardFooter>+ <Submit>+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card></VStack></ScrollArea>);@@ -496,3 +564,38 @@ function IncompletePickingListPolicyChoice() {</>);}++// ChoiceSelect for when un-consumed picked material returns to the warehouse.+// 'job' flushes the remainder when the whole job completes; 'operation' flushes+// each operation's remainder as soon as that operation is Done (holding back+// what completion-time backflush still needs).+function ReturnPickedMaterialTimingChoice() {+ const { t } = useLingui();+ const [value, setValue] = useControlField<ReturnPickedMaterialTiming>(+ "returnPickedMaterialTiming"+ );+ const current: ReturnPickedMaterialTiming = value ?? "job";+ return (+ <>+ <ChoiceSelect<ReturnPickedMaterialTiming>+ value={current}+ onChange={setValue}+ options={[+ {+ value: "job",+ title: t`At job completion`,+ description: t`Leftover staged material returns when the whole job completes.`,+ icon: <LuPackageCheck />+ },+ {+ value: "operation",+ title: t`At operation completion`,+ description: t`Each operation's unused material returns as soon as the operation is done.`,+ icon: <LuUndo2 />+ }+ ]}+ />+ <input type="hidden" name="returnPickedMaterialTiming" value={current} />+ </>+ );+}diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsxindex 4ab8fa1c29..7db9aee676 100644--- a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx+++ b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx@@ -6,6 +6,7 @@ import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { inspectionCompletePassedValidator } from "~/services/models";+import { returnPickedRemainders } from "~/services/operations.service";import {getInspectionOutcomeState,getSerialCompletionCandidates,@@ -14,6 +15,24 @@ import {} from "~/services/quality.server";import { path } from "~/utils/path";+// Completions posted here insert productionQuantity rows, whose SQL interceptor+// can auto-flip the operation to 'Done' (and complete the job) inside the DB —+// no app hook fires on that path, so the picked-material return sweep is+// orchestrated here after the postings land.+async function sweepIfOperationDone(+ serviceRole: Awaited<ReturnType<typeof getCarbonServiceRole>>,+ args: { jobOperationId: string; userId: string; companyId: string }+) {+ const op = await serviceRole+ .from("jobOperation")+ .select("status")+ .eq("id", args.jobOperationId)+ .eq("companyId", args.companyId)+ .maybeSingle();+ if (op.data?.status !== "Done") return;+ await returnPickedRemainders(serviceRole, args);+}+// Progressive completion while the lot stays open: any unit that passed// inspection can move on immediately, without waiting for the disposition.// Explicit (a button, not auto-on-pass) so a verdict typo doesn't need a@@ -93,6 +112,11 @@ export async function action({ request, params }: ActionFunctionArgs) {`Completing units failed after ${completions.completed} of ${candidates.length}`);}+ await sweepIfOperationDone(serviceRole, {+ jobOperationId: state.jobOperationId,+ userId,+ companyId+ });throw redirect(returnTo,await flash(@@ -126,6 +150,12 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ await sweepIfOperationDone(serviceRole, {+ jobOperationId: state.jobOperationId,+ userId,+ companyId+ });+throw redirect(returnTo,await flash(diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.tsindex a474b03b6c..e791bb7ef1 100644--- a/apps/mes/app/services/inventory.service.ts+++ b/apps/mes/app/services/inventory.service.ts@@ -355,9 +355,10 @@ export type JobMaterialPickedQuantity = {* How much of each job material has been picked, summed across every live picking-list* line that references it. A job material can legitimately span several picking lists,* so we sum per `jobMaterialId`. We only count lines whose parent list is actually being- * worked ("In Progress"/"Completed"): cancelling or drafting a list does NOT cascade a- * status down to its lines, so a Cancelled/Draft list would otherwise inflate the- * to-pick total with stale lines. Picking is optional — materials with no picking+ * worked ("In Progress"/"Completed"/"Partial"): cancelling or drafting a list does NOT+ * cascade a status down to its lines, so a Cancelled/Draft list would otherwise inflate+ * the to-pick total with stale lines. Quantities are net of returns (picked − returned —+ * what is still staged at lineside). Picking is optional — materials with no picking* activity simply have no entry in the returned map. Never throws (returns {}).*/export async function getPickedQuantitiesByJobMaterial(@@ -370,11 +371,11 @@ export async function getPickedQuantitiesByJobMaterial(const { data, error } = await client.from("pickingListLine").select(- "jobMaterialId, quantityToPick, quantityPicked, pickingList!inner(status)"+ "jobMaterialId, quantityToPick, quantityPicked, quantityReturned, pickingList!inner(status)").in("jobMaterialId", jobMaterialIds).neq("status", "Cancelled")- .in("pickingList.status", ["In Progress", "Completed"]);+ .in("pickingList.status", ["In Progress", "Completed", "Partial"]);if (error || !data) return picked;@@ -384,7 +385,13 @@ export async function getPickedQuantitiesByJobMaterial(quantityPicked: 0,quantityToPick: 0});- entry.quantityPicked += Number(line.quantityPicked ?? 0);+ // Net of returns: quantityPicked is gross (returns book quantityReturned+ // instead of decrementing it), and consumers of this map reason about what+ // is still staged at lineside.+ entry.quantityPicked += Math.max(+ 0,+ Number(line.quantityPicked ?? 0) - Number(line.quantityReturned ?? 0)+ );entry.quantityToPick += Number(line.quantityToPick ?? 0);}@@ -414,7 +421,7 @@ export async function getPickedTrackedEntitiesForMaterial(.eq("jobMaterialId", args.jobMaterialId).eq("companyId", args.companyId).neq("status", "Cancelled")- .in("pickingList.status", ["In Progress", "Completed"]);+ .in("pickingList.status", ["In Progress", "Completed", "Partial"]);if (error || !data) return [];diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 2022844f8e..03370eb0db 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -189,28 +189,28 @@ export async function finishJobOperation(// The status='Done' write fires the sync_finish_job_operation trigger, which// completes the job to inventory (job.status → 'Completed') when this was the- // last operation. At that point, return any picking-list-allocated batch/serial- // stock that was staged to lineside but not consumed back to its warehouse- // source — the SQL trigger can't call edge functions, so we orchestrate it here.- await returnAllocatedRemaindersAtJobComplete(client, args);+ // last operation. Return any picked-but-unconsumed stock staged at lineside+ // back to its warehouse source — the SQL trigger can't call edge functions,+ // so we orchestrate it here.+ await returnPickedRemainders(client, args);}return result;}/**- * When a job has just completed, sweep its tracked (batch/serial) picking-list- * allocations and return the un-consumed remainder of each from the lineside- * shelf back to the warehouse source (so it's re-allocatable, and inventory- * reflects only what was actually consumed). No-op unless the job is 'Completed'.- * Idempotent: `returnPickedRemainder` returns nothing once lineside on-hand is 0.+ * Flush un-consumed picked material (tracked AND untracked) from the lineside+ * shelf back to the warehouse via the post-picking sweep cases. Job just+ * completed → sweep the whole job (runs under both returnPickedMaterialTiming+ * policies). Otherwise → sweep this operation's lines; the edge function itself+ * no-ops unless the company policy is 'operation'. Both sweeps are idempotent.** Uses the client `finishJobOperation` is given — every caller passes a- * service-role client, so the picking allocations (an inventory table the- * finishing operator may not have RLS access to) are always readable and the- * returns aren't silently skipped for production-only roles.+ * service-role client, so the picking lines (an inventory table the finishing+ * operator may not have RLS access to) are always readable and the returns+ * aren't silently skipped for production-only roles.*/-async function returnAllocatedRemaindersAtJobComplete(+export async function returnPickedRemainders(client: SupabaseClient<Database>,args: {jobOperationId: string;@@ -222,57 +222,44 @@ async function returnAllocatedRemaindersAtJobComplete(.from("jobOperation").select("jobId").eq("id", args.jobOperationId)+ .eq("companyId", args.companyId).maybeSingle();const jobId = op.data?.jobId;if (!jobId) return;const job = await client.from("job")- .select("status, locationId")+ .select("status").eq("id", jobId)+ .eq("companyId", args.companyId).maybeSingle();- const locationId = job.data?.locationId;- if (job.data?.status !== "Completed" || !locationId) return;-- const { data: lines } = await client- .from("pickingListLine")- .select("id, pickingListId, pickingListLineTrackedEntity(trackedEntityId)")- .eq("jobId", jobId)- .neq("status", "Cancelled");- if (!lines?.length) return;-- const returns = lines.flatMap((line) => {- const allocations =- (line.pickingListLineTrackedEntity as Array<{- trackedEntityId: string;- }> | null) ?? [];- return allocations.map((allocation) =>- client.functions.invoke("post-picking", {- body: {- type: "returnPickedRemainder",- pickingListId: line.pickingListId,- pickingListLineId: line.id,- trackedEntityId: allocation.trackedEntityId,- locationId,+ if (!job.data) return;++ const body =+ job.data.status === "Completed"+ ? {+ type: "returnJobRemainders" as const,+ jobId,userId: args.userId,companyId: args.companyId}- })- );- });-- // `functions.invoke` resolves to `{ data, error }` rather than rejecting, so a- // failed return never surfaces through Promise.all — inspect each result and log- // it, otherwise a stranded lineside remainder is lost silently.- const results = await Promise.all(returns);- for (const { error } of results) {- if (error) {- log.error("returnPickedRemainder failed at job complete", {- error,- jobId,- companyId: args.companyId- });- }+ : {+ type: "returnOperationRemainders" as const,+ jobOperationId: args.jobOperationId,+ userId: args.userId,+ companyId: args.companyId+ };++ // `functions.invoke` resolves to `{ data, error }` rather than rejecting —+ // inspect and log, otherwise a stranded lineside remainder is lost silently.+ const { error } = await client.functions.invoke("post-picking", { body });+ if (error) {+ log.error("picked-material return sweep failed", {+ error,+ jobId,+ scope: body.type,+ companyId: args.companyId+ });}}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 13c0f1b2ea..deb65ecfda 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -45153,6 +45153,9 @@ export default {{$ref: "#/parameters/rowFilter.pickingListLine.customFields"},+ {+ $ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"+ },{$ref: "#/parameters/select"},@@ -45266,6 +45269,9 @@ export default {{$ref: "#/parameters/rowFilter.pickingListLine.customFields"},+ {+ $ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"+ },{$ref: "#/parameters/preferReturn"}@@ -45333,6 +45339,9 @@ export default {{$ref: "#/parameters/rowFilter.pickingListLine.customFields"},+ {+ $ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"+ },{$ref: "#/parameters/body.pickingListLine"},@@ -82998,6 +83007,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.includeMaterialsOnTraveler"},+ {+ $ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"+ },{$ref: "#/parameters/select"},@@ -83195,6 +83207,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.includeMaterialsOnTraveler"},+ {+ $ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"+ },{$ref: "#/parameters/preferReturn"}@@ -83346,6 +83361,9 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.includeMaterialsOnTraveler"},+ {+ $ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"+ },{$ref: "#/parameters/body.companySettings"},@@ -116446,7 +116464,8 @@ export default {"status","companyId","createdBy",- "createdAt"+ "createdAt",+ "quantityReturned"],properties: {id: {@@ -116545,6 +116564,11 @@ export default {},customFields: {format: "jsonb"+ },+ quantityReturned: {+ default: 0,+ format: "numeric",+ type: "number"}},type: "object"@@ -134379,7 +134403,8 @@ export default {"plmReleaseControl","autoSelectMaterialWithoutPickingList","incompletePickingListPolicy",- "includeMaterialsOnTraveler"+ "includeMaterialsOnTraveler",+ "returnPickedMaterialTiming"],properties: {id: {@@ -134630,6 +134655,11 @@ export default {default: false,format: "boolean",type: "boolean"+ },+ returnPickedMaterialTiming: {+ default: "job",+ format: "text",+ type: "string"}},type: "object"@@ -159409,6 +159439,12 @@ export default {in: "query",type: "string"},+ "rowFilter.pickingListLine.quantityReturned": {+ name: "quantityReturned",+ required: false,+ in: "query",+ type: "string"+ },"body.storageType": {name: "storageType",description: "storageType",@@ -179571,6 +179607,12 @@ export default {in: "query",type: "string"},+ "rowFilter.companySettings.returnPickedMaterialTiming": {+ name: "returnPickedMaterialTiming",+ required: false,+ in: "query",+ type: "string"+ },"body.part": {name: "part",description: "part",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 3b61af76da..6ad4b7677d 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -6757,6 +6757,7 @@ export type Database = {qualityDispatchNotificationGroup: string[] | nullqualityIssueTarget: numberquoteLineCategoryMarkups: Json | null+ returnPickedMaterialTiming: stringrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]samplingStandard: Database["public"]["Enums"]["samplingStandard"]@@ -6805,6 +6806,7 @@ export type Database = {qualityDispatchNotificationGroup?: string[] | nullqualityIssueTarget?: numberquoteLineCategoryMarkups?: Json | null+ returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]@@ -6853,6 +6855,7 @@ export type Database = {qualityDispatchNotificationGroup?: string[] | nullqualityIssueTarget?: numberquoteLineCategoryMarkups?: Json | null+ returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]@@ -35311,6 +35314,7 @@ export type Database = {outstandingQuantity: number | nullpickingListId: stringquantityPicked: number+ quantityReturned: numberquantityToPick: numberstatus: Database["public"]["Enums"]["pickingListLineStatus"]storageUnitId: string | null@@ -35331,6 +35335,7 @@ export type Database = {outstandingQuantity?: number | nullpickingListId: stringquantityPicked?: number+ quantityReturned?: numberquantityToPick: numberstatus?: Database["public"]["Enums"]["pickingListLineStatus"]storageUnitId?: string | null@@ -35351,6 +35356,7 @@ export type Database = {outstandingQuantity?: number | nullpickingListId?: stringquantityPicked?: number+ quantityReturned?: numberquantityToPick?: numberstatus?: Database["public"]["Enums"]["pickingListLineStatus"]storageUnitId?: string | null@@ -66770,14 +66776,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -70717,14 +70723,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 3b61af76da..6ad4b7677d 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -6757,6 +6757,7 @@ export type Database = {qualityDispatchNotificationGroup: string[] | nullqualityIssueTarget: numberquoteLineCategoryMarkups: Json | null+ returnPickedMaterialTiming: stringrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]samplingStandard: Database["public"]["Enums"]["samplingStandard"]@@ -6805,6 +6806,7 @@ export type Database = {qualityDispatchNotificationGroup?: string[] | nullqualityIssueTarget?: numberquoteLineCategoryMarkups?: Json | null+ returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]@@ -6853,6 +6855,7 @@ export type Database = {qualityDispatchNotificationGroup?: string[] | nullqualityIssueTarget?: numberquoteLineCategoryMarkups?: Json | null+ returnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]samplingStandard?: Database["public"]["Enums"]["samplingStandard"]@@ -35311,6 +35314,7 @@ export type Database = {outstandingQuantity: number | nullpickingListId: stringquantityPicked: number+ quantityReturned: numberquantityToPick: numberstatus: Database["public"]["Enums"]["pickingListLineStatus"]storageUnitId: string | null@@ -35331,6 +35335,7 @@ export type Database = {outstandingQuantity?: number | nullpickingListId: stringquantityPicked?: number+ quantityReturned?: numberquantityToPick: numberstatus?: Database["public"]["Enums"]["pickingListLineStatus"]storageUnitId?: string | null@@ -35351,6 +35356,7 @@ export type Database = {outstandingQuantity?: number | nullpickingListId?: stringquantityPicked?: number+ quantityReturned?: numberquantityToPick?: numberstatus?: Database["public"]["Enums"]["pickingListLineStatus"]storageUnitId?: string | null@@ -66770,14 +66776,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -70717,14 +70723,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.tsindex f4f96ed08f..3d936d2fe2 100644--- a/packages/database/supabase/functions/post-picking/index.ts+++ b/packages/database/supabase/functions/post-picking/index.ts@@ -88,6 +88,24 @@ const payloadValidator = z.discriminatedUnion("type", [locationId: z.string(),userId: z.string(),companyId: z.string()+ }),+ // Sweep every picking-list line of one operation (policy-gated: no-ops unless+ // companySettings.returnPickedMaterialTiming = 'operation') or of one job+ // (runs under both policies; requires job.status = 'Completed'). Tracked lines+ // return via the split-lineage walk; untracked lines return+ // picked − returned − max(issued, owed) per job material, where `owed` holds+ // back what completion-time backflush still needs.+ z.object({+ type: z.literal("returnOperationRemainders"),+ jobOperationId: z.string(),+ userId: z.string(),+ companyId: z.string()+ }),+ z.object({+ type: z.literal("returnJobRemainders"),+ jobId: z.string(),+ userId: z.string(),+ companyId: z.string()})]);@@ -725,14 +743,8 @@ serve(async (req: Request) => {}case "returnPickedRemainder": {- const {- pickingListId,- pickingListLineId,- trackedEntityId,- locationId,- userId,- companyId- } = validatedPayload;+ const { pickingListLineId, trackedEntityId, locationId, userId, companyId } =+ validatedPayload;await db.transaction().execute(async (trx) => {const line = await trx@@ -742,164 +754,88 @@ serve(async (req: Request) => {.selectAll().executeTakeFirstOrThrow();- const lineside = line.toStorageUnitId;-- // Return target = the bin this lot was actually PICKED from, recorded- // on its Pick trackedActivity at pick time — not the line's stale- // generation-time source bin, which can be wrong per-lot and is null- // for a shortage line that later got picked anyway.- const pickActivities = await trx- .selectFrom("trackedActivity as ta")- .innerJoin(- "trackedActivityInput as tai",- "tai.trackedActivityId",- "ta.id"- )- .where("ta.type", "=", "Pick")- .where("ta.sourceDocument", "=", "Picking List")- .where("ta.sourceDocumentId", "=", line.pickingListId)- .where("tai.trackedEntityId", "=", trackedEntityId)- .where("ta.companyId", "=", companyId)- .where("tai.companyId", "=", companyId)- .orderBy("ta.createdAt", "desc")- .select("ta.attributes")- .execute();-- // Use the LATEST pick for this line (activities are newest-first). Its- // "From Shelf" is the current truth — even if null (picked from an- // unassigned bin), fall through to the line bin rather than reusing an- // older pick's stale shelf.- const latestPickForLine = pickActivities- .map((a) => a.attributes as Record<string, unknown> | null)- // Disambiguate if the same entity was picked on multiple lines.- .find((a) => a?.["Picking List Line"] === pickingListLineId);- const pickedFromShelf = latestPickForLine?.["From Shelf"] as- | string- | null- | undefined;-- const source = pickedFromShelf ?? line.storageUnitId;- // No lineside stage or no source to return to → nothing to do.- if (!lineside || !source) return;-- // Walk the picked entity's split lineage (picked entity + every split- // descendant). A partial consume splits the un-consumed remainder into- // a new entity, so the leftover stock at lineside sits under a- // descendant, not the originally-picked entity.- const lineage = new Set<string>([trackedEntityId]);- let frontier: string[] = [trackedEntityId];- while (frontier.length > 0) {- const rows = await trx- .selectFrom("trackedActivityInput as tai")- .innerJoin(- "trackedActivityOutput as tao",- "tao.trackedActivityId",- "tai.trackedActivityId"- )- .where("tai.trackedEntityId", "in", frontier)- .where("tai.companyId", "=", companyId)- .whereRef("tao.trackedEntityId", "<>", "tai.trackedEntityId")- .select("tao.trackedEntityId as id")- .distinct()- .execute();- const next: string[] = [];- for (const r of rows) {- if (r.id && !lineage.has(r.id)) {- lineage.add(r.id);- next.push(r.id);- }- }- frontier = next;- }-- // Transfer each lineage entity's remaining lineside on-hand back to- // the warehouse source bin.- const inserts: ItemLedgerInsert[] = [];- let totalReturned = 0;- for (const entityId of lineage) {- const onHandRow = await trx- .selectFrom("itemLedger")- .where("trackedEntityId", "=", entityId)- .where("storageUnitId", "=", lineside)- .where("itemId", "=", line.itemId)- .where("companyId", "=", companyId)- .select((eb) => eb.fn.sum<number>("quantity").as("qty"))- .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: pickingListId,- trackedEntityId: entityId,- userId,- companyId- })- );- totalReturned += onHand;+ const totalReturned = await returnTrackedAllocationRemainder(trx, {+ today,+ line,+ trackedEntityId,+ locationId,+ userId,+ companyId+ });++ // Legacy single-allocation call: restore the consumption pointer+ // only when something actually returned (matching the original+ // early-return behavior). The sweep cases decide per material.+ if (totalReturned > 0) {+ await restoreJobMaterialSource(trx, line, userId);}+ });+ break;+ }- if (totalReturned <= 0) return;-- await trx.insertInto("itemLedger").values(inserts).execute();+ case "returnOperationRemainders": {+ const { jobOperationId, userId, companyId } = validatedPayload;- // Decrement the recorded picked qty by what was returned so the lot is- // re-allocatable and the picked/to-pick display reflects reality.- const allocation = await trx- .selectFrom("pickingListLineTrackedEntity")- .where("pickingListLineId", "=", pickingListLineId)- .where("trackedEntityId", "=", trackedEntityId)- .selectAll()+ await db.transaction().execute(async (trx) => {+ const settings = await trx+ .selectFrom("companySettings")+ .where("id", "=", companyId)+ .select("returnPickedMaterialTiming").executeTakeFirst();- if (allocation) {- const nextQuantity = Math.max(- 0,- Number(allocation.quantity ?? 0) - totalReturned- );- const nextPicked = Math.max(- 0,- Number(allocation.quantityPicked ?? 0) - totalReturned- );- if (nextPicked <= 0) {- await trx- .deleteFrom("pickingListLineTrackedEntity")- .where("pickingListLineId", "=", pickingListLineId)- .where("trackedEntityId", "=", trackedEntityId)- .execute();- } else {- await trx- .updateTable("pickingListLineTrackedEntity")- .set({ quantity: nextQuantity, quantityPicked: nextPicked })- .where("pickingListLineId", "=", pickingListLineId)- .where("trackedEntityId", "=", trackedEntityId)- .execute();- }- }+ // The policy gate lives here (not at call sites) so every op-Done+ // path can invoke unconditionally.+ if (settings?.returnPickedMaterialTiming !== "operation") return;- const nextLinePicked = Math.max(- 0,- Number(line.quantityPicked ?? 0) - totalReturned- );- await trx- .updateTable("pickingListLine")- .set({- quantityPicked: nextLinePicked,- // Fully returned → the line is no longer picked; mirror unpick's- // reset so status doesn't linger on 'Picked' with 0 picked qty.- ...(nextLinePicked <= 0 ? { status: "Pending" as const } : {}),- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .where("id", "=", pickingListLineId)+ const op = await trx+ .selectFrom("jobOperation")+ .where("id", "=", jobOperationId).where("companyId", "=", companyId)- .execute();+ .select(["id", "jobId", "quantityComplete"])+ .executeTakeFirstOrThrow();+ if (!op.jobId) return;- await restoreJobMaterialSource(trx, line, userId);+ const job = await trx+ .selectFrom("job")+ .where("id", "=", op.jobId)+ .where("companyId", "=", companyId)+ .select(["id", "quantity", "locationId", "status"])+ .executeTakeFirstOrThrow();+ if (!job.locationId) return;++ await runReturnSweep(trx, {+ scope: "operation",+ job: { id: job.id, quantity: job.quantity, locationId: job.locationId },+ opId: op.id,+ opQuantityComplete: Number(op.quantityComplete ?? 0),+ today,+ userId,+ companyId+ });+ });+ break;+ }++ case "returnJobRemainders": {+ const { jobId, userId, companyId } = validatedPayload;++ await db.transaction().execute(async (trx) => {+ const job = await trx+ .selectFrom("job")+ .where("id", "=", jobId)+ .where("companyId", "=", companyId)+ .select(["id", "quantity", "locationId", "status"])+ .executeTakeFirstOrThrow();+ // Job scope is the final catch-all: only a completed job's remainder+ // is provably surplus (completion-time backflush has already run).+ if (job.status !== "Completed" || !job.locationId) return;++ await runReturnSweep(trx, {+ scope: "job",+ job: { id: job.id, quantity: job.quantity, locationId: job.locationId },+ today,+ userId,+ companyId+ });});break;}@@ -977,3 +913,477 @@ async function restoreJobMaterialSource(.where("id", "=", line.jobMaterialId).execute();}++type ReturnSweepLine = {+ id: string;+ pickingListId: string;+ jobMaterialId: string;+ jobOperationId: string | null;+ itemId: string;+ quantityPicked: number | string | null;+ quantityReturned: number | string | null;+ storageUnitId: string | null;+ toStorageUnitId: string | null;+ createdAt: string | Date | null;+};++// Return the un-consumed remainder of ONE tracked (batch/serial) allocation from+// the lineside shelf back to the warehouse source. Walks the picked entity's+// split lineage and moves whatever is still physically on hand at the lineside+// bin (a partial consume splits the remainder into a NEW entity the picking line+// never references). Idempotent: nothing on hand → nothing moves.+//+// Books the return on pickingListLine.quantityReturned instead of decrementing+// quantityPicked — the update_picking_list_status trigger reacts to+// quantityPicked/status changes and would demote a Completed/Partial header back+// to In Progress. quantityPicked stays gross-picked; net staged at lineside is+// quantityPicked - quantityReturned. The allocation row keeps its historical+// decrement/delete-at-0 so the lot becomes re-allocatable (the availability RPCs+// net allocations out of on-hand). Does NOT repoint jobMaterial.storageUnitId —+// callers decide that per material.+async function returnTrackedAllocationRemainder(+ trx: any,+ args: {+ today: string;+ line: {+ id: string;+ pickingListId: string;+ itemId: string;+ storageUnitId: string | null;+ toStorageUnitId: string | null;+ };+ trackedEntityId: string;+ locationId: string;+ userId: string;+ companyId: string;+ }+): Promise<number> {+ const { today, line, trackedEntityId, locationId, userId, companyId } = args;+ const lineside = line.toStorageUnitId;++ // Return target = the bin this lot was actually PICKED from, recorded+ // on its Pick trackedActivity at pick time — not the line's stale+ // generation-time source bin, which can be wrong per-lot and is null+ // for a shortage line that later got picked anyway.+ const pickActivities = await trx+ .selectFrom("trackedActivity as ta")+ .innerJoin("trackedActivityInput as tai", "tai.trackedActivityId", "ta.id")+ .where("ta.type", "=", "Pick")+ .where("ta.sourceDocument", "=", "Picking List")+ .where("ta.sourceDocumentId", "=", line.pickingListId)+ .where("tai.trackedEntityId", "=", trackedEntityId)+ .where("ta.companyId", "=", companyId)+ .where("tai.companyId", "=", companyId)+ .orderBy("ta.createdAt", "desc")+ .select("ta.attributes")+ .execute();++ // Use the LATEST pick for this line (activities are newest-first). Its+ // "From Shelf" is the current truth — even if null (picked from an+ // unassigned bin), fall through to the line bin rather than reusing an+ // older pick's stale shelf.+ const latestPickForLine = pickActivities+ .map((a: { attributes: unknown }) => a.attributes as Record<string, unknown> | null)+ // Disambiguate if the same entity was picked on multiple lines.+ .find((a: Record<string, unknown> | null) => a?.["Picking List Line"] === line.id);+ const pickedFromShelf = latestPickForLine?.["From Shelf"] as+ | string+ | null+ | undefined;++ const source = pickedFromShelf ?? line.storageUnitId;+ // No lineside stage or no source to return to → nothing to do.+ if (!lineside || !source) return 0;++ // Walk the picked entity's split lineage (picked entity + every split+ // descendant). A partial consume splits the un-consumed remainder into+ // a new entity, so the leftover stock at lineside sits under a+ // descendant, not the originally-picked entity.+ const lineage = new Set<string>([trackedEntityId]);+ let frontier: string[] = [trackedEntityId];+ while (frontier.length > 0) {+ const rows = await trx+ .selectFrom("trackedActivityInput as tai")+ .innerJoin(+ "trackedActivityOutput as tao",+ "tao.trackedActivityId",+ "tai.trackedActivityId"+ )+ .where("tai.trackedEntityId", "in", frontier)+ .where("tai.companyId", "=", companyId)+ .whereRef("tao.trackedEntityId", "<>", "tai.trackedEntityId")+ .select("tao.trackedEntityId as id")+ .distinct()+ .execute();+ const next: string[] = [];+ for (const r of rows) {+ if (r.id && !lineage.has(r.id)) {+ lineage.add(r.id);+ next.push(r.id);+ }+ }+ frontier = next;+ }++ // Transfer each lineage entity's remaining lineside on-hand back to+ // the warehouse source bin.+ const inserts: ItemLedgerInsert[] = [];+ let totalReturned = 0;+ for (const entityId of lineage) {+ const onHandRow = await trx+ .selectFrom("itemLedger")+ .where("trackedEntityId", "=", entityId)+ .where("storageUnitId", "=", lineside)+ .where("itemId", "=", line.itemId)+ .where("companyId", "=", companyId)+ .select((eb: any) => eb.fn.sum<number>("quantity").as("qty"))+ .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+ })+ );+ totalReturned += onHand;+ }++ if (totalReturned <= 0) return 0;++ await trx.insertInto("itemLedger").values(inserts).execute();++ // Decrement the recorded allocation by what was returned so the lot is+ // re-allocatable.+ const allocation = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", line.id)+ .where("trackedEntityId", "=", trackedEntityId)+ .selectAll()+ .executeTakeFirst();+ if (allocation) {+ const nextQuantity = Math.max(+ 0,+ Number(allocation.quantity ?? 0) - totalReturned+ );+ const nextPicked = Math.max(+ 0,+ Number(allocation.quantityPicked ?? 0) - totalReturned+ );+ if (nextPicked <= 0) {+ await trx+ .deleteFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", line.id)+ .where("trackedEntityId", "=", trackedEntityId)+ .execute();+ } else {+ await trx+ .updateTable("pickingListLineTrackedEntity")+ .set({ quantity: nextQuantity, quantityPicked: nextPicked })+ .where("pickingListLineId", "=", line.id)+ .where("trackedEntityId", "=", trackedEntityId)+ .execute();+ }+ }++ await trx+ .updateTable("pickingListLine")+ .set((eb: any) => ({+ quantityReturned: eb("quantityReturned", "+", totalReturned),+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ }))+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();++ return totalReturned;+}++// Return the un-consumed remainder of an UNTRACKED job material. There is no+// per-line consumption attribution (jobMaterial.quantityIssued is one counter+// across N lines), so the remainder is computed per material —+// returnable = max(0, Σ(line.picked − line.returned) − max(issued, owed))+// — and allocated back across the material's lines newest-first. `owed` is what+// completion-time backflush is still entitled to draw from lineside; holding it+// back is what keeps the top-up suppliable (never derived from bin on-hand: the+// lineside bin is shared per work center across jobs).+async function returnUntrackedMaterialRemainder(+ trx: any,+ args: {+ today: string;+ material: { id: string; itemId: string; quantityIssued: number | string | null };+ lines: ReturnSweepLine[];+ owed: number;+ locationId: string;+ userId: string;+ companyId: string;+ }+): Promise<number> {+ const { today, material, lines, owed, locationId, userId, companyId } = args;++ const staged = lines+ .map((l) => ({+ ...l,+ stagedNet: Math.max(+ 0,+ Number(l.quantityPicked ?? 0) - Number(l.quantityReturned ?? 0)+ )+ }))+ .filter((l) => l.stagedNet > 0 && l.toStorageUnitId);+ if (staged.length === 0) return 0;++ const totalStaged = staged.reduce((sum, l) => sum + l.stagedNet, 0);+ const issued = Number(material.quantityIssued ?? 0);+ let returnable = Math.max(0, totalStaged - Math.max(issued, owed));+ if (returnable <= 0) return 0;++ // Newest-first: return the most recently staged stock, deterministic.+ staged.sort(+ (a, b) =>+ new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime()+ );++ // Lazy fallback bin for lines picked from an unassigned source.+ let fallbackBin: string | null | undefined;+ const resolveFallbackBin = async () => {+ if (fallbackBin !== undefined) return fallbackBin;+ const pickMethod = await trx+ .selectFrom("pickMethod")+ .where("itemId", "=", material.itemId)+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .select("defaultStorageUnitId")+ .executeTakeFirst();+ fallbackBin = pickMethod?.defaultStorageUnitId ?? null;+ return fallbackBin;+ };++ const inserts: ItemLedgerInsert[] = [];+ let totalReturned = 0;+ for (const line of staged) {+ if (returnable <= 0) break;+ const quantity = Math.min(line.stagedNet, returnable);+ // Return target: the line's source bin, else the item's default pick bin,+ // else location-level unassigned stock (mirrors picks from unassigned bins;+ // never strands the return).+ const target = line.storageUnitId ?? (await resolveFallbackBin());++ const base = {+ postingDate: today,+ itemId: line.itemId,+ locationId,+ entryType: "Transfer" as const,+ documentType: "Direct Transfer" as const,+ documentId: line.pickingListId,+ createdBy: userId,+ companyId+ };+ inserts.push(+ { ...base, quantity: -quantity, storageUnitId: line.toStorageUnitId },+ { ...base, quantity, storageUnitId: target }+ );++ await trx+ .updateTable("pickingListLine")+ .set((eb: any) => ({+ quantityReturned: eb("quantityReturned", "+", quantity),+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ }))+ .where("id", "=", line.id)+ .where("companyId", "=", companyId)+ .execute();++ returnable -= quantity;+ totalReturned += quantity;+ }++ if (totalReturned <= 0) return 0;+ await trx.insertInto("itemLedger").values(inserts).execute();+ return totalReturned;+}++// Sweep every live picking-list line of one operation (scope "operation") or of+// one whole job (scope "job"), returning each material's un-consumed remainder+// and repointing jobMaterial.storageUnitId back at the warehouse source when+// nothing staged remains to consume.+async function runReturnSweep(+ trx: any,+ args: {+ scope: "operation" | "job";+ job: { id: string; quantity: number | string | null; locationId: string };+ opId?: string;+ opQuantityComplete?: number;+ today: string;+ userId: string;+ companyId: string;+ }+) {+ const { scope, job, opId, opQuantityComplete, today, userId, companyId } = args;++ let lineQuery = trx+ .selectFrom("pickingListLine as pll")+ .innerJoin("pickingList as pl", "pl.id", "pll.pickingListId")+ .where("pll.companyId", "=", companyId)+ .where("pll.jobId", "=", job.id)+ .where("pll.status", "<>", "Cancelled")+ .where("pl.status", "not in", ["Draft", "Cancelled"])+ .select([+ "pll.id",+ "pll.pickingListId",+ "pll.jobMaterialId",+ "pll.jobOperationId",+ "pll.itemId",+ "pll.quantityPicked",+ "pll.quantityReturned",+ "pll.storageUnitId",+ "pll.toStorageUnitId",+ "pll.createdAt"+ ]);+ if (scope === "operation") {+ lineQuery = lineQuery.where("pll.jobOperationId", "=", opId);+ }+ const lines: ReturnSweepLine[] = await lineQuery.execute();+ if (lines.length === 0) return;++ const materialIds = [...new Set(lines.map((l) => l.jobMaterialId))];+ const materials = await trx+ .selectFrom("jobMaterial")+ .where("id", "in", materialIds)+ .where("companyId", "=", companyId)+ .select([+ "id",+ "itemId",+ "jobOperationId",+ "quantityIssued",+ "estimatedQuantity",+ "requiresBatchTracking",+ "requiresSerialTracking"+ ])+ .execute();++ const jobQuantity = Number(job.quantity ?? 0);++ for (const material of materials) {+ const materialLines = lines.filter((l) => l.jobMaterialId === material.id);+ const tracked =+ Boolean(material.requiresBatchTracking) ||+ Boolean(material.requiresSerialTracking);++ // What completion-time backflush is still entitled to consume from lineside.+ // Op scope, material owned by the completing op: its completed quantity is+ // final, so owed = (estimatedQuantity ÷ job quantity) × op completed — the+ // estimated ratio keeps the scrap allowance staged. A material owned by a+ // DIFFERENT (possibly not-yet-run) op has no final quantity yet: hold its+ // full estimate. Job scope: backflush already ran inside+ // complete_job_to_inventory, nothing further is owed.+ let owed = 0;+ if (scope === "operation") {+ const estimated = Number(material.estimatedQuantity ?? 0);+ if (material.jobOperationId === opId && jobQuantity > 0) {+ owed = (estimated / jobQuantity) * Number(opQuantityComplete ?? 0);+ } else {+ owed = estimated;+ }+ }++ if (tracked) {+ for (const line of materialLines) {+ const allocations = await trx+ .selectFrom("pickingListLineTrackedEntity")+ .where("pickingListLineId", "=", line.id)+ .select("trackedEntityId")+ .execute();+ for (const allocation of allocations) {+ await returnTrackedAllocationRemainder(trx, {+ today,+ line,+ trackedEntityId: allocation.trackedEntityId,+ locationId: job.locationId,+ userId,+ companyId+ });+ }+ }+ } else {+ await returnUntrackedMaterialRemainder(trx, {+ today,+ material,+ lines: materialLines,+ owed,+ locationId: job.locationId,+ userId,+ companyId+ });+ }++ await maybeRestoreJobMaterialSource(trx, {+ scope,+ material: { id: material.id, quantityIssued: material.quantityIssued },+ userId,+ companyId+ });+ }+}++// Repoint jobMaterial.storageUnitId back at the warehouse source once nothing+// staged remains for it to consume at lineside. Job scope: the job is done —+// always restore. Op scope: restore only when net staged (Σ picked − returned+// across ALL live lines of the material) is covered by what was already issued —+// otherwise the held-back (owed) stock must stay consumable at lineside by the+// completion-time backflush. Skips the restore when no line has a source bin,+// rather than nulling the pointer.+async function maybeRestoreJobMaterialSource(+ trx: any,+ args: {+ scope: "operation" | "job";+ material: { id: string; quantityIssued: number | string | null };+ userId: string;+ companyId: string;+ }+) {+ const { scope, material, userId, companyId } = args;++ const liveLines = await trx+ .selectFrom("pickingListLine as pll")+ .innerJoin("pickingList as pl", "pl.id", "pll.pickingListId")+ .where("pll.jobMaterialId", "=", material.id)+ .where("pll.companyId", "=", companyId)+ .where("pll.status", "<>", "Cancelled")+ .where("pl.status", "not in", ["Draft", "Cancelled"])+ .select(["pll.storageUnitId", "pll.quantityPicked", "pll.quantityReturned", "pll.createdAt"])+ .execute();++ if (scope === "operation") {+ const netStaged = liveLines.reduce(+ (sum: number, l: ReturnSweepLine) =>+ sum ++ Math.max(0, Number(l.quantityPicked ?? 0) - Number(l.quantityReturned ?? 0)),+ 0+ );+ if (netStaged - Number(material.quantityIssued ?? 0) > 0) return;+ }++ const sourceLine = liveLines+ .filter((l: ReturnSweepLine) => l.storageUnitId)+ .sort(+ (a: ReturnSweepLine, b: ReturnSweepLine) =>+ new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime()+ )[0];+ if (!sourceLine) return;++ await restoreJobMaterialSource(+ trx,+ { jobMaterialId: material.id, storageUnitId: sourceLine.storageUnitId },+ userId+ );+}diff --git a/packages/database/supabase/migrations/20260804111631_picked-material-return-timing.sql b/packages/database/supabase/migrations/20260804111631_picked-material-return-timing.sqlnew file mode 100644index 0000000000..abc62d951e--- /dev/null+++ b/packages/database/supabase/migrations/20260804111631_picked-material-return-timing.sql@@ -0,0 +1,463 @@+-- Picked-material return timing (spec: .ai/specs/2026-08-04-picked-material-return-timing.md)+--+-- 1. companySettings.returnPickedMaterialTiming: when unconsumed picked material+-- flushes back from the work-center lineside bin to the warehouse — at job+-- completion (default, current behavior) or at each operation's completion.+-- 2. pickingListLine.quantityReturned: returns book here instead of decrementing+-- quantityPicked. The update_picking_list_status trigger reacts to+-- quantityPicked/status changes and demotes Completed/Partial headers back to+-- In Progress — correct for an operator unpick (work regression), wrong for a+-- post-completion return sweep. quantityPicked stays gross-picked; net staged+-- at lineside = quantityPicked - quantityReturned.+-- 3. backflush_job_materials: verbatim fork of the 20260713190909 definition,+-- adding a lineside on-hand clamp (untracked stock, bins with a workCenterId+-- only) so a completion-time top-up can never drive a lineside bin negative+-- after an early per-operation return.++ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "returnPickedMaterialTiming" TEXT NOT NULL DEFAULT 'job'+ CHECK ("returnPickedMaterialTiming" IN ('job', 'operation'));++ALTER TABLE "pickingListLine"+ ADD COLUMN IF NOT EXISTS "quantityReturned" NUMERIC NOT NULL DEFAULT 0;++DROP FUNCTION IF EXISTS backflush_job_materials(TEXT, NUMERIC, TEXT, TEXT);++CREATE OR REPLACE FUNCTION backflush_job_materials(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_company_id TEXT,+ p_user_id TEXT+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_job_quantity NUMERIC;+ v_job_location_id TEXT;+ v_job_id_readable TEXT;+ v_ratio NUMERIC;+ v_target NUMERIC;+ v_material RECORD;+ v_material_qty_to_issue NUMERIC;+ v_material_storage_unit_id TEXT;+ v_bin_work_center_id TEXT;+ v_bin_on_hand NUMERIC;+ v_material_costing_method TEXT;+ v_material_standard_cost NUMERIC;+ v_material_unit_cost NUMERIC;+ v_material_item_posting_group_id TEXT;+ v_material_cogs_total NUMERIC;+ v_cost_layer RECORD;+ v_remaining_to_consume NUMERIC;+ v_layer_unit_cost NUMERIC;+ v_quantity_from_layer NUMERIC;+ v_adjustment_child RECORD;+ v_child_budget NUMERIC;+ v_child_apply NUMERIC;+ v_child_per_unit NUMERIC;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_raw_materials_account TEXT;+ v_finished_goods_account TEXT;+ v_material_inventory_account TEXT;+ v_material_inventory_description TEXT;+ v_wip_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_bf_item_ids TEXT[] := '{}';+ v_bf_quantities NUMERIC[] := '{}';+ v_bf_storage_unit_ids TEXT[] := '{}';+ v_bf_journal_id TEXT;+ v_bf_journal_entry_id TEXT;+ v_bf_accounting_period_id TEXT;+ v_bf_journal_line_ref TEXT;+ v_bf_jl_id TEXT;+ v_bf_jl_ids TEXT[];+ v_bf_posting_group_ids TEXT[];+ v_bf_line_item_ids TEXT[];+BEGIN+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));++ -- Fetch job details+ SELECT quantity, "locationId", "jobId"+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable+ FROM "job"+ WHERE id = p_job_id;++ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN+ RETURN;+ END IF;++ v_ratio := p_quantity_complete / v_job_quantity;++ -- Backflush non-tracked materials+ FOR v_material IN+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit"+ FROM "jobMaterial" jm+ WHERE jm."jobId" = p_job_id+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ AND jm."quantityToIssue" > 0+ LOOP+ -- Prorate: only issue what's needed for the completed quantity+ v_target := v_material."estimatedQuantity" * v_ratio;+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);++ IF v_material_qty_to_issue <= 0 THEN+ CONTINUE;+ END IF;++ -- Resolve storage unit+ v_material_storage_unit_id := v_material."storageUnitId";++ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id+ FROM "pickMethod"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "companyId" = p_company_id;+ END IF;++ IF v_material_storage_unit_id IS NULL THEN+ SELECT "storageUnitId" INTO v_material_storage_unit_id+ FROM "itemLedger"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "storageUnitId" IS NOT NULL+ GROUP BY "storageUnitId"+ HAVING SUM(quantity) > 0+ ORDER BY SUM(quantity) DESC+ LIMIT 1;+ END IF;++ -- Clamp lineside draws to actual untracked on-hand. An early per-operation+ -- return (returnPickedMaterialTiming = 'operation') or a manual transfer can+ -- leave the lineside bin short of the prorated target; never post a+ -- consumption the bin cannot supply. Warehouse bins (no workCenterId) keep+ -- the historical unclamped behavior.+ v_bin_work_center_id := NULL;+ IF v_material_storage_unit_id IS NOT NULL THEN+ SELECT su."workCenterId" INTO v_bin_work_center_id+ FROM "storageUnit" su+ WHERE su.id = v_material_storage_unit_id;++ IF v_bin_work_center_id IS NOT NULL THEN+ SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_hand+ FROM "itemLedger"+ WHERE "itemId" = v_material."itemId"+ AND "storageUnitId" = v_material_storage_unit_id+ AND "locationId" = v_job_location_id+ AND "companyId" = p_company_id+ AND "trackedEntityId" IS NULL;++ v_material_qty_to_issue := LEAST(v_material_qty_to_issue, GREATEST(v_bin_on_hand, 0));++ IF v_material_qty_to_issue <= 0 THEN+ CONTINUE;+ END IF;+ END IF;+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,+ v_material."itemId", -v_material_qty_to_issue,+ v_job_location_id, v_material_storage_unit_id, p_user_id+ );++ UPDATE "jobMaterial"+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue+ WHERE id = v_material.id;++ v_bf_item_ids := v_bf_item_ids || v_material."itemId";+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');+ END LOOP;++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount"+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location');++ -- Get accounting period+ SELECT id INTO v_bf_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ AND status = 'Active'+ LIMIT 1;++ IF v_bf_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ RETURNING id INTO v_bf_accounting_period_id;++ IF v_bf_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', CURRENT_DATE)::DATE,+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_bf_accounting_period_id;+ END IF;+ END IF;++ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_bf_journal_entry_id, v_bf_accounting_period_id,+ 'Material Issue — Job ' || v_job_id_readable,+ CURRENT_DATE, p_company_id, 'Job Consumption', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_bf_journal_id;++ v_bf_jl_ids := '{}';+ v_bf_posting_group_ids := '{}';+ v_bf_line_item_ids := '{}';++ FOR i IN 1..array_length(v_bf_item_ids, 1)+ LOOP+ -- Get itemCost for COGS calculation+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id;++ IF v_material_costing_method IS NULL THEN+ CONTINUE;+ END IF;++ -- Calculate COGS based on costing method+ v_material_cogs_total := 0;++ IF v_material_costing_method = 'Standard' THEN+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method = 'Average' THEN+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN+ v_remaining_to_consume := v_bf_quantities[i];++ FOR v_cost_layer IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id+ AND "remainingQuantity" > 0+ -- adjustment child rows are consumed with their parent, not as layers+ AND adjustment = false+ AND "appliesToCostLedgerId" IS NULL+ -- 'Purchase Order' rows are planning/cost-history artifacts, not layers+ AND ("documentType" IS NULL OR "documentType" <> 'Purchase Order')+ ORDER BY+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC+ LOOP+ EXIT WHEN v_remaining_to_consume <= 0;++ v_layer_unit_cost := CASE+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity+ ELSE 0+ END;++ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer+ WHERE id = v_cost_layer.id;++ -- Consume the layer's cost-adjustment children (invoice-vs-receipt+ -- price corrections linked via "appliesToCostLedgerId") alongside the+ -- parent: each adjusted unit carries a bump of child.cost/child.quantity.+ -- Mirrors shared/calculate-cogs.ts.+ v_child_budget := v_quantity_from_layer;+ FOR v_adjustment_child IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "appliesToCostLedgerId" = v_cost_layer.id+ AND "remainingQuantity" > 0+ ORDER BY "createdAt" ASC+ LOOP+ EXIT WHEN v_child_budget <= 0;++ v_child_per_unit := CASE+ WHEN v_adjustment_child.quantity > 0+ THEN v_adjustment_child.cost / v_adjustment_child.quantity+ ELSE 0+ END;++ v_child_apply := LEAST(v_adjustment_child."remainingQuantity", v_child_budget);+ v_material_cogs_total := v_material_cogs_total + v_child_apply * v_child_per_unit;+ v_child_budget := v_child_budget - v_child_apply;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_child_apply+ WHERE id = v_adjustment_child.id;+ END LOOP;+ END LOOP;++ -- Fallback for negative inventory+ IF v_remaining_to_consume > 0 THEN+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);+ END IF;+ END IF;++ IF v_material_cogs_total <= 0 THEN+ CONTINUE;+ END IF;++ -- Resolve Raw Materials vs Finished Goods from the consumed item:+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.+ SELECT+ CASE WHEN i2."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,+ CASE WHEN i2."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END+ INTO v_material_inventory_account, v_material_inventory_description+ FROM "item" i2+ WHERE i2."id" = v_bf_item_ids[i]+ AND i2."companyId" = p_company_id;++ v_bf_journal_line_ref := nanoid();++ -- DR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_wip_account, 'WIP Account',+ v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');++ -- CR Inventory (Raw Materials or Finished Goods by item)+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_material_inventory_account, v_material_inventory_description,+ -v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');++ -- Cost ledger entry for consumption+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Consumption', 'Direct Cost', false,+ 'Job Consumption', p_job_id, v_bf_item_ids[i],+ -v_bf_quantities[i], -v_material_cogs_total,+ 0, p_company_id+ );+ END LOOP;++ -- Dimensions for material consumption journal lines+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN+ FOR i IN 1..array_length(v_bf_jl_ids, 1)+ LOOP+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_bf_line_item_ids[i] != '' THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item, v_bf_line_item_ids[i], p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 64217c5cb5..63da2a3c76 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -1657,9 +1657,15 @@ msgstr "Weist diese Einheit einem Arbeitsplatz für Linienside-Material zu, damimsgid "At each gate"msgstr "Bei jedem Gate"+msgid "At job completion"+msgstr "Nach Auftragsabschluss"+msgid "At least one condition must match"msgstr "Mindestens eine Bedingung muss erfüllt sein"+msgid "At operation completion"+msgstr "Nach Vorgangsabschluss"+msgid "Attach File"msgstr "Datei anhängen"@@ -3711,6 +3717,9 @@ msgstr "Entscheiden Sie, was ein Bediener sieht, wenn er versucht, einen Batch omsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Legen Sie fest, was passiert, wenn ein Bediener auf dem Shopfloor die Funktion \"Fertig\" drückt, während Material noch nicht kommissioniert ist."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Entscheiden Sie, wann Material, das zu einem Arbeitszentrum gepickt, aber nicht verbraucht wurde, ins Lager zurückfließt."+msgid "Decimal Places"msgstr "Dezimalstellen"@@ -4558,6 +4567,9 @@ msgstr "z.B. die ersten 3 bis 4 Wochen"msgid "e.g. Zebra 2x1"msgstr "z.B. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Das ungenutzte Material jedes Vorgangs wird sofort nach Abschluss des Vorgangs zurückgegeben."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Jede physische Einheit erhält ihre eigene nachverfocgte Einheit und eindeutige Nummer — eine Einheit, eine Einheit."@@ -7213,6 +7225,9 @@ msgstr "Linkes Element"msgid "Leftover Parts Detected"msgstr "Überschüssige Teile erkannt"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Überschüssiges bereitgestelltes Material wird zurückgegeben, wenn der gesamte Auftrag abgeschlossen ist."+msgid "Less manual work"msgstr "Weniger manuelle Arbeit"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Keine Übereinstimmungen. Geben Sie ein, um eine zu erstellen."msgid "No matching bins"-msgstr ""+msgstr "Keine übereinstimmenden Behälter"msgid "No new notifications"msgstr "Keine neuen Benachrichtigungen"@@ -8796,7 +8811,7 @@ msgstr "Notizen (optional)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Nichts an diesem Ort entspricht \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "Keine anderen Artikel an diesem Ort haben Bestand zum Entnehmen."@@ -10787,6 +10802,12 @@ msgstr "Erneut versuchen"msgid "Return Home"msgstr "Zur Startseite zurück"+msgid "Returned"+msgstr "Zurückgegeben"++msgid "Returning unused picked material"+msgstr "Rückgabe ungenutzten Pickmaterials"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "Unbenanntes Diagramm"msgid "Untitled line"msgstr "Unbenannte Zeile"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Ungenutztes Pickmaterial aus dem Arbeitszentrum zurück ins Lager gespült."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 3411acd0da..cf11de86bc 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -1657,9 +1657,15 @@ msgstr "Assigns this unit to a work center for lineside material, so operators smsgid "At each gate"msgstr "At each gate"+msgid "At job completion"+msgstr "At job completion"+msgid "At least one condition must match"msgstr "At least one condition must match"+msgid "At operation completion"+msgstr "At operation completion"+msgid "Attach File"msgstr "Attach File"@@ -3711,6 +3717,9 @@ msgstr "Decide what an operator sees if they try to issue a batch or serial thatmsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgid "Decimal Places"msgstr "Decimal Places"@@ -4558,6 +4567,9 @@ msgstr "e.g. the first 3 to 4 weeks"msgid "e.g. Zebra 2x1"msgstr "e.g. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Each operation's unused material returns as soon as the operation is done."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Each physical unit gets its own tracked entity and unique number — one entity, one unit."@@ -7213,6 +7225,9 @@ msgstr "Left item"msgid "Leftover Parts Detected"msgstr "Leftover Parts Detected"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Leftover staged material returns when the whole job completes."+msgid "Less manual work"msgstr "Less manual work"@@ -10787,6 +10802,12 @@ msgstr "Retry"msgid "Return Home"msgstr "Return Home"+msgid "Returned"+msgstr "Returned"++msgid "Returning unused picked material"+msgstr "Returning unused picked material"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "Untitled Diagram"msgid "Untitled line"msgstr "Untitled line"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Unused picked material flushed back from the work center to the warehouse."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex df2a514180..72c3493ac3 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -1657,9 +1657,15 @@ msgstr "Asigna esta unidad a un centro de trabajo para material en el costado demsgid "At each gate"msgstr "En cada puerta"+msgid "At job completion"+msgstr "Al completar el trabajo"+msgid "At least one condition must match"msgstr "Al menos una condición debe coincidir"+msgid "At operation completion"+msgstr "Al completar la operación"+msgid "Attach File"msgstr "Adjuntar archivo"@@ -3711,6 +3717,9 @@ msgstr "Decide qué ve un operador si intenta emitir un lote o número de seriemsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Decidir qué sucede cuando un operador presiona Finalizar en el piso de producción con material aún sin recoger."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Decide cuándo el material enviado a un centro de trabajo pero no consumido fluye de vuelta al almacén."+msgid "Decimal Places"msgstr "Lugares Decimales"@@ -4558,6 +4567,9 @@ msgstr "p. ej. las primeras 3 a 4 semanas"msgid "e.g. Zebra 2x1"msgstr "p. ej. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "El material no utilizado de cada operación se devuelve tan pronto como la operación finaliza."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Cada unidad física obtiene su propia entidad rastreada y número único — una entidad, una unidad."@@ -7213,6 +7225,9 @@ msgstr "Elemento izquierdo"msgid "Leftover Parts Detected"msgstr "Piezas Sobrantes Detectadas"+msgid "Leftover staged material returns when the whole job completes."+msgstr "El material preparado restante se devuelve cuando todo el trabajo se completa."+msgid "Less manual work"msgstr "Menos trabajo manual"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Sin coincidencias. Escribe para crear una."msgid "No matching bins"-msgstr ""+msgstr "No hay contenedores coincidentes"msgid "No new notifications"msgstr "Sin notificaciones nuevas"@@ -8796,7 +8811,7 @@ msgstr "Notas (opcional)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Nada en esta ubicación coincide con \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "Nada más en esta ubicación tiene stock para extraer."@@ -10787,6 +10802,12 @@ msgstr "Reintentar"msgid "Return Home"msgstr "Volver al Inicio"+msgid "Returned"+msgstr "Devuelto"++msgid "Returning unused picked material"+msgstr "Devolviendo material recogido no utilizado"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "Diagrama sin título"msgid "Untitled line"msgstr "Línea sin título"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Material recogido no utilizado devuelto desde el centro de trabajo al almacén."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 79ef4396cb..dc90675b78 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -1657,9 +1657,15 @@ msgstr "Attribue cette unité à un centre de travail pour les matériaux en bormsgid "At each gate"msgstr "À chaque étape"+msgid "At job completion"+msgstr "À la fin du travail"+msgid "At least one condition must match"msgstr "Au moins une condition doit correspondre"+msgid "At operation completion"+msgstr "À la fin de l'opération"+msgid "Attach File"msgstr "Joindre un fichier"@@ -3711,6 +3717,9 @@ msgstr "Décidez ce qu'un opérateur voit s'il essaie d'émettre un lot ou un numsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Décidez ce qui se passe lorsqu'un opérateur appuie sur Terminer à l'atelier avec du matériel non prélevé."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Décidez quand le matériel prélevé vers un centre de travail mais non consommé revient à l'entrepôt."+msgid "Decimal Places"msgstr "Décimales"@@ -4558,6 +4567,9 @@ msgstr "par exemple les 3 à 4 premières semaines"msgid "e.g. Zebra 2x1"msgstr "p. ex. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Le matériel inutilisé de chaque opération revient dès que l'opération est terminée."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Chaque unité physique obtient sa propre entité suivie et un numéro unique — une entité, une unité."@@ -7213,6 +7225,9 @@ msgstr "Élément de gauche"msgid "Leftover Parts Detected"msgstr "Pièces excédentaires détectées"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Le matériel préparé restant revient quand l'ensemble du travail est terminé."+msgid "Less manual work"msgstr "Moins de travail manuel"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Aucune correspondance. Tapez pour en créer une."msgid "No matching bins"-msgstr ""+msgstr "Aucune zone correspondante"msgid "No new notifications"msgstr "Aucune nouvelle notification"@@ -8796,7 +8811,7 @@ msgstr "Notes (facultatif)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Rien à cet emplacement ne correspond à \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "Aucun autre article à cet endroit n'a de stock à prélever."@@ -10787,6 +10802,12 @@ msgstr "Réessayer"msgid "Return Home"msgstr "Retour à l'accueil"+msgid "Returned"+msgstr "Retourné"++msgid "Returning unused picked material"+msgstr "Retour du matériel prélevé inutilisé"+msgid "Rev {revision}"msgstr "Rév {revision}"@@ -13954,6 +13975,9 @@ msgstr "Diagramme sans titre"msgid "Untitled line"msgstr "Ligne sans titre"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Matériel prélevé inutilisé renvoyé du centre de travail à l'entrepôt."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 088fc92d3d..be8aa19cef 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -1657,9 +1657,15 @@ msgstr "इस इकाई को लाइनसाइड सामग्रmsgid "At each gate"msgstr "हर गेट पर"+msgid "At job completion"+msgstr "जॉब पूरी होने पर"+msgid "At least one condition must match"msgstr "कम से कम एक शर्त मेल खानी चाहिए"+msgid "At operation completion"+msgstr "ऑपरेशन पूरी होने पर"+msgid "Attach File"msgstr "फ़ाइल संलग्न करें"@@ -3711,6 +3717,9 @@ msgstr "तय करें कि यदि कोई ऑपरेटर एकmsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "तय करें कि जब ऑपरेटर शॉप फ्लोर पर फिनिश दबाता है तो क्या होता है जब सामग्री अभी भी अनचुनी होती है।"+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "तय करें कि वर्क सेंटर में चुनी गई अप्रयुक्त सामग्री कब गोदाम में वापस जाए।"+msgid "Decimal Places"msgstr "दशमलव स्थान"@@ -4558,6 +4567,9 @@ msgstr "उदाहरण के लिए पहले 3 से 4 सप्तmsgid "e.g. Zebra 2x1"msgstr "उदाहरण के लिए Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "प्रत्येक ऑपरेशन की अप्रयुक्त सामग्री ऑपरेशन पूरी होते ही वापस आती है।"+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "प्रत्येक भौतिक इकाई को अपनी खुद की ट्रैक की गई इकाई और अद्वितीय संख्या मिलती है — एक इकाई, एक इकाई।"@@ -7213,6 +7225,9 @@ msgstr "बाईं ओर की वस्तु"msgid "Leftover Parts Detected"msgstr "बचे हुए पार्ट्स का पता चला"+msgid "Leftover staged material returns when the whole job completes."+msgstr "बची हुई सामग्री पूरी जॉब पूरी होने पर वापस आती है।"+msgid "Less manual work"msgstr "कम मैनुअल काम"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "कोई मेल नहीं। एक बनाने के लिए टाइप करें।"msgid "No matching bins"-msgstr ""+msgstr "कोई मेल खाने वाले बिन नहीं"msgid "No new notifications"msgstr "कोई नई सूचनाएं नहीं"@@ -8796,7 +8811,7 @@ msgstr "नोट्स (वैकल्पिक)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "इस स्थान पर \"{0}\" से कुछ भी मेल नहीं खाता।"msgid "Nothing else at this location has stock to pull from."msgstr "इस स्थान पर कोई अन्य स्टॉक नहीं है जहां से खींचा जा सकता है।"@@ -10787,6 +10802,12 @@ msgstr "पुनः प्रयास करें"msgid "Return Home"msgstr "घर लौटें"+msgid "Returned"+msgstr "लौटाया गया"++msgid "Returning unused picked material"+msgstr "अप्रयुक्त सामग्री को वापस किया जा रहा है"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "बिना शीर्षक वाला आरेख"msgid "Untitled line"msgstr "बिना शीर्षक की पंक्ति"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "अप्रयुक्त सामग्री को वर्क सेंटर से गोदाम में वापस भेजा गया।"+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex e17072e53d..826d7e627a 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -1657,9 +1657,15 @@ msgstr "Assegna questa unità a un centro di lavoro per il materiale lineside, imsgid "At each gate"msgstr "Ad ogni gate"+msgid "At job completion"+msgstr "Al completamento del lavoro"+msgid "At least one condition must match"msgstr "Almeno una condizione deve corrispondere"+msgid "At operation completion"+msgstr "Al completamento dell'operazione"+msgid "Attach File"msgstr "Allega File"@@ -3711,6 +3717,9 @@ msgstr "Decidi cosa vede un operatore se tenta di emettere un lotto o un numeromsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Decidi cosa accade quando un operatore preme Fine in officina con materiale ancora non prelevato."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Decide quando il materiale prelevato per un centro di lavoro ma non consumato torna al magazzino."+msgid "Decimal Places"msgstr "Posizioni Decimali"@@ -4558,6 +4567,9 @@ msgstr "ad es. le prime 3-4 settimane"msgid "e.g. Zebra 2x1"msgstr "ad es. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Il materiale inutilizzato di ogni operazione torna non appena l'operazione è completata."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Ogni unità fisica ottiene la propria entità tracciata e numero univoco — un'entità, un'unità."@@ -7213,6 +7225,9 @@ msgstr "Elemento sinistro"msgid "Leftover Parts Detected"msgstr "Parti Rimanenti Rilevate"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Il materiale in staging rimanente torna quando l'intero lavoro è completato."+msgid "Less manual work"msgstr "Meno lavoro manuale"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Nessuna corrispondenza. Digita per crearne uno."msgid "No matching bins"-msgstr ""+msgstr "Nessun bin corrispondente"msgid "No new notifications"msgstr "Nessuna nuova notifica"@@ -8796,7 +8811,7 @@ msgstr "Note (facoltativo)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Nulla in questa posizione corrisponde a \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "Niente altro in questa posizione ha stock da cui prelevare."@@ -10787,6 +10802,12 @@ msgstr "Riprova"msgid "Return Home"msgstr "Torna alla Home"+msgid "Returned"+msgstr "Restituito"++msgid "Returning unused picked material"+msgstr "Restituzione di materiale prelevato inutilizzato"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "Diagramma senza titolo"msgid "Untitled line"msgstr "Riga senza titolo"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Materiale prelevato inutilizzato riportato dal centro di lavoro al magazzino."+msgid "UoM"msgstr "UdM"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 7f31cc01b8..e15d8e3499 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -1657,9 +1657,15 @@ msgstr "このユニットを作業センターに割り当ててラインサイmsgid "At each gate"msgstr "各ゲートで"+msgid "At job completion"+msgstr "ジョブ完了時"+msgid "At least one condition must match"msgstr "少なくとも1つの条件が一致する必要があります"+msgid "At operation completion"+msgstr "操作完了時"+msgid "Attach File"msgstr "ファイルを添付"@@ -3711,6 +3717,9 @@ msgstr "オペレーターが既に期限切れのバッチまたはシリアルmsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "オペレーターが店舗の床で材料がまだピックされていない状態で「完了」を押すとどうなるかを決定します。"+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "作業センターに仕分けされたが消費されなかった材料が倉庫に戻る時期を決定します。"+msgid "Decimal Places"msgstr "小数位数"@@ -4558,6 +4567,9 @@ msgstr "例:最初の3~4週間"msgid "e.g. Zebra 2x1"msgstr "例:Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "各操作の未使用材料は操作が完了するとすぐに戻されます。"+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "各物理ユニットは独自の追跡エンティティと一意の番号を取得します — 1つのエンティティ、1つのユニット。"@@ -7213,6 +7225,9 @@ msgstr "左側の項目"msgid "Leftover Parts Detected"msgstr "余剰部品が検出されました"+msgid "Leftover staged material returns when the whole job completes."+msgstr "ジョブ全体が完了したときに、ステージングされたままの材料が戻されます。"+msgid "Less manual work"msgstr "手作業を減らす"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "一致するものがありません。作成するには入力してください。"msgid "No matching bins"-msgstr ""+msgstr "マッチするビンがありません"msgid "No new notifications"msgstr "新しい通知はありません"@@ -8796,7 +8811,7 @@ msgstr "メモ(オプション)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "この場所に「{0}」に一致するものはありません。"msgid "Nothing else at this location has stock to pull from."msgstr "この場所には他に引き出す在庫がありません。"@@ -10787,6 +10802,12 @@ msgstr "再試行"msgid "Return Home"msgstr "ホームに戻る"+msgid "Returned"+msgstr "返却"++msgid "Returning unused picked material"+msgstr "未使用の仕分け材料を返却中"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "無題の図"msgid "Untitled line"msgstr "無題の行"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "作業センターから倉庫に戻された未使用の仕分け材料。"+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 9385cea375..34bef74cd5 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -1657,9 +1657,15 @@ msgstr "이 단위를 라인사이드 자재용으로 작업장에 배정하여msgid "At each gate"msgstr "각 게이트마다"+msgid "At job completion"+msgstr "작업 완료 시"+msgid "At least one condition must match"msgstr "하나 이상의 조건이 일치해야 합니다"+msgid "At operation completion"+msgstr "작업 완료 시"+msgid "Attach File"msgstr "파일 첨부"@@ -3711,6 +3717,9 @@ msgstr "작업자가 이미 만료된 배치 또는 일련번호를 출고하려msgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "작업자가 아직 선택되지 않은 재료가 있는 상태에서 현장에서 완료를 누를 때 발생할 사항을 결정하십시오."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "작업장으로 이송했으나 소비하지 않은 재료가 창고로 반환되는 시기를 결정합니다."+msgid "Decimal Places"msgstr "소수 자릿수"@@ -4558,6 +4567,9 @@ msgstr "예: 처음 3~4주"msgid "e.g. Zebra 2x1"msgstr "예: Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "각 작업의 미사용 재료는 해당 작업이 완료되는 즉시 반환됩니다."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "각 실물 유닛은 고유한 추적 개체와 번호를 부여받습니다 — 하나의 개체, 하나의 유닛."@@ -7213,6 +7225,9 @@ msgstr "왼쪽 품목"msgid "Leftover Parts Detected"msgstr "잔여 부품 발견됨"+msgid "Leftover staged material returns when the whole job completes."+msgstr "남은 스테이징 재료는 전체 작업이 완료될 때 반환됩니다."+msgid "Less manual work"msgstr "수작업 감소"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "일치하는 항목 없음. 입력하여 새로 만드세요."msgid "No matching bins"-msgstr ""+msgstr "일치하는 빈이 없습니다"msgid "No new notifications"msgstr "새 알림이 없습니다"@@ -8796,7 +8811,7 @@ msgstr "메모(선택)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "이 위치에서 \"{0}\"과(와) 일치하는 항목이 없습니다."msgid "Nothing else at this location has stock to pull from."msgstr "이 위치에는 더 이상 가져올 재고가 없습니다."@@ -10787,6 +10802,12 @@ msgstr "재시도"msgid "Return Home"msgstr "홈으로 돌아가기"+msgid "Returned"+msgstr "반환됨"++msgid "Returning unused picked material"+msgstr "미사용 선택 재료 반환 중"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "제목 없는 다이어그램"msgid "Untitled line"msgstr "제목 없는 라인"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "작업장에서 창고로 반환된 미사용 선택 재료."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 72bb3d20d6..179bececef 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -1657,9 +1657,15 @@ msgstr "Przypisuje tę jednostkę do centrum pracy do materiałów liniesidowychmsgid "At each gate"msgstr "Na każdej bramce"+msgid "At job completion"+msgstr "Po zakończeniu zadania"+msgid "At least one condition must match"msgstr "Co najmniej jeden warunek musi się zgadzać"+msgid "At operation completion"+msgstr "Po zakończeniu operacji"+msgid "Attach File"msgstr "Dolacz plik"@@ -3711,6 +3717,9 @@ msgstr "Zdecyduj, co operator widzi, jeśli spróbuje wydać partię lub numer smsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Zdecyduj, co się stanie, gdy operator naciśnie Zakończ na hali produkcji z materiałem, który wciąż nie został pobrany."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Zdecyduj, kiedy materiał pobrany do stanowiska pracy, ale nie zużyty, wraca do magazynu."+msgid "Decimal Places"msgstr "Miejsca Dziesiętne"@@ -4558,6 +4567,9 @@ msgstr "np. pierwsze 3 do 4 tygodnie"msgid "e.g. Zebra 2x1"msgstr "np. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Nieużywany materiał każdej operacji wraca natychmiast po zakończeniu operacji."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Każda jednostka fizyczna otrzymuje swoją własną jednostkę śledzenia i unikalny numer — jedna jednostka, jedna jednostka."@@ -7213,6 +7225,9 @@ msgstr "Element po lewej stronie"msgid "Leftover Parts Detected"msgstr "Wykryte nadmiarowe części"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Pozostały materiał przygotowany wraca, gdy całe zadanie się zakończy."+msgid "Less manual work"msgstr "Mniej pracy ręcznej"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Brak dopasowań. Wpisz, aby utworzyć jeden."msgid "No matching bins"-msgstr ""+msgstr "Brak pasujących pojemników"msgid "No new notifications"msgstr "Brak nowych powiadomień"@@ -8796,7 +8811,7 @@ msgstr "Notatki (opcjonalnie)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Nic w tej lokalizacji nie pasuje do \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "W tym miejscu nic innego nie ma zapasów do pobrania."@@ -10787,6 +10802,12 @@ msgstr "Ponów"msgid "Return Home"msgstr "Wróć do domu"+msgid "Returned"+msgstr "Zwrócone"++msgid "Returning unused picked material"+msgstr "Zwracanie nieużywanego pobranego materiału"+msgid "Rev {revision}"msgstr "Wer. {revision}"@@ -13954,6 +13975,9 @@ msgstr "Diagram bez tytułu"msgid "Untitled line"msgstr "Linia bez tytułu"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Nieużywany pobrany materiał odprowadzony z powrotem od stanowiska pracy do magazynu."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 99057717ed..11e465a97a 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -1657,9 +1657,15 @@ msgstr "Atribui esta unidade a um centro de trabalho para material ao lado da limsgid "At each gate"msgstr "Em cada etapa"+msgid "At job completion"+msgstr "Na conclusão do trabalho"+msgid "At least one condition must match"msgstr "Pelo menos uma condição deve corresponder"+msgid "At operation completion"+msgstr "Na conclusão da operação"+msgid "Attach File"msgstr "Anexar Arquivo"@@ -3711,6 +3717,9 @@ msgstr "Decida o que um operador vê se tentar emitir um lote ou série que jámsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Decida o que acontece quando um operador pressiona Concluir no piso de produção com material ainda não colhido."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Decida quando o material coletado para um centro de trabalho, mas não consumido, flui de volta para o armazém."+msgid "Decimal Places"msgstr "Casas Decimais"@@ -4558,6 +4567,9 @@ msgstr "p.ex. as primeiras 3 a 4 semanas"msgid "e.g. Zebra 2x1"msgstr "p.ex. Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "O material não utilizado de cada operação retorna assim que a operação é concluída."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Cada unidade física obtém sua própria entidade rastreada e número único — uma entidade, uma unidade."@@ -7213,6 +7225,9 @@ msgstr "Item esquerdo"msgid "Leftover Parts Detected"msgstr "Peças Excedentes Detectadas"+msgid "Leftover staged material returns when the whole job completes."+msgstr "O material preparado restante retorna quando todo o trabalho é concluído."+msgid "Less manual work"msgstr "Menos trabalho manual"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Nenhuma correspondência. Digite para criar uma."msgid "No matching bins"-msgstr ""+msgstr "Nenhuma caixa correspondente"msgid "No new notifications"msgstr "Sem notificações novas"@@ -8796,7 +8811,7 @@ msgstr "Notas (opcional)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Nada neste local corresponde a \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "Nada mais neste local tem estoque para puxar."@@ -10787,6 +10802,12 @@ msgstr "Tentar novamente"msgid "Return Home"msgstr "Voltar para Início"+msgid "Returned"+msgstr "Retornado"++msgid "Returning unused picked material"+msgstr "Retornando material coletado não utilizado"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "Diagrama sem título"msgid "Untitled line"msgstr "Linha sem título"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Material coletado não utilizado devolvido do centro de trabalho para o armazém."+msgid "UoM"msgstr "UoM"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex d950bcf9d2..3d4147a815 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -1657,9 +1657,15 @@ msgstr "Назначает эту единицу рабочему центруmsgid "At each gate"msgstr "На каждом этапе"+msgid "At job completion"+msgstr "При завершении работы"+msgid "At least one condition must match"msgstr "По крайней мере одно условие должно совпадать"+msgid "At operation completion"+msgstr "При завершении операции"+msgid "Attach File"msgstr "Прикрепить файл"@@ -3711,6 +3717,9 @@ msgstr "Решите, что видит оператор при попыткеmsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Решите, что произойдет, когда оператор нажмет кнопку 'Завершить' на производстве с неподобранным материалом."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Решение о том, когда материал, отобранный в рабочий центр, но не использованный, поступает обратно на склад."+msgid "Decimal Places"msgstr "Десятичные разряды"@@ -4558,6 +4567,9 @@ msgstr "например, первые 3-4 недели"msgid "e.g. Zebra 2x1"msgstr "например Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Неиспользованный материал каждой операции возвращается сразу после завершения операции."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Каждая физическая единица получает свою собственную отслеживаемую сущность и уникальный номер — одна сущность, одна единица."@@ -7213,6 +7225,9 @@ msgstr "Левый элемент"msgid "Leftover Parts Detected"msgstr "Обнаружены лишние детали"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Оставшийся подготовленный материал возвращается по завершении всей работы."+msgid "Less manual work"msgstr "Меньше ручной работы"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Совпадений не найдено. Введите текст для создания."msgid "No matching bins"-msgstr ""+msgstr "Нет подходящих ячеек"msgid "No new notifications"msgstr "Нет новых уведомлений"@@ -8796,7 +8811,7 @@ msgstr "Примечания (опционально)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "На этом месте нет совпадений с \"{0}\"."msgid "Nothing else at this location has stock to pull from."msgstr "На этом месте больше нечего извлекать из запаса."@@ -10787,6 +10802,12 @@ msgstr "Повторить"msgid "Return Home"msgstr "Вернуться на главную"+msgid "Returned"+msgstr "Возвращено"++msgid "Returning unused picked material"+msgstr "Возврат неиспользованного отобранного материала"+msgid "Rev {revision}"msgstr "Ред. {revision}"@@ -13954,6 +13975,9 @@ msgstr "Безымянная диаграмма"msgid "Untitled line"msgstr "Безымянная строка"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "Неиспользованный отобранный материал поступает обратно из рабочего центра на склад."+msgid "UoM"msgstr "УИ"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex dbc6b647c1..b08df9163b 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -1657,9 +1657,15 @@ msgstr "Bu birimi lineside malzemeleri için bir çalışma merkezine atar, böymsgid "At each gate"msgstr "Her kapıda"+msgid "At job completion"+msgstr "İş tamamlandığında"+msgid "At least one condition must match"msgstr "En az bir koşul eşleşmelidir"+msgid "At operation completion"+msgstr "İşlem tamamlandığında"+msgid "Attach File"msgstr "Dosya Ekle"@@ -3711,6 +3717,9 @@ msgstr "Operatörün zaten süresi dolmuş bir parti veya seri çıkarmaya çalmsgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "Bir operatör, malzeme henüz seçilmemiş olarak üretim alanında Bitir'e bastığında ne olacağını belirleyin."+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "Bir iş merkezine alınan ancak tüketilmeyen malzemenin depoya geri akışının ne zaman gerçekleşeceğine karar verin."+msgid "Decimal Places"msgstr "Ondalık Basamaklar"@@ -4558,6 +4567,9 @@ msgstr "örn. ilk 3 ila 4 hafta"msgid "e.g. Zebra 2x1"msgstr "örneğin Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "Her işlemin kullanılmayan malzemesi işlem tamamlandığı anda geri döner."+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "Her fiziksel birim kendi izlenen varlığını ve benzersiz numarasını alır — bir varlık, bir birim."@@ -7213,6 +7225,9 @@ msgstr "Sol öğe"msgid "Leftover Parts Detected"msgstr "Artık Parçalar Tespit Edildi"+msgid "Leftover staged material returns when the whole job completes."+msgstr "Kalan hazırlanan malzeme tüm iş tamamlandığında geri döner."+msgid "Less manual work"msgstr "Daha az manuel çalışma"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "Eşleşme yok. Bir tane oluşturmak için yazın."msgid "No matching bins"-msgstr ""+msgstr "Eşleşen kutu yok"msgid "No new notifications"msgstr "Yeni bildirim yok"@@ -8796,7 +8811,7 @@ msgstr "Notlar (isteğe bağlı)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "Bu konumdaki hiçbir şey \"{0}\" ile eşleşmiyor."msgid "Nothing else at this location has stock to pull from."msgstr "Bu konumda çekilecek başka hiçbir stok yok."@@ -10787,6 +10802,12 @@ msgstr "Tekrar Dene"msgid "Return Home"msgstr "Ana Sayfaya Dön"+msgid "Returned"+msgstr "İade Edildi"++msgid "Returning unused picked material"+msgstr "Kullanılmayan alınan malzeme iade ediliyor"+msgid "Rev {revision}"msgstr "Sürüm {revision}"@@ -13954,6 +13975,9 @@ msgstr "Başlıksız Diyagram"msgid "Untitled line"msgstr "Başlıksız satır"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "İş merkezinden depoya geri gönderilen kullanılmayan alınan malzeme."+msgid "UoM"msgstr "Birim"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 91a9a7b0e0..bb95b4dc24 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -1657,9 +1657,15 @@ msgstr "将此单元分配给工作中心以用于线边材料,以便操作员msgid "At each gate"msgstr "在每个关卡"+msgid "At job completion"+msgstr "在工作完成时"+msgid "At least one condition must match"msgstr "至少一个条件必须匹配"+msgid "At operation completion"+msgstr "在操作完成时"+msgid "Attach File"msgstr "附加文件"@@ -3711,6 +3717,9 @@ msgstr "决定操作员在尝试发放已过期的批次或序列号时看到的msgid "Decide what happens when an operator presses Finish on the shop floor with material still unpicked."msgstr "决定当操作员在车间按下完成时但材料仍未拣选时会发生什么。"+msgid "Decide when material picked to a work center but not consumed flows back to the warehouse."+msgstr "决定当物料拣配到工作中心但未消耗时何时流回仓库。"+msgid "Decimal Places"msgstr "小数位数"@@ -4558,6 +4567,9 @@ msgstr "例如前3到4周"msgid "e.g. Zebra 2x1"msgstr "例如 Zebra 2x1"+msgid "Each operation's unused material returns as soon as the operation is done."+msgstr "每个操作的未使用物料在操作完成后立即返回。"+msgid "Each physical unit gets its own tracked entity and unique number — one entity, one unit."msgstr "每个物理单位都获得自己的跟踪实体和唯一编号 — 一个实体、一个单位。"@@ -7213,6 +7225,9 @@ msgstr "左项"msgid "Leftover Parts Detected"msgstr "检测到剩余零件"+msgid "Leftover staged material returns when the whole job completes."+msgstr "当整个工作完成时,剩余的暂存物料返回。"+msgid "Less manual work"msgstr "更少的手动工作"@@ -8567,7 +8582,7 @@ msgid "No matches. Type to create one."msgstr "无匹配项。输入内容以创建一个。"msgid "No matching bins"-msgstr ""+msgstr "没有匹配的库位"msgid "No new notifications"msgstr "没有新通知"@@ -8796,7 +8811,7 @@ msgstr "备注(可选)"#. placeholder {0}: search.trim()msgid "Nothing at this location matches \"{0}\"."-msgstr ""+msgstr "此位置处没有与\"{0}\"匹配的任何内容。"msgid "Nothing else at this location has stock to pull from."msgstr "此位置没有其他可提取的库存。"@@ -10787,6 +10802,12 @@ msgstr "重试"msgid "Return Home"msgstr "返回首页"+msgid "Returned"+msgstr "已返回"++msgid "Returning unused picked material"+msgstr "返回未使用的拣配物料"+msgid "Rev {revision}"msgstr "Rev {revision}"@@ -13954,6 +13975,9 @@ msgstr "未命名图表"msgid "Untitled line"msgstr "未命名行"+msgid "Unused picked material flushed back from the work center to the warehouse."+msgstr "未使用的拣配物料从工作中心冲回仓库。"+msgid "UoM"msgstr "计量单位"