Skip to content

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

feat(supersession): Consume First end to end — whole assemblies, made parts, chains, picking and consumption (#1642)

Naveen Kashyapd89c80d64be0
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 956de41865..ad96c03677 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1484,6 +1484,136 @@ full-screen ERP route.
**Applies to:** API/MCP sweep scripts, `apps/erp/app/modules/*/[a-z]*.models.ts` validators that feed `client.functions.invoke` wrappers, `packages/database/supabase/functions/lib/response.ts`, `apps/erp/app/utils/error.ts`.
+## A creation-time swap must be keyed by its provenance column at every later lookup
+
+**Context:** Supersession swaps a `jobMaterial` to its successor when the job is created (`substitutedFromItemId` records the predecessor). Picking then looked up `itemSupersession` by `jobMaterial.itemId` — which is now the successor, which has no row — so `resolvePickTarget` returned "pick the item unchanged" and `Consume First` never consumed the predecessor's stock. The picking-side branch was dead code for every job created after the effectivity date, and the unit tests (which passed a material still on the predecessor) could not see it.
+
+**Problem:** The rule lives on the OLD item; the row already names the NEW one. Any later stage that re-reads the rule by the row's current item silently finds nothing, and "no rule" is a valid, quiet outcome.
+
+**Rule:** When a row is rewritten by a rule and carries a provenance column (`substitutedFromItemId`, `redirectedFromItemId`, …), every downstream lookup of that rule must key on `COALESCE(provenance, current)`, in BOTH the TS and SQL mirrors. Test the swapped shape explicitly — a fixture that stops at "rule set, nothing swapped yet" proves nothing about what happens after the swap.
+
+**Applies to:** `apps/erp/app/modules/inventory/supersession-pick.ts` / `generatePickingList`, `get_picking_schedule`, `packages/ee/src/planning/mrp/mrp.ts` (redirected BOM children), any consumer of `jobMaterial.substitutedFromItemId`.
+
+
+## A post-insert fix-up pass must be scoped to the rows the flow inserted, not to the parent entity
+
+**Context:** `pullConsumeFirstPredecessors` in `get-method` ran after every jobMaterial insert and read `WHERE jobId = …`. Three of the four flows rebuild the whole job, so that read was equivalent — but `itemToJobMakeMethod` rebuilds ONE sub-method, and the pass rewrote lines on every other sub-method too, including rows that already had issued quantity in the successor's units.
+
+**Problem:** A pass keyed on the parent id is correct for the flow it was written next to and silently over-broad for any flow that rebuilds a subset. Nothing fails: the rewritten row has plausible numbers and a plausible provenance column, and only the units disagree with what was already issued.
+
+**Rule:** A fix-up pass that runs after inserts takes the inserted row ids (collect them at every insert site of every flow) and filters on them, plus a guard on any state that means "this row's units are already committed" (`quantityIssued > 0`). Never derive the candidate set from the parent entity when some caller rebuilds only part of it.
+
+**Applies to:** `packages/database/supabase/functions/get-method/index.ts` post-insert passes, any future "after all rows are in, patch some" step in the four job flows.
+
+## A provenance column that records both directions of a swap cannot be trusted first
+
+**Context:** `jobMaterial.substitutedFromItemId` holds the predecessor on a line swapped forward at creation, and the SUCCESSOR on a line pulled back onto a stocked predecessor. Picking looked the rule up on that column first — correct for the forward case, and when the successor had a rule of its own (NEW → NEWER) the pulled-back line resolved NEW's rule, the roles inverted, and the pick went back to NEW.
+
+**Problem:** "Column set ⇒ rule lives there" was true until the second writer appeared. The only thing that distinguishes the two shapes is the relation between the row's own item and the column: on a pulled-back line, the row's own rule NAMES the column as its successor.
+
+**Rule:** When a provenance column can be written by more than one direction of a swap, resolve by relation, not by presence: prefer the row's own rule when it points at the column; only then fall back to the column's rule. Mirror the precedence in every SQL twin (`ORDER BY (own AND successor = column) IS TRUE DESC, …`). Or give the two directions distinct columns.
+
+**Applies to:** `apps/erp/app/modules/inventory/supersession-pick.ts` (`resolvePickRule`), `get_picking_schedule`, any reader of `substitutedFromItemId` / `redirectedFromItemId`.
+
+## Consume First splits are per assembly, not per unit (2026-09-15)
+
+- **Context:** the Consume First partial-stock split picked the predecessor for
+ every unit the warehouse had and the successor for the rest.
+- **Problem:** with 2 per assembly and 3 on the shelf that put one old and one
+ new part on the same unit. A customer would rather leave the odd part in
+ stock than fit a mismatched pair; units of a batch may differ, one unit never.
+- **Rule:** round a predecessor's usable on-hand DOWN to a multiple of the
+ line's per-assembly quantity (`consumableInWholeAssemblies`) everywhere the
+ split is computed — job creation, picking, the SQL schedule, the job
+ materials note, Order Status, the planning list, MRP. A quantity rule that
+ lives in seven places needs one helper, or the sites drift.
+- **Applies to:** any allocation of a per-unit component across a batch.
+
+## Consume First is one rule for bought and made parts (2026-09-16)
+
+- **Context:** the Consume First stock-netting was written for bought parts
+ only. A made predecessor always swapped to its successor — at job creation
+ (`loadSupersessionRedirect`'s Make exclusion) and in MRP (full BOM swap) —
+ because the post-explosion pass that moved the bought shortfall could not
+ explode a made successor's BOM.
+- **Problem:** stocked old sub-assemblies were never used: a job named the new
+ bracket while old brackets sat on the shelf, and planning bought the new
+ bracket's ingredients for the whole quantity. The two "made" special cases
+ were a workaround for where the netting lived, not a product decision.
+- **Rule:** put the netting where the successor can still be planned as
+ itself. In MRP that is INSIDE `explodeBom` (`consumeFirstRedirect`): the old
+ part nets its running balance and moves the shortfall to the successor,
+ which then explodes or buys at a deeper level (a synthetic leveling edge
+ keeps it below the predecessor). In job creation the per-line settle pass is
+ the authority for every Pull from Inventory line, and the item-level filter
+ is provisional. When a rule has a replenishment-specific exception, ask
+ whether the exception is a product decision or an artefact of where the
+ code sits.
+- **Applies to:** `lib/mrp-engine.ts`, `packages/ee/src/planning/mrp/mrp.ts`,
+ `get-method` `settleConsumeFirstLines` / `loadSupersessionRedirect`.
+
+## A Make to Order line is never picked, and never split for Consume First (2026-09-16)
+
+- **Context:** a Consume First sub-assembly on a Make to Order BOM line, three
+ old on the shelf, five needed. The job swapped the line to the successor and
+ built five (Plate B 5), and the picking list ALSO staged three old and two
+ new from the shelf for the parent operation.
+- **Problem:** two bugs stacked. `get_picking_schedule` never excluded Make to
+ Order lines, and since unassigned materials are attributed to the first
+ operation every Make to Order sub-assembly got a phantom pick that nothing
+ consumes (`issue`'s backflush skips Make to Order). And the made-line rule
+ "always swap" meant stocked old sub-assemblies were never used. The obvious
+ fix — split the line into "pick 3 old" + "build 2 new" — dies at the next
+ `recalculate`, which rebuilds every line as per-assembly × parent quantity.
+- **Rule:** a Make to Order line follows the bought Consume First rule by
+ CHANGING METHOD TYPE, not by splitting: when the predecessor covers one whole
+ assembly it becomes a Pull from Inventory line on the predecessor (decided in
+ the row builder, before insert, so no sub-method row is ever created), and
+ picking splits per unit as for any picked line; otherwise it swaps and is
+ built. Picking excludes Make to Order lines everywhere (SQL + TS). When a
+ fix needs two rows where the BOM has one, check what `recalculate` will do
+ to them before writing it.
+- **Applies to:** `get-method` row builders (`itemToJob`,
+ `itemToJobMakeMethod`), `generatePickingList`, `get_picking_schedule`,
+ `lib/job-quantities-engine.ts`.
+
+## A helper that models a chain must be tested with a loop (2026-09-16)
+
+- **Context:** `buildConsumeFirstHops` walked one Consume First hop at a time
+ and guarded against loops only while collapsing through non-Consume-First
+ hops. A two-item Consume First loop passed straight through, and in the
+ engine both items would sit on one cycle level and hand demand to an item
+ already planned — silently lost.
+- **Problem:** the guard was written for the path being walked, not for the
+ property that matters ("does this chain terminate?"), and the first test
+ I wrote for it was the one that caught it.
+- **Rule:** any function that follows successor / parent / next pointers
+ gets a cycle test of the smallest loop (two nodes) before anything else,
+ and the guard checks termination of the WHOLE chain, not just the part the
+ function happens to traverse.
+- **Applies to:** `lib/supersession-pick.ts` chain builders, BOM walkers,
+ anything keyed on `successorItemId` or `parentMaterialId`.
+
+## Two readers of the same shelf must share one definition (2026-09-16)
+
+- **Context:** the pick-list generator credited lineside material with an
+ all-or-nothing on-hand check per item, the schedule SQL did its own version,
+ and consumption followed pick lines only. A job whose two assemblies' parts
+ were already at the work centre (one pair picked on a since-cancelled list,
+ one produced by a sub-job straight into the bin) got a list for four more,
+ and would have consumed the wrong part from the wrong bin.
+- **Problem:** three code paths each answered "what is at the machine for
+ this job?" with a different formula, and none of them was wrong in
+ isolation. The trial found it in minutes because real shop floors leave
+ material at the machine in every way except a clean pick.
+- **Rule:** when picking, scheduling and consumption all read the same bin,
+ write the definition ONCE as a pure function (`linesideCredit`), mirror it
+ in SQL under the same name (`get_lineside_credit`), and make every reader
+ call it. Then enumerate the ways stock reaches a bin — pick, cancelled
+ pick, sub-job output, manual transfer, return — and test each against the
+ definition before calling the feature done.
+- **Applies to:** `generatePickingList`, `get_picking_schedule`,
+ `getPickedBudgets` / `issue`, `post-picking`.
## Resolve adoption assumptions before designing accounting migration machinery
**Context:** The accounting posting-corrections spec raised legacy open-balance migration concerns; the user clarified that accounting can be assumed unused.
@@ -1583,6 +1713,16 @@ full-screen ERP route.
**Applies to:** every `.from(...).insert(...)` / `.update(...)` whose result is not bound, especially in post-commit "also link X" tails; fixed for both writers in PR #1612 by moving them into a Kysely transaction under `lockIssueDispositions`.
+## A running total must be subtracted from the pool it was taken from
+
+**Context:** The operation-completion backflush (`issue`, `issueJobOperationMaterials`) allocates every material of the operation against its lineside budgets before inserting any ledger row. A review pointed out that two materials sharing a picked item could both be offered the same unclaimed lineside stock, and asked to track what earlier materials took and subtract it from the next budget.
+
+**Problem:** The budget's `available` was the sum of two pools — the material's OWN pick (private) and the bin's UNCLAIMED stock (shared) — and the fix subtracted a per-item running total of whole takes from that sum. Material A consuming its own private pick therefore zeroed material B's private pick, and B fell back to the warehouse while its staged stock sat at the machine. The fix was written to the reviewer's wording ("subtract it from available"), it had no test with a non-empty running total, and the follow-up review comment landed after the fix was pushed and was never re-polled.
+
+**Rule:** When a value is a sum of pools with different sharing scopes, never subtract a merged total from it. Keep the pools apart on the type, attribute each take to a pool, and subtract a take only from the pool it came from. Every fix that adds a cross-iteration accumulator gets a pure test with the accumulator non-empty before it is committed. After pushing review fixes, re-read the PR's open threads — the reviewer's follow-up is on the FIX commit, not the original diff.
+
+**Applies to:** `lib/picked-consumption.ts` (`SharedTakes`, `recordSharedTakes`, `splitTakeByBin`), `generatePickingList`'s `unclaimedRemaining`, `getPickedBudgets` callers, and any loop that allocates from a shared balance before persisting.
+
## A cron that walks every tenant must isolate each tenant
**Context:** `accounting-pull-sweep` looped `for (target of targets) await step.run(...)` over every active accounting integration; `mrp` ran every company inside ONE `step.run`. One Xero tenant's refresh token died (`invalid_grant` "Refresh token not found"); one MRP run outgrew Vercel's function timeout.
diff --git a/.ai/plans/2026-09-09-supersession-trial-fixes.md b/.ai/plans/2026-09-09-supersession-trial-fixes.md
new file mode 100644
index 0000000000..010f22dffc
--- /dev/null
+++ b/.ai/plans/2026-09-09-supersession-trial-fixes.md
@@ -0,0 +1,57 @@
+# Supersession trial fixes
+
+Source: customer trial board (`.context/attachments/DqBNfz/Supersession Trial (1).pdf`),
+supersession section. Old part = predecessor, new part = successor.
+
+## Tasks
+
+- [x] 1. Picking honours a job-creation swap. Look up the supersession on
+ `COALESCE(substitutedFromItemId, itemId)`; Consume First pulls the predecessor while it
+ has warehouse stock (qty / substitutionFactor); Prefer New falls back to the predecessor
+ only while the successor has none. TS (`resolvePickTarget`, `generatePickingList`) and
+ SQL (`get_picking_schedule`, new migration) mirror each other.
+- [x] 1b. MRP nets a Consume First BUY component's on-hand before moving the shortfall to
+ the successor (post-explosion pass in `mrp.ts`); made components keep the full swap.
+- [x] 2. Planning tab shows incoming supersessions ("Supersedes") and offers "Add
+ predecessor", which writes the row on the old item with this item as successor.
+- [x] 3. Discontinuation Date keeps its label, gets a clearer description, optional for
+ Consume First.
+- [x] 4. Prefer New description matches the pick-time fallback.
+- [x] 5. Stock Only joins `REDIRECTING_MODES` so production demand moves to the successor at
+ job creation and in MRP.
+- [x] 6. Cycle guard in `upsertItemSupersession` (service) surfaced as a field error.
+- [x] 7. Update `.claude/rules/supersession-system.md`; run tests, typecheck, lint,
+ `pnpm generate:mcp`.
+
+- [x] 8. Job creation keeps a Consume First material on the predecessor while it has
+ on-hand at the job's location (`withoutStockedConsumeFirst`); swaps only once it is out.
+
+- [x] 9. Partial stock: job lines are never split at creation (one line on the predecessor,
+ with a live "remaining M will be picked as NEW" note); `pullConsumeFirstPredecessors`
+ pulls a successor line onto a stocked predecessor; `generatePickingList` splits pick
+ lines; pick-side rule lookup falls back to the row's own item.
+- [x] 10. "Picked as X in place of this item" note on the job materials page; clearer
+ substitution note on ERP and MES picking lines.
+
+- [x] 11. Cancelling a job returns picked-but-unconsumed material from lineside to the
+ warehouse (`$jobId.status.tsx` → `returnJobRemainders`, guard accepts Cancelled).
+
+- [x] 12. Planning sees the redirect: MRP moves the actual-demand share to the successor
+ (`demandActual`); the job materials Order Status nets a Consume First shortfall against
+ the successor and names it in the badge.
+
+- [x] 13. Item planning tab list: open job material lines follow the rule (predecessor keeps
+ what its stock covers, successor shows the rest "via OLD"), matching the chart bars.
+
+- [x] 14. Consumption follows what was picked (`lib/picked-consumption.ts`): completion
+ backflush, manual/step issue and the return sweep read the pick lines per item, old
+ part first; the material row is untouched.
+
+## Verification
+- `deno test packages/database/supabase/functions/lib/picked-consumption.test.ts`
+
+- `deno test packages/database/supabase/functions/lib/supersession-pick.test.ts`
+- `pnpm --filter ./apps/erp exec vitest run app/modules/inventory/supersession-pick.test.ts`
+- `pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee`
+- `pnpm run lint`
+- `pnpm check:manifest`
diff --git a/.ai/plans/2026-09-15-supersession-whole-assemblies.md b/.ai/plans/2026-09-15-supersession-whole-assemblies.md
new file mode 100644
index 0000000000..023956c324
--- /dev/null
+++ b/.ai/plans/2026-09-15-supersession-whole-assemblies.md
@@ -0,0 +1,30 @@
+# Consume First: whole assemblies only
+
+Customer feedback on the partial-stock split: a unit that needs 2 of a part must get
+two of the SAME part. Old stock is used in whole multiples of the per-assembly
+quantity; the odd part stays on the shelf. Units in a batch may differ from one
+another; a single unit never mixes old and new.
+
+## Tasks
+
+- [x] 1. Shared helper `consumableInWholeAssemblies(onHand, perAssembly)` in
+ `lib/supersession-pick.ts` (+ `RoundingMode.Down` in precision.ts), Deno tests.
+- [x] 2. get-method: settle pass after insert handles BOTH directions with the
+ per-assembly threshold — pull a successor line back when the predecessor covers
+ ≥ 1 assembly; push a predecessor line to the successor when it covers none.
+- [x] 3. `generatePickingList`: split at whole assemblies; predecessor "in stock" for
+ Consume First means ≥ 1 assembly of the running balance.
+- [x] 4. SQL `get_picking_schedule`: Consume First predecessor stock test ≥ per-assembly
+ quantity (new migration); `openJobMaterialLines` gains `quantityPerParent`.
+- [x] 5. Job materials note + Order Status netting round the same way.
+- [x] 6. Item planning list split rounds per line.
+- [x] 7. MRP post-explode Consume First pass nets per contributor in whole assemblies.
+- [x] 8. Pick line notes (ERP + MES) and the materials note say how many assemblies.
+- [x] 9. Rule doc, lessons, types regenerated, tests, typecheck, lint.
+
+## Verification
+
+- `deno test packages/database/supabase/functions/lib/supersession-pick.test.ts`
+- `pnpm --filter ./apps/erp exec vitest run app/modules/inventory/supersession-pick.test.ts`
+- `pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/ee`
+- `pnpm run lint`
diff --git a/.ai/plans/2026-09-16-consume-first-made-parts.md b/.ai/plans/2026-09-16-consume-first-made-parts.md
new file mode 100644
index 0000000000..20925d13fa
--- /dev/null
+++ b/.ai/plans/2026-09-16-consume-first-made-parts.md
@@ -0,0 +1,116 @@
+# Consume First for made parts — same rule as bought parts
+
+Branch: `supersession-trial-pdf-issues`. Decision (user, 2026-09-16): a made
+Consume First predecessor with stock is used up first, exactly like a bought
+one. Job creation and MRP both net the old part's on-hand in whole assemblies
+and move only the shortfall to the successor.
+
+## Scope
+
+- MRP: a Consume First child of ANY replenishment stays on the predecessor in
+ the BOM; the engine nets the predecessor's on-hand per contributor in whole
+ assemblies and moves the shortfall to the successor, which then plans as
+ itself (explodes its own BOM when Make, surfaces as buy when Buy). Replaces
+ the bought-only post-explosion pass in `mrp.ts`, which could not explode a
+ made successor.
+- Job creation: a Pull from Inventory line for a made predecessor gets the same
+ per-line settle as a bought line. Make to Order lines keep the successor swap
+ (a Make to Order line never consumes stock, so "use the old stock" has no
+ meaning for it, and building the phased-out part fresh is never wanted).
+
+## Tasks
+
+- [x] `lib/mrp-engine.ts`: `explodeBom` takes `consumeFirstRedirect`; levels
+ the successor below the predecessor; nets + redirects at the predecessor.
+- [x] `lib/mrp-engine.test.ts`: made predecessor nets stock and explodes only
+ the successor's BOM for the shortfall; a shallower successor still
+ receives the redirected demand; bought behaviour unchanged.
+- [x] `packages/ee/src/planning/mrp/mrp.ts`: drop the Make exception in the
+ BOM rewrite, pass the redirect map + Phase 4.5 remaining on-hand into the
+ engine, delete the post-pass.
+- [x] `get-method/index.ts`: `settleConsumeFirstLines` also settles a line
+ swapped at creation from a Consume First predecessor (revert to the
+ predecessor when it covers a whole assembly); `loadSupersessionRedirect`
+ comment restated.
+- [x] Docs: `.claude/rules/supersession-system.md`, `.ai/lessons.md`.
+- [x] Verify: `deno test --no-lock lib/mrp-engine.test.ts lib/supersession-pick.test.ts`
+ in `packages/database/supabase/functions`; `pnpm exec turbo run typecheck --filter=@carbon/ee`;
+ `deno check --no-lock get-method/index.ts`.
+
+## Follow-up (same day): Make to Order lines
+
+Decision (user): per-unit matching, bought and made alike; a batch may mix
+units, a unit never mixes parts. No line split.
+
+- [x] `get-method`: `loadSupersessionRedirect` returns `{ redirect,
+ consumeFirstOnHand }`; `itemToJob` / `itemToJobMakeMethod` row builders
+ turn a Make to Order line into Pull from Inventory on the predecessor
+ when `consumableInWholeAssemblies(onHand, quantity) > 0`; `madeChildren`
+ derived from the built rows.
+- [x] Picking excludes Make to Order lines: `generatePickingList` (TS) and
+ `get_picking_schedule` (migration `20260908211552`, NOT yet applied).
+- [x] Docs: rule + lessons.
+- [x] Verify: deno test (37 pass), deno check get-method (no new errors),
+ biome (pre-existing warnings only), migration compiled in a rolled-back
+ transaction, ERP typecheck.
+
+## Follow-up: gaps 2 and 3 (same day)
+
+- [x] Fix 3 — successor lead time: `explodeBom` places the redirected
+ shortfall earlier by the successor's longer lead time, never later.
+ Test: "fix 3" in `lib/mrp-engine.test.ts`.
+- [x] Fix 2 — chains hop by hop: `buildConsumeFirstHops` +
+ `firstStockedInConsumeFirstChain` (lib, tested); MRP Phase 4.5 and the
+ engine use hops; both job-creation flows walk the chain for a Make to
+ Order line. Test: "fix 2" in `lib/mrp-engine.test.ts`.
+- [ ] Fix 1 — job-to-job copies of a converted line: NOT done. Needs made
+ sub-assembly explosion inside `jobToJob` (the documented "later layer");
+ a copied line has no marker that its BOM source was Make to Order, so
+ a partial fix would guess. See the summary to the user.
+
+## Follow-up: Phase 4.5 whole assemblies (same day)
+
+- [x] `netConsumeFirstContributors` (engine, exported, tested) is the one
+ per-contributor netting; the engine's redirect and MRP Phase 4.5 both
+ use it. Job Material contributors carry `perAssemblyQuantity`.
+ Trial: J000038 (2 ASM, 2 OLD per unit, 3 OLD on shelf) now plans
+ NEW 2, not 1.
+
+## Follow-up: review findings (same day)
+
+- [x] Make to Buy successor: a Make to Order line with no stocked hop and a
+ bought successor is created as Pull from Inventory on the successor.
+- [x] Chains: Phase 4.5 runs predecessor-first along the hops; moved
+ contributors keep the origin and a converted per-assembly quantity.
+ Closes the lineage and actual-demand findings.
+- [ ] Job-to-job copies: deferred (needs made sub-assembly explosion in that
+ flow). Not in this PR.
+- [x] Inline share: not a defect — a Make to Order successor is built inline,
+ so no separate production forecast row is correct. Closed, no change.
+
+## Follow-up: quality pass (same day)
+
+- [x] `supersessionMode` typed as the DB enum everywhere it was `string`
+ (lib `SupersessionMode`, MRP, ERP picking module, forecast route).
+- [x] `resolveMadeLinePull` + `SupersessionContext` replace the duplicated
+ Make to Order decision in both job-creation flows.
+- [x] Order Status badge reads the substitute item's supply jobs and PO
+ lines, so a job raised for the NEW remainder shows "Planned job".
+- [x] Every comment added on this branch removed (309 lines, 29 files);
+ functional directives kept.
+- [x] The two schedule migrations merged into
+ `20260908211552_picking-supersession-consume-first.sql`.
+
+## Follow-up: lineside credit (same day)
+
+- [x] One definition of usable lineside stock (`linesideCredit` /
+ `get_lineside_credit`): own live picks + unclaimed on-hand, claims only
+ from live jobs. Used by the generator (all lines, running balance per
+ item+bin), the schedule, and consumption budgets.
+- [x] Consume First picks credit staged parts in whole assemblies across both
+ items (`splitConsumeFirstPick`, tested); consumption takes a
+ predecessor only in whole assemblies.
+- [x] Schedule hides an operation only while a list is OPEN.
+- [ ] Cancelling a pick list leaves picked material at the lineside bin
+ (status flip only). Now harmless — the stock is unclaimed and reused —
+ but returning it on cancel is a product decision. Not changed.
diff --git a/.claude/rules/supersession-system.md b/.claude/rules/supersession-system.md
index 55c32a35fc..69353b795a 100644
--- a/.claude/rules/supersession-system.md
+++ b/.claude/rules/supersession-system.md
@@ -13,7 +13,23 @@ paths:
`discontinuationDate` and `conversionFactor` (1 old = N new).
Authored at **Part → Planning → Supersession** (`ItemSupersessionForm`, rendered
-by `x+/part+/$itemId.planning.tsx`).
+by `x+/part+/$itemId.planning.tsx`). The same card lists the parts that name
+this item as their successor ("Supersedes", from `getItemSupersededBy`) and has
+an **Add Predecessor** modal (`predecessorSupersessionValidator`, intent
+`supersession-predecessor`) that writes the row on the OLD item with this item
+as successor — a planner starts from the new BOM, so the rule must be
+authorable from the successor side. The row still lives on the predecessor;
+the engines need no reverse lookup.
+
+`upsertItemSupersession` refuses a **loop** (A→B plus B→A, any length) with
+`SUPERSESSION_CYCLE_CODE`; the route surfaces it as a field error. Before this
+guard the redirect map silently dropped both entries and neither part ever
+swapped, which reads as "working" in a trial.
+
+`discontinuationDate` only suppresses NEW purchase suggestions for the old part
+(`purchasing-planning` views); it never stops picking or production. It is
+optional for `Consume First` — that mode switches when stock runs out, not on a
+date.
## Three consumers, three different questions
@@ -22,31 +38,248 @@ Do not assume one rule. Each answers something different, deliberately.
| Consumer | Source | Question |
|---|---|---|
| **MRP** (`mrp/index.ts`) | live, every run | what should we BUY? |
-| **Job creation** (`get-method`) | live at creation, then **frozen** | what does this job consume? |
+| **Job creation** (`get-method`) | live at creation, then **frozen** | what does this job consume? (a `Consume First` predecessor with stock at the job's location keeps its Pull from Inventory lines, bought or made — the item-level `withoutStockedConsumeFirst` filter in `loadSupersessionRedirect` is provisional and `settleConsumeFirstLines` applies the per-line whole-assembly rule after insert. A made predecessor's **Make to Order** line follows the same rule by becoming a Pull from Inventory line on the predecessor when its stock covers at least one whole assembly — a Make to Order line is built in the job and never consumes stock, so pulling it is the only way the old sub-assemblies get used; with no whole assembly in stock it swaps to the successor's method and is built) |
| **Picking** (`inventory/supersession-pick.ts`) | live, at pick time | what do we pull off the shelf? |
A `jobMaterial` row is a **snapshot**. Editing a supersession afterwards never
rewrites existing rows — but picking re-evaluates live, so the same job can be
picked differently tomorrow. That split is intentional; don't "fix" it.
-## Mode gating — only two modes redirect
+## Mode gating — three modes redirect
-`REDIRECTING_MODES = { "Consume First", "Prefer New" }`
-(`lib/supersession-pick.ts`). `Stock Only` keeps its successor as a
-reserve-governed reference; `No Stock` has no successor.
+`REDIRECTING_MODES = { "Consume First", "Prefer New", "Stock Only" }`
+(`lib/supersession-pick.ts`). `Stock Only` is "service reserve, no production
+use", so production demand moves to the successor like a phase-out mode; only
+the predecessor's OWN replenishment is reserve-governed (the planning views top
+it up to `minimumReserveQuantity`). Leaving it out made a job's BOM name the
+spares-only part and dropped the successor demand from purchasing. `No Stock`
+has no successor and never redirects.
-**This is the single most common way to set up a test that proves nothing** —
-seed `Stock Only`, watch nothing swap, conclude the feature works.
+**The single most common way to set up a test that proves nothing** — seed
+`No Stock`, or a two-row loop, watch nothing swap, conclude the feature works.
-Picking uses a *different* rule set on purpose
+Picking is stock-aware on purpose
(`apps/erp/app/modules/inventory/supersession-pick.ts`, mirrored by
-`get_picking_schedule`):
+`get_picking_schedule`, migration `20260908211552`). The supersession row is
+looked up by `resolvePickRule`: the row's OWN item's rule when its successor is
+the `substitutedFromItemId` (a line pulled back onto the predecessor — the
+column holds the successor), else the `substitutedFromItemId`'s rule (a line
+swapped at creation — the column holds the predecessor), else the row's own.
+Keying on the material's own item alone found no row for a swapped line, so
+`Consume First` never consumed the predecessor for any job created after the
+effectivity date; trusting the column FIRST inverted the roles on a pulled-back
+line whenever the successor had a rule of its own (NEW → NEWER) and sent the
+pick back to NEW. The SQL's lateral `ORDER BY` encodes the same precedence.
+
+Material still on the predecessor:
- `No Stock` → skip
- `Stock Only` → pick the successor (never the spares-only predecessor)
-- `Prefer New` → successor, falling back to the predecessor until effective
+- `Prefer New` → successor when effective, falling back to the predecessor
+ while the successor has no warehouse stock and the predecessor does
- `Consume First` → predecessor **until it has no warehouse stock**, then successor
+Material swapped at creation (`substitutedFromItemId` set, quantity in
+successor units; effectivity is not re-checked — for `Consume First` this only
+happens when the predecessor had no stock at creation):
+
+- `Consume First` → predecessor while it has warehouse stock, then successor
+- `Prefer New` → successor, unless it has no stock and the predecessor does
+- anything else → successor
+
+Pulling the predecessor converts the quantity by `1 / substitutionFactor`.
+A row the BOM's successor pulled onto the predecessor carries the successor in
+`substitutedFromItemId`; `resolvePickRule` reads it as an unswapped line on the
+predecessor (see above), whether or not the successor has a rule of its own.
+
+**Whole assemblies.** A unit that needs N of the part gets N of the SAME
+part — two of the old or two of the new, never one of each. Every Consume
+First consumer rounds the predecessor's usable on-hand DOWN to a multiple of
+the line's per-assembly quantity with `consumableInWholeAssemblies(onHand,
+perAssembly)` (`lib/supersession-pick.ts`; `RoundingMode.Down` exists for it).
+2 per assembly and 3 on the shelf fits ONE assembly: 2 old, the rest new, and
+the odd part stays in stock. Units of one batch may differ from each other; a
+single unit never mixes. This came from a customer who would rather leave one
+old part on the shelf than fit a mismatched pair — the unit-level split before
+it did exactly that. A row's `quantity` is the per-assembly quantity in the
+row's own units; a row swapped at creation holds successor units, so the
+predecessor's per-assembly quantity is `quantity / substitutionFactor`
+(`perAssemblyOld` in `generatePickingList` and the SQL).
+
+**Partial stock.** A job line is never split at creation: a Consume First
+line stays whole on the predecessor whenever it covers at least one assembly,
+and the job materials page shows "N in stock, for K assemblies; the remaining
+M will be picked as NEW" (`consumeFirstByItemId` in `$jobId.materials.tsx`,
+computed live from the row's on-hand, rounded as above).
+`generatePickingList` is where the split happens: it picks the predecessor for
+the whole assemblies the warehouse covers and the successor for the rest, as
+two pick lines on one material, and the page then shows the pick-based note
+instead. `settleConsumeFirstLines` (get-method, after every row of a job is
+inserted, all four flows) settles every Pull from Inventory line, bought or
+made. The decision per line is the pure `settleConsumeFirstLine`
+(`lib/supersession-pick.ts`, with `buildConsumeFirstRules` and the shared
+threshold `keepsLineOnPredecessor`), pinned by `lib/supersession-pick.test.ts`;
+get-method only loads stock and writes the row. Three cases — a row SWAPPED at creation from a Consume First predecessor that covers
+one assembly is reverted onto it with no provenance (the BOM named it; the
+provisional map swaps a made predecessor regardless of stock, for its Make to
+Order lines); a row on the successor with a predecessor that covers one
+assembly becomes the predecessor (`substitutedFromItemId` = the successor,
+`substitutionFactor` = `1 / factor`); a row kept on a predecessor whose
+on-hand covers no whole assembly of it is pushed to the successor. The
+item-level `withoutStockedConsumeFirst` filter only asks "any stock" and is
+provisional; the settle pass is what applies the per-line rule.
+The job materials **Order Status** column (`getJobMaterialShortfallByItem`)
+nets a Consume First shortfall against the successor's on-hand and incoming
+supply in a second pass; `ItemOrderStatus.substituteItemId` tells the badge to
+say "In stock, the remainder as NEW" or "Order N × NEW for this job". The
+successor's own supply also drives the badge: `getJobMaterialsOrderStatus`
+loads PO lines and supply jobs for every substitute item that is not itself a
+material of the job, and `getJobOrderStatusByMaterial` reads a line's own item
+AND its substitute — so a job raised for the NEW remainder shows "Planned job"
+on the OLD line instead of no badge at all.
+The item planning tab's supply/demand list (`api+/items.$id.$locationId.forecast.ts`,
+`getRedirectedOpenJobMaterials`) applies the same split to open job material
+lines so the rows match the bars: the predecessor keeps what its on-hand
+covers, the successor lists the remainder "via <predecessor>".
+`hasWarehouseStock` / the SQL `EXISTS … GROUP BY storageUnitId HAVING SUM > 0`
+both count any single non-lineside bin (including the unassigned bin) with
+positive on-hand.
+
+**Lineside credit.** Before anything is picked, material already at the
+operation's lineside bin is credited, and both the generator and the schedule
+use ONE definition (`linesideCredit` in `lib/picked-consumption.ts`, exported
+to Node through `@carbon/database/picked-consumption`; `get_lineside_credit`
+in SQL): the material's OWN live pick lines to that bin (picked − returned,
+less the job's consumption of the item) plus whatever on-hand at the bin no
+LIVE job's live pick line claims — a claim is Σ(picked − returned) of a job's
+non-cancelled lines to the bin minus that job's consumption, and only jobs in
+Planned / Ready / In Progress / Paused hold claims (a finished job never
+consumes its leftover pick; a cancelled list's picked material is simply
+unclaimed). For a Consume First line the credit is taken in whole assemblies
+across predecessor AND successor (`splitConsumeFirstPick`, ERP
+`supersession-pick.ts`, tested) — one assembly of each already at the bin
+means nothing to pick — and the generator keeps a running `unclaimedRemaining`
+per (item, bin) so two materials in one list cannot credit the same stock.
+Consumption sees the same stock: `getPickedBudgets` takes the operation's
+lineside bin (`getOperationLinesideBin`) and adds the unclaimed on-hand of the
+line's item, its predecessor and its successor as budgets, and
+`allocateAcrossBudgets` takes a PREDECESSOR budget only in whole assemblies
+(`perAssembly`, the material's per-parent quantity), so a unit is never
+completed with one old and one new part out of the bin. The schedule hides an
+operation only while it is on an OPEN list (Draft / In Progress / Partial),
+not forever after a completed one, so a job whose quantity grows after
+picking gets a card for the remainder.
+
+Inside `generatePickingList` the predecessor's stock test is the **running
+balance** (`warehouseRemaining`, seeded from `getWarehouseOnHand` and drawn
+down by every earlier line of the list) and nothing else — an `||
+hasWarehouseStock` fallback let a later line pick the predecessor in full after
+earlier lines had used it up, and never split. The "already staged at the op's
+lineside bin" check runs BEFORE the split, so material sitting at the machine
+neither charges the balance nor raises a successor line for nothing.
+
+**Make to Order lines.** The row builders of `itemToJob` and
+`itemToJobMakeMethod` resolve a Make to Order child against
+`consumeFirstOnHand` (the second value `loadSupersessionRedirect` returns: the
+job-location on-hand of every MADE Consume First predecessor whose rule is
+effective) BEFORE the row is built: when
+`consumableInWholeAssemblies(onHand, quantity) > 0` the row's `methodType`
+becomes `Pull from Inventory` on the predecessor, so it is inserted as a
+picked row — no `jobMakeMethod` is created (the insert interceptor keys on
+`methodType`), nothing is exploded, and picking splits it per unit like any
+other Consume First line. Otherwise `swapMadeSubAssembly` swaps it to the
+successor and explodes the successor's method. `madeChildren` is therefore
+derived from the BUILT rows' `methodType`, not the BOM lines' — the two are
+paired by index in the made-children loop, and a converted row must drop out
+of both. This is per unit, never per batch: a batch of five may use old
+sub-assemblies on three units and new on two, but one unit never mixes.
+Converting to Pull from Inventory (rather than splitting the line into a
+picked half and a built half) is what keeps it stable under `recalculate`,
+which rebuilds every line as per-assembly quantity × parent quantity and
+would inflate a split back to two full lines.
+
+**Picking never stages a Make to Order line** (`generatePickingList`
+`.neq("methodType", "Make to Order")`, `get_picking_schedule` migration
+`20260908211552`). The parent operation never consumes such a line from stock
+(`issue`'s backflush skips it), so a pick only moved material to lineside that
+nothing would use. Since unassigned materials were attributed to the first
+operation of their method (`20260720160557`) every Make to Order sub-assembly
+was scheduled that way — visible as a second, phantom pick (old and new from
+the shelf) for a sub-assembly the job was already building as its successor.
+
+`settleConsumeFirstLines` is scoped to the rows the calling flow **just
+inserted** (`jobMaterialIds`, collected at every `jobMaterial` insert of the
+four flows) and skips any row with issued quantity. Get Method on one
+sub-method rebuilds only that sub-method's rows; the job-wide read it started
+with rewrote lines on other sub-methods — some already issued in successor
+units. The moved row's quantities come from `pullBackQuantities`
+(`lib/supersession-pick.ts`), which is direction-agnostic despite its name:
+recover the source's target (`estimatedQuantity − scrapQuantity` on a Buy/Pick
+row), convert, and re-derive scrap at the TARGET item's rate — the rate the
+row now carries.
+
+Cancelling a job (`$jobId.status.tsx`) returns the staged material first, then
+`cancelOpenPickingListsForJob` cancels its lines on every open list and the
+lists that have no live line left; a list shared with other jobs stays open.
+`get_picking_schedule` ignores a cancelled LINE as well as a cancelled list, so
+a reopened job's operation returns to the schedule. Its Consume First
+predecessor stock test is the whole-assembly one (warehouse on-hand ≥
+`perAssemblyOld`, migration `20260908211552`); Prefer New keeps the any-bin
+test because it never splits.
+
+The substituted pick line's note (ERP `PickingListLines`, MES picking route)
+says how many assemblies it covers — "8 × NEW in place of OLD, for 4
+assemblies" — from the job material's `quantity` and factor; the select embeds
+`jobMaterial(quantity, substitutionFactor, item(itemSupersession(conversionFactor)))`
+for that. Only shown when it is a whole number.
+
+## Consumption follows what was picked
+
+`lib/picked-consumption.ts`. A pick can bring a different part than the job
+material names (a Consume First split, a Prefer New fallback, a Stock Only
+redirect), and the material row is never rewritten after creation — so the
+consumers read the pick lines instead of the row:
+
+- `getPickedBudgets` — per picked item for one material: staged at lineside
+ (`Σ picked − returned` over live lines) minus what the job has already
+ consumed of that item (`itemLedger` "Job Consumption" rows for the job at
+ the location), the lineside bin, and the line-units→item-units factor
+ (`pickFactor`, from the supersession rule in either direction, else the
+ row's `substitutionFactor`).
+- `orderOldFirst` — predecessors first, then the line's own item, then the
+ rest. Partial completions therefore use up the old part before touching the
+ new one.
+- `allocateAcrossBudgets` — spreads a line-unit quantity across the budgets;
+ what no pick covered is returned as `remaining` and the caller falls back to
+ the material's own item from its own bin (the pre-existing behaviour).
+
+**A budget is two pools, and only one is shared.** `own` is the material's
+OWN live pick (scoped by `jobMaterialId`, so private to that material, at
+the bin its pick lines went to); `unclaimed` is what sits at the operation's
+lineside bin that no live job's pick claims, shared by every material of the
+operation. `available` is their sum. `allocateAcrossBudgets` attributes each
+take own-first (`fromOwn` / `fromShared`), `recordSharedTakes` accumulates
+ONLY the shared portion per (item, bin) into a `SharedTakes` map, and
+`getPickedBudgets` subtracts that map from `unclaimed` alone. The backflush
+loops over every material of the operation before inserting its ledger rows,
+so without the map two materials sharing a picked item were both offered the
+same unclaimed stock; but recording the WHOLE take, keyed by item, let
+material A's private pick zero out material B's private pick, and B fell
+back to the warehouse while its staged stock sat at the machine.
+`splitTakeByBin` turns a take back into ledger rows — the own portion
+against the pick bin, the shared portion against the lineside bin — so a
+take that draws on both pools is never charged to one bin.
+
+Used by `issue` (`issueJobOperationMaterials` completion backflush and
+`partToOperation` manual/step issue, negative adjustments only) and by
+`post-picking` (`returnUntrackedMaterialRemainder` holds `owed` back
+predecessor-first and returns the rest per item; `maybeRestoreJobMaterialSource`
+keeps the lineside pointer while any budget is still available). Pinned by
+`lib/picked-consumption.test.ts`.
+
+Consumed-so-far is attributed per (job, item), not per material — two
+materials on one job sharing an item share one counter.
+
## `buildSupersessionRedirectMap` — the shared builder
`lib/supersession-pick.ts`, used by MRP and `get-method` so both resolve a
@@ -59,6 +292,67 @@ the factors.
(all three columns are `DATE`, so string order is chronological).
- `asOfDate` differs by caller: MRP uses today in the **company timezone**;
`get-method` uses the job's build date (`jobBuildDate`).
+- **MRP nets a Consume First component's on-hand, bought or made.** Top-level
+ demand (Phase 4.5) draws the old item's on-hand down first; the BOM rewrite
+ leaves every Consume First child on the old part and passes the rule to the
+ engine as `consumeFirstRedirect` (`lib/mrp-engine.ts`), with the engine's
+ starting on-hand for the old part overlaid from `remainingConsumeFirstOnHand`.
+ When the engine reaches the old part it nets its running balance **per
+ contributor in whole assemblies** (`redirectConsumeFirstShortfall`: each
+ contributor is one parent's demand and carries `perAssemblyQuantity`, the
+ IMMEDIATE parent's per-unit need stamped by the cascade — `parentItemId` is
+ the root source's item and cannot answer that for a sub-sub-assembly — so a
+ parent needing two per unit draws only multiples of two, at any depth) and moves the shortfall (× factor, stamped
+ `redirectedFromItemId`) to the successor — in the old part's period, or
+ EARLIER by the difference when the successor's lead time is longer (the
+ parent needs it by the same date); never later, since the old part's period
+ may already be floored at period[0]. The old part
+ never explodes its own BOM; the successor is planned as itself at a deeper
+ level — its BOM explodes for exactly the shortfall when it is Make, and it
+ surfaces as a buy when it is Buy. The supersession is a synthetic edge in
+ `computeLowLevelCodes` for that: a successor that also sits shallower in
+ another BOM would otherwise be planned before the redirect reaches it.
+ Phase 4.5 (demand on the old part ITSELF — its own sales lines and existing
+ job lines) nets the same way through the shared `netConsumeFirstContributors`
+ (`lib/mrp-engine.ts`): a Job Material contributor carries
+ `perAssemblyQuantity` from `openJobMaterialLines.quantityPerParent`, so an
+ open job line needing two per unit draws only multiples of two, and only the
+ MOVED contributors are stamped onto the successor (before this every
+ contributor was copied over at full quantity). Sales lines and projections
+ have no per-assembly quantity and net by the unit. Pinned by
+ `lib/mrp-engine.test.ts`.
+- **The redirect also moves the ACTUAL demand rows.** Phase 4.5 rewrites
+ `jobMaterialDemandByKey` / `salesDemandByKey` in the same proportion it
+ moves `grossDemand`, so `demandActual` (which `get_purchasing_planning`,
+ `get_production_planning` and the item planning chart read) shows the
+ predecessor with only what its stock covers and the successor with the rest
+ in successor units. Before this, planning suggested buying the predecessor
+ while the successor sat in stock.
+- **Consume First walks its chain one hop at a time.** The collapsed map
+ (`A→B→C` to `A→C`) is right for Prefer New / Stock Only, where B is being
+ skipped, but B's own shelf stock must be used before Consume First demand
+ moves on. `buildConsumeFirstHops` (same file) maps each effective Consume
+ First item to the NEXT Consume First item in its chain, collapsing only
+ through non-Consume-First hops and multiplying their factors; a chain that
+ never terminates is dropped. MRP passes every hop as `consumeFirstRedirect`
+ (a middle hop gets demand only through the redirect and must still net its
+ stock) and Phase 4.5 moves a Consume First shortfall to the hop, not the
+ collapsed terminal. Job creation walks the same hops for a Make to Order
+ line (`firstStockedInConsumeFirstChain`): the first item in the chain with
+ a whole assembly in stock becomes the Pull from Inventory line, recorded as
+ a swap when it is not the BOM's own item. With no stock anywhere in the
+ chain and a BOUGHT successor (`boughtSuccessors`, the fourth value the
+ loader returns: every redirect target whose effective replenishment is not
+ Make), the line becomes a Pull from Inventory line on the successor — it is
+ purchased — instead of falling through `swapMadeSubAssembly` (no make
+ method on a bought item) to building the phased-out part. A Pull from
+ Inventory line needs no walk — `settleConsumeFirstLine` already pulls it
+ back onto any direct stocked predecessor of the item it landed on.
+ Phase 4.5 iterates redirected items predecessor-first along the hops
+ (`redirectOrder`), so a hop's own pass sees the demand, actuals and
+ contributors its predecessor just moved onto it and splits them again;
+ a moved contributor keeps its ORIGINAL `redirectedFromItemId` and has its
+ `perAssemblyQuantity` converted by the factor.
- **Cycles are dropped, not collapsed.** A two-row cycle (`A→B` plus `B→A`) is
writable from the UI — only *self*-reference is blocked, by both the DB CHECK
and the zod refine. Collapsing one produced `A → A` with the cycle's factor
@@ -86,7 +380,14 @@ there under-explodes the entire sub-tree — every row below looks individually
correct on a wrong base.
`loadSupersessionRedirect` is loaded **once per request**, before the
-transaction, in all four flows. It pages with `fetchAll` + `.order("itemId")`;
+transaction, in all four flows, and returns a `SupersessionContext`
+(`lib/supersession-pick.ts`: the collapsed `redirect` map, `consumeFirstHops`,
+`consumeFirstOnHand`, `boughtSuccessors`); `resolveMadeLinePull(itemId,
+perAssembly, ctx)` is the one decision for a Make to Order line — stocked
+chain hop first, then a bought successor, else null (build). `supersessionMode`
+is typed everywhere as the DB enum
+(`Database["public"]["Enums"]["supersessionMode"]`, re-exported from the lib
+as `SupersessionMode`), never `string`. It pages with `fetchAll` + `.order("itemId")`;
a bare select stops at PostgREST's 1000-row cap and would silently redirect a
different subset than MRP.
@@ -108,9 +409,17 @@ re-derives it when the stored value is NULL — which a NOT NULL column never is
documented as "a later layer". Fail-safe (you get the quoted/copied
structure), but it disagrees with MRP, which has already redirected that
demand.
-- A Make→Buy successor leaves the line on the predecessor, and that fallthrough
- is indistinguishable from "successor's make method isn't Active" or "item read
- failed".
+- A Make→Buy successor now becomes a Pull from Inventory line on the bought
+ successor at job creation (see the chain paragraph above); the remaining
+ fallthrough is a MADE successor whose make method isn't Active, or an item
+ read failure — both leave the line on the predecessor, indistinguishably.
+- A Make to Order line pulled from a Consume First predecessor's stock is a
+ Pull from Inventory line for the WHOLE quantity: the units the shelf does
+ not cover are picked as the successor from stock, or planned by MRP (which
+ nets the same predecessor stock and moves the shortfall to the successor).
+ The job never builds the successor remainder itself. Splitting the line
+ into a picked half and a built half would need `recalculate`'s quantities
+ engine to know about the split.
- `jobBuildDate` falls back to **UTC today** when a job has neither start nor due
date — which is the default creation path (`No Deadline` renders no due-date
field). MRP uses the company timezone; this is where the shared-map guarantee
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index c02a85edc6..b068f4e7e2 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -1,6 +1,11 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import {
+ type LinesideClaim,
+ linesideCredit
+} from "@carbon/database/picked-consumption";
+import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { datetime } from "@carbon/utils";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
@@ -42,7 +47,10 @@ import {
import {
effectiveSuccessorId,
type PickSupersession,
- resolvePickTarget
+ pickSupersessionItemId,
+ resolvePickRule,
+ resolvePickTarget,
+ splitConsumeFirstPick
} from "./supersession-pick";
export async function deleteBatchProperty(
@@ -2717,6 +2725,60 @@ export async function getPickingList(
.single();
}
+export async function getPicksByJobMaterial(
+ client: SupabaseClient<Database>,
+ jobId: string,
+ companyId: string
+) {
+ const lines = await client
+ .from("pickingListLine")
+ .select(
+ "jobMaterialId, itemId, quantityToPick, quantityPicked, quantityReturned, status, jobMaterial(itemId), pickingList!inner(id, pickingListId, status), item(readableIdWithRevision)"
+ )
+ .eq("jobId", jobId)
+ .eq("companyId", companyId)
+ .neq("status", "Cancelled")
+ .neq("pickingList.status", "Cancelled");
+
+ const byMaterial: Record<string, JobMaterialPick[]> = {};
+ for (const line of lines.data ?? []) {
+ if (!line.jobMaterialId || !line.itemId) continue;
+ const picks = (byMaterial[line.jobMaterialId] ??= []);
+ const key = `${line.itemId}:${line.pickingList.id}`;
+ let pick = picks.find((p) => `${p.itemId}:${p.pickingListId}` === key);
+ if (!pick) {
+ pick = {
+ itemId: line.itemId,
+ itemReadableId: line.item?.readableIdWithRevision ?? line.itemId,
+ isSubstitute: line.jobMaterial?.itemId !== line.itemId,
+ quantityToPick: 0,
+ quantityPicked: 0,
+ pickingListId: line.pickingList.id,
+ pickingListReadableId: line.pickingList.pickingListId,
+ pickingListStatus: line.pickingList.status
+ };
+ picks.push(pick);
+ }
+ pick.quantityToPick += Number(line.quantityToPick ?? 0);
+ pick.quantityPicked += Math.max(
+ 0,
+ Number(line.quantityPicked ?? 0) - Number(line.quantityReturned ?? 0)
+ );
+ }
+ return { data: byMaterial, error: lines.error };
+}
+
+export type JobMaterialPick = {
+ itemId: string;
+ itemReadableId: string;
+ isSubstitute: boolean;
+ quantityToPick: number;
+ quantityPicked: number;
+ pickingListId: string;
+ pickingListReadableId: string;
+ pickingListStatus: string;
+};
+
export async function getPickingListLines(
client: SupabaseClient<Database>,
pickingListId: string
@@ -2724,7 +2786,7 @@ export async function getPickingListLines(
return client
.from("pickingListLine")
.select(
- "*, item(name, readableId, itemTrackingType), jobMaterial(itemId, item(readableId)), job(jobId), jobOperation(order, processId, workCenterId, process:process(name), workCenter:workCenter(name)), storageUnit:storageUnit!pickingListLine_storageUnitId_fkey(name, locationId), toStorageUnit:storageUnit!pickingListLine_toStorageUnitId_fkey(name, locationId), trackedEntities:pickingListLineTrackedEntity(trackedEntityId, quantity, quantityPicked, trackedEntity(readableId))"
+ "*, item(name, readableId, itemTrackingType), jobMaterial(itemId, quantity, substitutionFactor, item(readableId, itemSupersession!itemSupersession_itemId_fkey(conversionFactor))), job(jobId), jobOperation(order, processId, workCenterId, process:process(name), workCenter:workCenter(name)), storageUnit:storageUnit!pickingListLine_storageUnitId_fkey(name, locationId), toStorageUnit:storageUnit!pickingListLine_toStorageUnitId_fkey(name, locationId), trackedEntities:pickingListLineTrackedEntity(trackedEntityId, quantity, quantityPicked, trackedEntity(readableId))"
)
.eq("pickingListId", pickingListId)
.order("jobOperationId")
@@ -3047,6 +3109,61 @@ export async function getUnresolvedPickingListLines(
return { unresolved, hasShort, error: null };
}
+export async function cancelOpenPickingListsForJob(
+ db: Kysely<KyselyDatabase>,
+ args: { jobId: string; companyId: string; userId: string }
+): Promise<{ error: Error | null }> {
+ try {
+ await db.transaction().execute(async (trx) => {
+ const lines = await trx
+ .selectFrom("pickingListLine as pll")
+ .innerJoin("pickingList as pl", "pl.id", "pll.pickingListId")
+ .select(["pll.id", "pll.pickingListId"])
+ .where("pll.jobId", "=", args.jobId)
+ .where("pll.companyId", "=", args.companyId)
+ .where("pll.status", "<>", "Cancelled")
+ .where("pl.status", "in", ["Draft", "In Progress"])
+ .execute();
+ if (lines.length === 0) return;
+
+ const now = new Date().toISOString();
+ await trx
+ .updateTable("pickingListLine")
+ .set({ status: "Cancelled", updatedBy: args.userId, updatedAt: now })
+ .where(
+ "id",
+ "in",
+ lines.map((line) => line.id)
+ )
+ .execute();
+
+ const pickingListIds = Array.from(
+ new Set(lines.map((line) => line.pickingListId))
+ );
+ const remaining = await trx
+ .selectFrom("pickingListLine")
+ .select("pickingListId")
+ .where("pickingListId", "in", pickingListIds)
+ .where("companyId", "=", args.companyId)
+ .where("status", "<>", "Cancelled")
+ .execute();
+ const stillLive = new Set(remaining.map((line) => line.pickingListId));
+ const emptied = pickingListIds.filter((id) => !stillLive.has(id));
+ if (emptied.length === 0) return;
+
+ await trx
+ .updateTable("pickingList")
+ .set({ status: "Cancelled", updatedBy: args.userId, updatedAt: now })
+ .where("id", "in", emptied)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ });
+ return { error: null };
+ } catch (err) {
+ return { error: err instanceof Error ? err : new Error(String(err)) };
+ }
+}
+
export async function updatePickingListStatus(
client: SupabaseClient<Database>,
pickingListId: string,
@@ -3179,6 +3296,46 @@ async function resolveWarehouseSource(
return null;
}
+function toPickFactor(value: number | string | null | undefined): number {
+ const n = Number(value ?? 1);
+ return Number.isFinite(n) && n > 0 ? n : 1;
+}
+
+async function getWarehouseOnHand(
+ client: SupabaseClient<Database>,
+ args: { itemId: string; locationId: string; companyId: string }
+): Promise<number> {
+ const quantities = await getItemStorageUnitQuantities(
+ client,
+ args.itemId,
+ args.companyId,
+ args.locationId
+ );
+
+ const perUnit = new Map<string, number>();
+ let total = 0;
+ for (const row of quantities.data ?? []) {
+ const unitId = (row as { storageUnitId?: string | null }).storageUnitId;
+ const qty = Number((row as { quantity?: number | null }).quantity ?? 0);
+ if (!unitId) {
+ total += qty;
+ } else {
+ perUnit.set(unitId, (perUnit.get(unitId) ?? 0) + qty);
+ }
+ }
+ total = Math.max(0, total);
+
+ for (const [storageUnitId, qty] of perUnit) {
+ if (qty <= 0) continue;
+ const effectiveWc = await client.rpc("get_effective_work_center_id", {
+ p_storage_unit_id: storageUnitId
+ });
+ if (!effectiveWc.data) total += qty;
+ }
+
+ return total;
+}
+
/**
* Whether an item has any WAREHOUSE (non-lineside) on-hand at a location,
* INCLUDING the unassigned (null storage unit) bin.
@@ -3228,6 +3385,12 @@ async function hasWarehouseStock(
return false;
}
+class PickingReadError extends Error {
+ constructor(readonly postgrestError: PostgrestError) {
+ super(postgrestError.message);
+ }
+}
+
export async function generatePickingList(
client: SupabaseClient<Database>,
args: {
@@ -3321,10 +3484,11 @@ export async function generatePickingList(
let materialsQuery = client
.from("jobMaterial")
.select(
- "id, jobId, jobOperationId, jobMakeMethodId, itemId, quantityToIssue, storageUnitId, requiresSerialTracking, requiresBatchTracking"
+ "id, jobId, jobOperationId, jobMakeMethodId, itemId, substitutedFromItemId, substitutionFactor, quantity, quantityToIssue, storageUnitId, requiresSerialTracking, requiresBatchTracking"
)
.eq("companyId", args.companyId)
- .gt("quantityToIssue", 0);
+ .gt("quantityToIssue", 0)
+ .neq("methodType", "Make to Order");
materialsQuery =
makeMethodIds.length > 0
? materialsQuery.or(
@@ -3343,7 +3507,12 @@ export async function generatePickingList(
// Stock Only) or, for Consume First, when the predecessor is out of stock.
// Mirrors get_picking_schedule's SQL resolution.
const materialItemIds = Array.from(
- new Set((materials.data ?? []).map((m) => m.itemId))
+ new Set(
+ (materials.data ?? []).flatMap((m) => [
+ pickSupersessionItemId(m),
+ m.itemId
+ ])
+ )
);
const supersessionByItem = new Map<string, PickSupersession>();
if (materialItemIds.length > 0) {
@@ -3370,8 +3539,120 @@ export async function generatePickingList(
// boundary.
const asOfDate = datetime.today("UTC").toString();
+ const warehouseStockCache = new Map<string, boolean>();
+ const inWarehouseStock = async (itemId: string): Promise<boolean> => {
+ const cached = warehouseStockCache.get(itemId);
+ if (cached !== undefined) return cached;
+ const result = await hasWarehouseStock(client, {
+ itemId,
+ locationId: args.locationId,
+ companyId: args.companyId
+ });
+ warehouseStockCache.set(itemId, result);
+ return result;
+ };
+ const warehouseRemaining = new Map<string, number>();
+ const remainingWarehouseStock = async (itemId: string): Promise<number> => {
+ const cached = warehouseRemaining.get(itemId);
+ if (cached !== undefined) return cached;
+ const result = await getWarehouseOnHand(client, {
+ itemId,
+ locationId: args.locationId,
+ companyId: args.companyId
+ });
+ warehouseRemaining.set(itemId, result);
+ return result;
+ };
+
// Cache per-item on-hand-by-bin so a supersession redirect doesn't refetch.
const onHandCache = new Map<string, Map<string, number>>();
+ const claimsByItem = new Map<string, LinesideClaim[]>();
+ const claimsFor = async (
+ itemId: string,
+ storageUnitId: string
+ ): Promise<LinesideClaim[]> => {
+ const key = `${itemId}|${storageUnitId}`;
+ const cached = claimsByItem.get(key);
+ if (cached) return cached;
+ const { data, error } = await client
+ .from("pickingListLine")
+ .select(
+ "jobId, jobMaterialId, quantityPicked, quantityReturned, pickingList!inner(status), job!inner(status)"
+ )
+ .eq("companyId", args.companyId)
+ .eq("itemId", itemId)
+ .eq("toStorageUnitId", storageUnitId)
+ .neq("status", "Cancelled")
+ .neq("pickingList.status", "Cancelled")
+ .in("job.status", ["Planned", "Ready", "In Progress", "Paused"]);
+ if (error) throw new PickingReadError(error);
+ const claims = (data ?? []).map((line) => ({
+ jobId: line.jobId,
+ jobMaterialId: line.jobMaterialId,
+ staged:
+ Number(line.quantityPicked ?? 0) - Number(line.quantityReturned ?? 0)
+ }));
+ claimsByItem.set(key, claims);
+ return claims;
+ };
+ const consumedByItem = new Map<string, Map<string, number>>();
+ const consumedFor = async (
+ itemId: string,
+ storageUnitId: string
+ ): Promise<Map<string, number>> => {
+ const key = `${itemId}|${storageUnitId}`;
+ const cached = consumedByItem.get(key);
+ if (cached) return cached;
+ const { data, error } = await client
+ .from("itemLedger")
+ .select("documentId, quantity")
+ .eq("companyId", args.companyId)
+ .eq("locationId", args.locationId)
+ .eq("itemId", itemId)
+ .eq("storageUnitId", storageUnitId)
+ .eq("documentType", "Job Consumption");
+ if (error) throw new PickingReadError(error);
+ const byJob = new Map<string, number>();
+ for (const row of data ?? []) {
+ if (!row.documentId) continue;
+ byJob.set(
+ row.documentId,
+ (byJob.get(row.documentId) ?? 0) +
+ Math.max(0, -Number(row.quantity ?? 0))
+ );
+ }
+ consumedByItem.set(key, byJob);
+ return byJob;
+ };
+ const unclaimedRemaining = new Map<string, number>();
+ const linesideCreditFor = async (
+ itemId: string,
+ storageUnitId: string,
+ jobId: string,
+ jobMaterialId: string
+ ): Promise<{ own: number; unclaimed: number; key: string }> => {
+ const key = `${itemId}|${storageUnitId}`;
+ const credit = linesideCredit({
+ onHand: (await onHandFor(itemId)).get(storageUnitId) ?? 0,
+ claims: await claimsFor(itemId, storageUnitId),
+ consumedByJob: await consumedFor(itemId, storageUnitId),
+ jobId,
+ jobMaterialId
+ });
+ if (!unclaimedRemaining.has(key)) {
+ unclaimedRemaining.set(key, credit.unclaimed);
+ }
+ return {
+ own: credit.own,
+ unclaimed: unclaimedRemaining.get(key) ?? 0,
+ key
+ };
+ };
+ const chargeUnclaimed = (key: string, used: number, own: number) => {
+ const current = unclaimedRemaining.get(key) ?? 0;
+ unclaimedRemaining.set(key, Math.max(0, current - Math.max(0, used - own)));
+ };
+
const onHandFor = async (itemId: string): Promise<Map<string, number>> => {
const cached = onHandCache.get(itemId);
if (cached) return cached;
@@ -3422,115 +3703,180 @@ export async function generatePickingList(
companyId: string;
createdBy: string;
}> = [];
- for (const mat of materials.data ?? []) {
- const quantityToIssue = Number(mat.quantityToIssue ?? 0);
- if (quantityToIssue <= 0) continue;
-
- // Unassigned materials attach to the earliest selected operation of their
- // make method; its work center drives the lineside destination.
- const effectiveOperationId =
- mat.jobOperationId ??
- firstSelectedOpByMakeMethod.get(mat.jobMakeMethodId)?.id ??
- null;
-
- const opWorkCenterId = effectiveOperationId
- ? (workCenterByOperation.get(effectiveOperationId) ?? null)
- : null;
-
- // 5. Resolve the destination: the operation's work-center lineside shelf.
- const toStorageUnitId = await resolveLineside(opWorkCenterId);
-
- // 6. Honor supersession: decide which item this pick targets. Consume First
- // needs to know whether the predecessor is out of warehouse stock (and the
- // successor has stock), so probe those sources first — for that mode only.
- // The stock TEST uses total non-lineside on-hand (including the unassigned
- // bin) rather than a resolvable concrete source, so predecessor stock sitting
- // only in the unassigned bin still blocks a spurious successor redirect.
- const supersession = supersessionByItem.get(mat.itemId);
- let predecessorInStock = true;
- let successorInStock = true;
- if (supersession?.supersessionMode === "Consume First") {
- predecessorInStock = await hasWarehouseStock(client, {
+ try {
+ for (const mat of materials.data ?? []) {
+ const quantityToIssue = Number(mat.quantityToIssue ?? 0);
+ if (quantityToIssue <= 0) continue;
+
+ // Unassigned materials attach to the earliest selected operation of their
+ // make method; its work center drives the lineside destination.
+ const effectiveOperationId =
+ mat.jobOperationId ??
+ firstSelectedOpByMakeMethod.get(mat.jobMakeMethodId)?.id ??
+ null;
+
+ const opWorkCenterId = effectiveOperationId
+ ? (workCenterByOperation.get(effectiveOperationId) ?? null)
+ : null;
+
+ // 5. Resolve the destination: the operation's work-center lineside shelf.
+ const toStorageUnitId = await resolveLineside(opWorkCenterId);
+
+ // The stock TEST uses total non-lineside on-hand (including the unassigned
+ // bin) rather than a resolvable concrete source, so predecessor stock sitting
+ // only in the unassigned bin still blocks a spurious successor redirect.
+ const { rule: supersession, swappedFromItemId } = resolvePickRule(
+ mat,
+ supersessionByItem
+ );
+ const predecessorItemId = swappedFromItemId ?? mat.itemId;
+ const perAssemblyOld =
+ Number(mat.quantity ?? 0) *
+ (swappedFromItemId ? 1 / toPickFactor(mat.substitutionFactor) : 1);
+ let predecessorInStock = true;
+ let successorInStock = true;
+ let successorId: string | null = null;
+ if (
+ supersession?.supersessionMode === "Consume First" ||
+ supersession?.supersessionMode === "Prefer New"
+ ) {
+ successorId = swappedFromItemId
+ ? mat.itemId
+ : effectiveSuccessorId(supersession, asOfDate);
+ if (successorId) {
+ const available = await remainingWarehouseStock(predecessorItemId);
+ predecessorInStock =
+ supersession.supersessionMode === "Consume First"
+ ? consumableInWholeAssemblies(available, perAssemblyOld) > 0
+ : available > 0;
+ successorInStock = await inWarehouseStock(successorId);
+ }
+ }
+
+ const target = resolvePickTarget({
itemId: mat.itemId,
- locationId: args.locationId,
- companyId: args.companyId
+ substitutedFromItemId: swappedFromItemId,
+ substitutionFactor: mat.substitutionFactor,
+ supersession,
+ predecessorInStock,
+ successorInStock,
+ asOfDate
});
- const successorId = effectiveSuccessorId(supersession, asOfDate);
- if (successorId && !predecessorInStock) {
- successorInStock = await hasWarehouseStock(client, {
- itemId: successorId,
- locationId: args.locationId,
- companyId: args.companyId
+ // Nothing valid to pick for production (No Stock, or Stock Only without an
+ // effective successor) — drop it, matching get_picking_schedule.
+ if (target.kind === "skip") continue;
+
+ let targets: { itemId: string; quantity: number }[];
+ if (supersession?.supersessionMode === "Consume First" && successorId) {
+ const oldPerLine = swappedFromItemId
+ ? 1 / toPickFactor(mat.substitutionFactor)
+ : 1;
+ const newPerOld = swappedFromItemId
+ ? toPickFactor(mat.substitutionFactor)
+ : toPickFactor(supersession.conversionFactor);
+ const oldCredit = toStorageUnitId
+ ? await linesideCreditFor(
+ predecessorItemId,
+ toStorageUnitId,
+ mat.jobId,
+ mat.id
+ )
+ : null;
+ const newCredit = toStorageUnitId
+ ? await linesideCreditFor(
+ successorId,
+ toStorageUnitId,
+ mat.jobId,
+ mat.id
+ )
+ : null;
+ const warehouseOld = await remainingWarehouseStock(predecessorItemId);
+ const split = splitConsumeFirstPick({
+ needOld: quantityToIssue * oldPerLine,
+ perAssemblyOld,
+ newPerOld,
+ stagedOld: oldCredit ? oldCredit.own + oldCredit.unclaimed : 0,
+ stagedNew: newCredit ? newCredit.own + newCredit.unclaimed : 0,
+ warehouseOld,
+ successorInStock
});
+ warehouseRemaining.set(
+ predecessorItemId,
+ Math.max(0, warehouseOld - split.warehouseOldUsed)
+ );
+ if (oldCredit) {
+ chargeUnclaimed(oldCredit.key, split.stagedOldUsed, oldCredit.own);
+ }
+ if (newCredit) {
+ chargeUnclaimed(newCredit.key, split.stagedNewUsed, newCredit.own);
+ }
+ if (split.picks.length === 0) continue;
+ targets = split.picks.map((pick) => ({
+ itemId: pick.item === "predecessor" ? predecessorItemId : successorId,
+ quantity: pick.quantity
+ }));
+ } else {
+ const need = quantityToIssue * target.factor;
+ if (toStorageUnitId) {
+ const credit = await linesideCreditFor(
+ target.itemId,
+ toStorageUnitId,
+ mat.jobId,
+ mat.id
+ );
+ const credited = Math.min(need, credit.own + credit.unclaimed);
+ chargeUnclaimed(credit.key, credited, credit.own);
+ if (credited >= need) continue;
+ targets = [{ itemId: target.itemId, quantity: need - credited }];
+ } else {
+ targets = [{ itemId: target.itemId, quantity: need }];
+ }
}
- }
- const target = resolvePickTarget({
- itemId: mat.itemId,
- supersession,
- predecessorInStock,
- successorInStock,
- asOfDate
- });
- // Nothing valid to pick for production (No Stock, or Stock Only without an
- // effective successor) — drop it, matching get_picking_schedule.
- if (target.kind === "skip") continue;
-
- const pickItemId = target.itemId;
- const quantityToPick = quantityToIssue * target.factor;
-
- // On-hand of the resolved PICK item per bin at the location (reused for the
- // already-staged skip and warehouse-source resolution).
- const onHandByUnit = await onHandFor(pickItemId);
-
- // Skip when the op's lineside bin already stocks enough of the pick item to
- // cover the (converted) quantity — it's already staged here, so there's
- // nothing to pick. We test the ACTUAL on-hand at that bin, not merely
- // whether the jobMaterial's recorded shelf points there: a part can be
- // line-stocked at this work center while the jobMaterial still points at the
- // warehouse (or another line).
- if (
- toStorageUnitId &&
- (onHandByUnit.get(toStorageUnitId) ?? 0) >= quantityToPick
- ) {
- continue;
- }
+ for (const { itemId: pickItemId, quantity: quantityToPick } of targets) {
+ const onHandByUnit = await onHandFor(pickItemId);
+
+ let sourceStorageUnitId: string | null;
+ if (pickItemId === mat.itemId && mat.storageUnitId) {
+ const effectiveWc = await client.rpc("get_effective_work_center_id", {
+ p_storage_unit_id: mat.storageUnitId
+ });
+ const materialEffectiveWc =
+ (effectiveWc.data as string | null) ?? null;
+ sourceStorageUnitId = materialEffectiveWc
+ ? await resolveWarehouseSource(client, onHandByUnit)
+ : mat.storageUnitId;
+ } else {
+ sourceStorageUnitId = await resolveWarehouseSource(
+ client,
+ onHandByUnit
+ );
+ }
- // 7. Determine the source (warehouse) shelf. The jobMaterial's recorded
- // shelf is only meaningful when we're picking that same item (the
- // predecessor); for a substituted successor, resolve a warehouse source by
- // on-hand. Use the recorded shelf only when it's a warehouse (non-lineside)
- // shelf; otherwise resolve by on-hand — never rob another work center's
- // lineside. A null source = a shortage the kitter/planner must resolve.
- let sourceStorageUnitId: string | null;
- if (pickItemId === mat.itemId && mat.storageUnitId) {
- const effectiveWc = await client.rpc("get_effective_work_center_id", {
- p_storage_unit_id: mat.storageUnitId
- });
- const materialEffectiveWc = (effectiveWc.data as string | null) ?? null;
- sourceStorageUnitId = materialEffectiveWc
- ? await resolveWarehouseSource(client, onHandByUnit)
- : mat.storageUnitId;
- } else {
- sourceStorageUnitId = await resolveWarehouseSource(client, onHandByUnit);
+ lineRows.push({
+ pickingListId: plId,
+ jobId: mat.jobId,
+ jobMaterialId: mat.id,
+ jobOperationId: effectiveOperationId,
+ itemId: pickItemId,
+ quantityToPick,
+ storageUnitId: sourceStorageUnitId,
+ toStorageUnitId,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ });
+ }
+ // Tracked (serial/batch) lots are intentionally NOT pre-allocated here — the
+ // kitter selects them at pick time via the TrackedEntityPicker (smart-ordered,
+ // deduped), and the pick records pickingListLineTrackedEntity. Pre-allocating
+ // would show un-picked lots as if already picked.
}
-
- lineRows.push({
- pickingListId: plId,
- jobId: mat.jobId,
- jobMaterialId: mat.id,
- jobOperationId: effectiveOperationId,
- itemId: pickItemId,
- quantityToPick,
- storageUnitId: sourceStorageUnitId,
- toStorageUnitId,
- companyId: args.companyId,
- createdBy: args.createdBy
- });
- // Tracked (serial/batch) lots are intentionally NOT pre-allocated here — the
- // kitter selects them at pick time via the TrackedEntityPicker (smart-ordered,
- // deduped), and the pick records pickingListLineTrackedEntity. Pre-allocating
- // would show un-picked lots as if already picked.
+ } catch (err) {
+ if (err instanceof PickingReadError) {
+ await client.from("pickingList").delete().eq("id", plId);
+ return { data: null, error: err.postgrestError };
+ }
+ throw err;
}
// 7. If no lines to pick, delete the empty header and report.
diff --git a/apps/erp/app/modules/inventory/supersession-pick.test.ts b/apps/erp/app/modules/inventory/supersession-pick.test.ts
index 413e85c057..a02da65090 100644
--- a/apps/erp/app/modules/inventory/supersession-pick.test.ts
+++ b/apps/erp/app/modules/inventory/supersession-pick.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";
import {
effectiveSuccessorId,
type PickSupersession,
- resolvePickTarget
+ pickSupersessionItemId,
+ resolvePickRule,
+ resolvePickTarget,
+ splitConsumeFirstPick
} from "./supersession-pick";
const TODAY = "2026-07-30";
@@ -118,6 +121,31 @@ describe("resolvePickTarget", () => {
).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
});
+ it("falls back to the predecessor for Prefer New while the successor is out of stock", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ predecessorInStock: true,
+ successorInStock: false,
+ supersession: ss({ supersessionMode: "Prefer New" })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
+ });
+
+ it("keeps Prefer New on the successor when both are out (shortage on the planned part)", () => {
+ expect(
+ resolvePickTarget({
+ ...base,
+ predecessorInStock: false,
+ successorInStock: false,
+ supersession: ss({
+ supersessionMode: "Prefer New",
+ conversionFactor: 2
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 2 });
+ });
+
it("keeps Consume First on the predecessor while it has stock", () => {
expect(
resolvePickTarget({
@@ -166,4 +194,251 @@ describe("resolvePickTarget", () => {
})
).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
});
+
+ describe("swapped at job creation", () => {
+ const swapped = {
+ itemId: "SUCC",
+ substitutedFromItemId: "OLD",
+ substitutionFactor: 2,
+ asOfDate: TODAY
+ };
+
+ it("Consume First pulls the predecessor while it has stock, in predecessor units", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: true,
+ successorInStock: true,
+ supersession: ss({ supersessionMode: "Consume First" })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 0.5 });
+ });
+
+ it("Consume First moves to the successor once the predecessor is out", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: false,
+ successorInStock: false,
+ supersession: ss({ supersessionMode: "Consume First" })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 1 });
+ });
+
+ it("Consume First ignores effectivity — the swap already settled it", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: true,
+ successorInStock: true,
+ supersession: ss({
+ supersessionMode: "Consume First",
+ successorEffectivityDate: "2026-12-31"
+ })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 0.5 });
+ });
+
+ it("Prefer New stays on the successor while it has stock", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: true,
+ successorInStock: true,
+ supersession: ss({ supersessionMode: "Prefer New" })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 1 });
+ });
+
+ it("Prefer New falls back to the predecessor only while the successor is out", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: true,
+ successorInStock: false,
+ supersession: ss({ supersessionMode: "Prefer New" })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 0.5 });
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: false,
+ successorInStock: false,
+ supersession: ss({ supersessionMode: "Prefer New" })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 1 });
+ });
+
+ it("Stock Only never pulls the spares-only predecessor", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: true,
+ successorInStock: false,
+ supersession: ss({ supersessionMode: "Stock Only" })
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 1 });
+ });
+
+ it("picks the successor when the rule was removed after the swap", () => {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ predecessorInStock: true,
+ successorInStock: true,
+ supersession: undefined
+ })
+ ).toEqual({ kind: "pick", itemId: "SUCC", factor: 1 });
+ });
+
+ it("a null or zero substitution factor is treated as 1", () => {
+ for (const substitutionFactor of [null, 0, "x"]) {
+ expect(
+ resolvePickTarget({
+ ...swapped,
+ substitutionFactor,
+ predecessorInStock: true,
+ successorInStock: true,
+ supersession: ss({ supersessionMode: "Consume First" })
+ })
+ ).toEqual({ kind: "pick", itemId: "OLD", factor: 1 });
+ }
+ });
+ });
+});
+
+describe("pickSupersessionItemId", () => {
+ it("is the predecessor for a swapped row, else the material's own item", () => {
+ expect(
+ pickSupersessionItemId({ itemId: "SUCC", substitutedFromItemId: "OLD" })
+ ).toBe("OLD");
+ expect(
+ pickSupersessionItemId({ itemId: "OLD", substitutedFromItemId: null })
+ ).toBe("OLD");
+ expect(pickSupersessionItemId({ itemId: "OLD" })).toBe("OLD");
+ });
+});
+
+describe("resolvePickRule", () => {
+ const rules = new Map<string, PickSupersession>([
+ ["OLD", ss({ successorItemId: "NEW", conversionFactor: 2 })],
+ ["NEW", ss({ successorItemId: "NEWER", conversionFactor: 3 })]
+ ]);
+
+ it("uses the predecessor's rule for a row swapped to the successor at creation", () => {
+ expect(
+ resolvePickRule({ itemId: "NEW", substitutedFromItemId: "OLD" }, rules)
+ ).toEqual({ rule: rules.get("OLD"), swappedFromItemId: "OLD" });
+ });
+
+ it("uses the row's own rule for a line pulled back onto the predecessor, even when the successor has a rule of its own", () => {
+ expect(
+ resolvePickRule({ itemId: "OLD", substitutedFromItemId: "NEW" }, rules)
+ ).toEqual({ rule: rules.get("OLD"), swappedFromItemId: null });
+ });
+
+ it("falls back to the row's own rule when the substituted-from item has none", () => {
+ const only = new Map([["OLD", rules.get("OLD")!]]);
+ expect(
+ resolvePickRule({ itemId: "OLD", substitutedFromItemId: "NEW" }, only)
+ ).toEqual({ rule: only.get("OLD"), swappedFromItemId: null });
+ });
+
+ it("is the row's own rule, unswapped, without provenance", () => {
+ expect(resolvePickRule({ itemId: "OLD" }, rules)).toEqual({
+ rule: rules.get("OLD"),
+ swappedFromItemId: null
+ });
+ expect(resolvePickRule({ itemId: "X" }, rules)).toEqual({
+ rule: undefined,
+ swappedFromItemId: null
+ });
+ });
+});
+
+describe("splitConsumeFirstPick", () => {
+ const base = {
+ needOld: 4,
+ perAssemblyOld: 2,
+ newPerOld: 1,
+ stagedOld: 0,
+ stagedNew: 0,
+ warehouseOld: 0,
+ successorInStock: false
+ };
+ const split = (overrides: Partial<typeof base>) =>
+ splitConsumeFirstPick({ ...base, ...overrides });
+
+ it("picks nothing when one assembly of each part is already at the lineside bin", () => {
+ expect(split({ stagedOld: 2, stagedNew: 2, warehouseOld: 1 })).toEqual({
+ picks: [],
+ warehouseOldUsed: 0,
+ stagedOldUsed: 2,
+ stagedNewUsed: 2
+ });
+ });
+
+ it("credits staged material only in whole assemblies", () => {
+ expect(
+ split({
+ stagedOld: 1,
+ stagedNew: 1,
+ warehouseOld: 0,
+ successorInStock: true
+ })
+ ).toEqual({
+ picks: [{ item: "successor", quantity: 4 }],
+ warehouseOldUsed: 0,
+ stagedOldUsed: 0,
+ stagedNewUsed: 0
+ });
+ });
+
+ it("splits the remainder: predecessor for the assemblies the warehouse covers, successor for the rest", () => {
+ expect(split({ warehouseOld: 3 })).toEqual({
+ picks: [
+ { item: "predecessor", quantity: 2 },
+ { item: "successor", quantity: 2 }
+ ],
+ warehouseOldUsed: 2,
+ stagedOldUsed: 0,
+ stagedNewUsed: 0
+ });
+ });
+
+ it("stays on the predecessor as a shortage when neither part is in the warehouse", () => {
+ expect(split({ stagedOld: 2, warehouseOld: 1 })).toEqual({
+ picks: [{ item: "predecessor", quantity: 2 }],
+ warehouseOldUsed: 0,
+ stagedOldUsed: 2,
+ stagedNewUsed: 0
+ });
+ });
+
+ it("converts the successor's quantities by the factor in both directions", () => {
+ expect(split({ newPerOld: 2, stagedNew: 4, warehouseOld: 2 })).toEqual({
+ picks: [{ item: "predecessor", quantity: 2 }],
+ warehouseOldUsed: 2,
+ stagedOldUsed: 0,
+ stagedNewUsed: 4
+ });
+ expect(split({ newPerOld: 2, warehouseOld: 2 })).toEqual({
+ picks: [
+ { item: "predecessor", quantity: 2 },
+ { item: "successor", quantity: 4 }
+ ],
+ warehouseOldUsed: 2,
+ stagedOldUsed: 0,
+ stagedNewUsed: 0
+ });
+ });
+
+ it("never credits more than the requirement", () => {
+ expect(split({ stagedOld: 10 })).toEqual({
+ picks: [],
+ warehouseOldUsed: 0,
+ stagedOldUsed: 4,
+ stagedNewUsed: 0
+ });
+ });
});
diff --git a/apps/erp/app/modules/inventory/supersession-pick.ts b/apps/erp/app/modules/inventory/supersession-pick.ts
index a1346f90ac..1774269897 100644
--- a/apps/erp/app/modules/inventory/supersession-pick.ts
+++ b/apps/erp/app/modules/inventory/supersession-pick.ts
@@ -1,19 +1,16 @@
+import type { Database } from "@carbon/database";
+import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
// Picking-side supersession resolution: given a job material's item and its
// supersession config, decide which item a pick should actually target.
//
// This is intentionally SEPARATE from the MRP / job-creation redirect map
-// (packages/database/supabase/functions/lib/supersession-pick.ts), which only
-// redirects `Consume First` / `Prefer New`. Picking has different rules: a
-// `Stock Only` predecessor is reserved for service and must NOT be picked for
-// production, so its effective successor is used instead; a `No Stock`
-// predecessor is obsolete and is skipped entirely. The SQL in
// `get_picking_schedule` mirrors this exactly.
//
// Dates are ISO "YYYY-MM-DD" strings; lexicographic comparison is exact for that
// format (same convention as the shared redirect map).
export type PickSupersession = {
- supersessionMode: string;
+ supersessionMode: Database["public"]["Enums"]["supersessionMode"];
successorItemId: string | null;
successorEffectivityDate: string | null;
conversionFactor: number | string | null;
@@ -38,11 +35,32 @@ export function effectiveSuccessorId(
return ss.successorItemId;
}
-function toFactor(value: number | string | null): number {
+function toFactor(value: number | string | null | undefined): number {
const n = Number(value ?? 1);
return Number.isFinite(n) && n > 0 ? n : 1;
}
+export function pickSupersessionItemId(material: {
+ itemId: string;
+ substitutedFromItemId?: string | null;
+}): string {
+ return material.substitutedFromItemId ?? material.itemId;
+}
+
+export function resolvePickRule<R extends PickSupersession>(
+ material: { itemId: string; substitutedFromItemId?: string | null },
+ ruleByItem: Map<string, R>
+): { rule: R | undefined; swappedFromItemId: string | null } {
+ const ownRule = ruleByItem.get(material.itemId);
+ const from = material.substitutedFromItemId ?? null;
+ if (from && ownRule?.successorItemId === from) {
+ return { rule: ownRule, swappedFromItemId: null };
+ }
+ const swappedRule = from ? ruleByItem.get(from) : undefined;
+ if (swappedRule) return { rule: swappedRule, swappedFromItemId: from };
+ return { rule: ownRule, swappedFromItemId: null };
+}
+
/**
* Resolve the item a pick should target for a job material.
*
@@ -51,17 +69,14 @@ function toFactor(value: number | string | null): number {
* - `Stock Only` → pick the effective successor (never the spares-only
* predecessor); skip when there is no effective successor.
* - `Prefer New` → pick the effective successor; fall back to the predecessor
- * until the successor is effective.
* - `Consume First` → pick the predecessor; redirect to the successor ONLY when
* the predecessor has no warehouse stock and an effective successor with stock
- * exists (never leaves predecessor stock unused, and satisfies
- * "predecessor out of stock → pick successor").
*
- * When redirecting to a successor, `factor` is the conversion factor
- * (1 old = N new); otherwise 1.
*/
export function resolvePickTarget(args: {
itemId: string;
+ substitutedFromItemId?: string | null;
+ substitutionFactor?: number | string | null;
supersession: PickSupersession | undefined;
/** predecessor has a resolvable warehouse source (non-lineside on-hand). */
predecessorInStock: boolean;
@@ -69,9 +84,28 @@ export function resolvePickTarget(args: {
successorInStock: boolean;
asOfDate: string;
}): PickTarget {
- const { itemId, supersession: ss } = args;
+ const { itemId, substitutedFromItemId, supersession: ss } = args;
if (!ss) return { kind: "pick", itemId, factor: 1 };
+ if (substitutedFromItemId) {
+ const predecessor = {
+ kind: "pick" as const,
+ itemId: substitutedFromItemId,
+ factor: 1 / toFactor(args.substitutionFactor)
+ };
+ const successor = { kind: "pick" as const, itemId, factor: 1 };
+ switch (ss.supersessionMode) {
+ case "Consume First":
+ return args.predecessorInStock ? predecessor : successor;
+ case "Prefer New":
+ return !args.successorInStock && args.predecessorInStock
+ ? predecessor
+ : successor;
+ default:
+ return successor;
+ }
+ }
+
const successor = effectiveSuccessorId(ss, args.asOfDate);
const factor = toFactor(ss.conversionFactor);
@@ -83,9 +117,10 @@ export function resolvePickTarget(args: {
? { kind: "pick", itemId: successor, factor }
: { kind: "skip" };
case "Prefer New":
- return successor
- ? { kind: "pick", itemId: successor, factor }
- : { kind: "pick", itemId, factor: 1 };
+ if (successor && (args.successorInStock || !args.predecessorInStock)) {
+ return { kind: "pick", itemId: successor, factor };
+ }
+ return { kind: "pick", itemId, factor: 1 };
case "Consume First":
if (successor && !args.predecessorInStock && args.successorInStock) {
return { kind: "pick", itemId: successor, factor };
@@ -95,3 +130,65 @@ export function resolvePickTarget(args: {
return { kind: "pick", itemId, factor: 1 };
}
}
+
+export type ConsumeFirstPick = {
+ item: "predecessor" | "successor";
+ quantity: number;
+};
+
+export function splitConsumeFirstPick(args: {
+ needOld: number;
+ perAssemblyOld: number;
+ newPerOld: number;
+ stagedOld: number;
+ stagedNew: number;
+ warehouseOld: number;
+ successorInStock: boolean;
+}): {
+ picks: ConsumeFirstPick[];
+ warehouseOldUsed: number;
+ stagedOldUsed: number;
+ stagedNewUsed: number;
+} {
+ const {
+ needOld,
+ perAssemblyOld,
+ stagedOld,
+ stagedNew,
+ warehouseOld,
+ successorInStock
+ } = args;
+ const newPerOld = args.newPerOld > 0 ? args.newPerOld : 1;
+ const perAssemblyNew = perAssemblyOld * newPerOld;
+ const stagedOldUsed = Math.min(
+ needOld,
+ consumableInWholeAssemblies(stagedOld, perAssemblyOld)
+ );
+ const stagedNewUsed = Math.min(
+ (needOld - stagedOldUsed) * newPerOld,
+ consumableInWholeAssemblies(stagedNew, perAssemblyNew)
+ );
+ const remaining = Math.max(
+ 0,
+ needOld - stagedOldUsed - stagedNewUsed / newPerOld
+ );
+ if (remaining <= 0) {
+ return { picks: [], warehouseOldUsed: 0, stagedOldUsed, stagedNewUsed };
+ }
+
+ const usable = Math.min(
+ remaining,
+ consumableInWholeAssemblies(warehouseOld, perAssemblyOld)
+ );
+ const picks: ConsumeFirstPick[] = [];
+ if (usable > 0) picks.push({ item: "predecessor", quantity: usable });
+ const rest = remaining - usable;
+ if (rest > 0) {
+ picks.push(
+ usable > 0 || successorInStock
+ ? { item: "successor", quantity: rest * newPerOld }
+ : { item: "predecessor", quantity: rest }
+ );
+ }
+ return { picks, warehouseOldUsed: usable, stagedOldUsed, stagedNewUsed };
+}
diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
index 764972cca2..482c582e8d 100644
--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListLines.tsx
@@ -51,6 +51,38 @@ import type {
} from "../../inventory.service";
import { ShortPickModal } from "./ShortPickModal";
+type PickLineSourceMaterial = {
+ itemId?: string | null;
+ quantity?: number | string | null;
+ substitutionFactor?: number | string | null;
+ item?: {
+ readableId?: string | null;
+ itemSupersession?: { conversionFactor?: number | string | null } | null;
+ } | null;
+};
+
+export function assembliesCovered(
+ pickItemId: string,
+ quantityToPick: number,
+ material: PickLineSourceMaterial | null | undefined
+): number | null {
+ const perAssembly = Number(material?.quantity ?? 0);
+ if (!material?.itemId || !(perAssembly > 0)) return null;
+ const substitutionFactor = Number(material.substitutionFactor ?? 0);
+ const conversionFactor = Number(
+ material.item?.itemSupersession?.conversionFactor ?? 0
+ );
+ const factor =
+ substitutionFactor > 0
+ ? 1 / substitutionFactor
+ : conversionFactor > 0
+ ? conversionFactor
+ : null;
+ if (factor === null || pickItemId === material.itemId) return null;
+ const assemblies = quantityToPick / (perAssembly * factor);
+ return Number.isInteger(assemblies) ? assemblies : null;
+}
+
type PickingListData = NonNullable<
Awaited<ReturnType<typeof getPickingList>>["data"]
>;
@@ -267,10 +299,7 @@ function PickingListLineItem({
// item (an item-supersession redirect at generation time). Show the original.
const sourceMaterial = (
line as {
- jobMaterial?: {
- itemId?: string | null;
- item?: { readableId?: string | null } | null;
- } | null;
+ jobMaterial?: PickLineSourceMaterial | null;
}
).jobMaterial;
const substitutedFrom =
@@ -281,6 +310,9 @@ function PickingListLineItem({
sourceMaterial.itemId)
: null;
const quantityToPick = Number(line.quantityToPick ?? 0);
+ const assemblies = substitutedFrom
+ ? assembliesCovered(line.itemId, quantityToPick, sourceMaterial)
+ : null;
const quantityPicked = Number(line.quantityPicked ?? 0);
const quantityReturned = Number(
(line as { quantityReturned?: number | null }).quantityReturned ?? 0
@@ -352,7 +384,17 @@ function PickingListLineItem({
</p>
{substitutedFrom && (
<p className="truncate text-sm text-blue-700 dark:text-blue-300 sm:text-xs">
- ↩ <Trans>substituted from</Trans> {substitutedFrom}
+ ↩{" "}
+ {assemblies !== null ? (
+ <Trans>
+ picking in place of {substitutedFrom}, the item on the job,
+ for {assemblies} assemblies
+ </Trans>
+ ) : (
+ <Trans>
+ picking in place of {substitutedFrom}, the item on the job
+ </Trans>
+ )}
</p>
)}
{isTracked && !isPicked && (
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index 3538c2a5c9..abbf843d21 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -692,7 +692,8 @@ export const supersessionModeMeta: Record<
},
"Prefer New": {
color: "blue",
- description: "Default to the successor; old part as fallback only"
+ description:
+ "Plan and build with the successor; picking falls back to the old part only while the successor is out of stock"
},
"Stock Only": {
color: "orange",
@@ -719,7 +720,10 @@ export const itemSupersessionValidator = z
minimumReserveQuantity: zfd.numeric(z.number().min(0).optional())
})
.refine(
- (data) => (data.supersessionMode ? !!data.discontinuationDate : true),
+ (data) =>
+ data.supersessionMode && data.supersessionMode !== "Consume First"
+ ? !!data.discontinuationDate
+ : true,
{
message: "Discontinuation date is required",
path: ["discontinuationDate"]
@@ -751,6 +755,39 @@ export const itemSupersessionValidator = z
}
);
+export const predecessorSupersessionValidator = z
+ .object({
+ predecessorItemId: z.string().min(1, { message: "Part is required" }),
+ supersessionMode: z.enum(supersessionModes),
+ discontinuationDate: zfd.text(z.string().optional()),
+ successorEffectivityDate: zfd.text(z.string().optional()),
+ conversionFactor: zfd.numeric(z.number().positive().optional())
+ })
+ .refine((data) => data.supersessionMode !== "No Stock", {
+ message: "No Stock has no successor; set it on the part itself",
+ path: ["supersessionMode"]
+ })
+ .refine(
+ (data) =>
+ data.supersessionMode !== "Consume First"
+ ? !!data.discontinuationDate
+ : true,
+ {
+ message: "Discontinuation date is required",
+ path: ["discontinuationDate"]
+ }
+ )
+ .refine(
+ (data) =>
+ data.successorEffectivityDate && data.discontinuationDate
+ ? data.successorEffectivityDate >= data.discontinuationDate
+ : true,
+ {
+ message:
+ "Successor effectivity date must be on or after the discontinuation date",
+ path: ["successorEffectivityDate"]
+ }
+ );
export const itemPurchasingValidator = z.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
preferredSupplierId: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index ca95ade530..c4a78da0f8 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -914,6 +914,21 @@ export async function getItemSupersession(
.maybeSingle();
}
+export async function getItemSupersessionsForItems(
+ client: SupabaseClient<Database>,
+ itemIds: string[],
+ companyId: string
+) {
+ if (itemIds.length === 0) return { data: [], error: null };
+ return client
+ .from("itemSupersession")
+ .select(
+ "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor, successor:item!itemSupersession_successorItemId_fkey(readableIdWithRevision)"
+ )
+ .in("itemId", itemIds)
+ .eq("companyId", companyId);
+}
+
// Parts that point to this item as their successor (the "Supersedes" back-ref).
export async function getItemSupersededBy(
client: SupabaseClient<Database>,
@@ -1775,7 +1790,7 @@ export async function getOpenJobMaterials(
return client
.from("openJobMaterialLines")
.select(
- "id, parentMaterialId, jobMakeMethodId, jobId, quantity:quantityToIssue, documentReadableId:jobReadableId, documentId:jobId, dueDate"
+ "id, parentMaterialId, jobMakeMethodId, jobId, quantity:quantityToIssue, quantityPerParent, documentReadableId:jobReadableId, documentId:jobId, dueDate"
)
.eq("itemId", itemId)
.eq("locationId", locationId)
@@ -3793,6 +3808,57 @@ export async function upsertItemPurchasing(
.eq("itemId", update.itemId);
}
+export const SUPERSESSION_CYCLE_CODE = "SUPERSESSION_CYCLE";
+
+const SUPERSESSION_CHAIN_LIMIT = 10;
+
+async function findSupersessionCycle(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ successorItemId: string,
+ companyId: string
+): Promise<
+ | { kind: "ok" }
+ | { kind: "cycle"; path: string[] }
+ | { kind: "tooLong" }
+ | { kind: "error"; error: PostgrestError }
+> {
+ const path = [itemId, successorItemId];
+ const visited = new Set(path);
+ let currentId = successorItemId;
+ let closed = false;
+ for (let hop = 0; hop < SUPERSESSION_CHAIN_LIMIT; hop++) {
+ const link = await client
+ .from("itemSupersession")
+ .select("successorItemId")
+ .eq("itemId", currentId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (link.error) return { kind: "error", error: link.error };
+ const next = link.data?.successorItemId;
+ if (!next) return { kind: "ok" };
+ path.push(next);
+ if (visited.has(next)) {
+ closed = true;
+ break;
+ }
+ visited.add(next);
+ currentId = next;
+ }
+ if (!closed) return { kind: "tooLong" };
+
+ const items = await client
+ .from("item")
+ .select("id, readableIdWithRevision")
+ .in("id", Array.from(new Set(path)))
+ .eq("companyId", companyId);
+ if (items.error) return { kind: "error", error: items.error };
+ const readable = new Map(
+ (items.data ?? []).map((i) => [i.id, i.readableIdWithRevision ?? i.id])
+ );
+ return { kind: "cycle", path: path.map((id) => readable.get(id) ?? id) };
+}
+
export async function upsertItemSupersession(
client: SupabaseClient<Database>,
itemSupersession: z.infer<typeof itemSupersessionValidator> & {
@@ -3837,6 +3903,35 @@ export async function upsertItemSupersession(
}
const isNoStock = supersessionMode === "No Stock";
+
+ if (!isNoStock && successorItemId) {
+ const check = await findSupersessionCycle(
+ client,
+ itemId,
+ successorItemId,
+ companyId
+ );
+ if (check.kind === "error") return { data: null, error: check.error };
+ if (check.kind === "tooLong") {
+ return {
+ data: null,
+ error: {
+ code: SUPERSESSION_CYCLE_CODE,
+ message: `Supersession chains longer than ${SUPERSESSION_CHAIN_LIMIT} hops are not allowed`
+ }
+ };
+ }
+ if (check.kind === "cycle") {
+ return {
+ data: null,
+ error: {
+ code: SUPERSESSION_CYCLE_CODE,
+ message: `This would create a supersession loop: ${check.path.join(" → ")}`
+ }
+ };
+ }
+ }
+
const row = {
supersessionMode,
// No Stock has no successor (nothing takes over the demand).
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index 171ef8b9ea..4c0642e8de 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -1195,6 +1195,7 @@ interface PlanningItem {
jobId?: string | null;
jobMakeMethodId?: string | null;
existingOrderReadableId?: string | null;
+ redirectedFromReadableId?: string | null;
forecastMethod?: string | null;
forecastSources?: DemandForecastSourceRow[];
// Planned-row metadata (only set on rows with sourceType === "Planned").
@@ -1297,6 +1298,11 @@ function SupplyDemandPlanningItem({
{item.documentReadableId}
</Hyperlink>
)}
+ {item.redirectedFromReadableId && (
+ <span className="text-xs text-blue-700 dark:text-blue-300">
+ <Trans>via</Trans> {item.redirectedFromReadableId}
+ </span>
+ )}
<span className="text-xs text-muted-foreground">
{item.dueDate ? (
<DateTime value={item.dueDate} variant="date" />
diff --git a/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx
index 7f6d32551a..31efacafeb 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemSupersessionForm.tsx
@@ -3,17 +3,29 @@ import {
Alert,
AlertDescription,
AlertTitle,
+ Button,
Card,
+ CardAction,
CardContent,
CardFooter,
CardHeader,
CardTitle,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
Status,
+ useDisclosure,
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useState } from "react";
-import { LuTriangleAlert } from "react-icons/lu";
+import { useRef, useState } from "react";
+import { LuPlus, LuTriangleAlert } from "react-icons/lu";
+import { Link, useActionData } from "react-router";
import type { z } from "zod";
import {
DatePicker,
@@ -24,9 +36,11 @@ import {
Submit
} from "~/components/Form";
import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
import type { SupersessionMode } from "../../items.models";
import {
itemSupersessionValidator,
+ predecessorSupersessionValidator,
supersessionModeMeta,
supersessionModes
} from "../../items.models";
@@ -48,15 +62,32 @@ type SupersessionChainLink = {
successor: { readableIdWithRevision: string | null } | null;
};
+type SupersededByLink = {
+ itemId: string;
+ supersessionMode: SupersessionMode;
+ successorEffectivityDate: string | null;
+ predecessor: { readableIdWithRevision: string | null; name: string } | null;
+};
+
+type ItemType = "Part" | "Material" | "Tool" | "Consumable";
+
type ItemSupersessionFormProps = {
initialValues: z.infer<typeof itemSupersessionValidator> & {
minimumReserveQuantity: number;
};
- type: "Part" | "Material" | "Tool" | "Consumable";
+ type: ItemType;
locationId: string;
itemReadableId: string;
quantityOnHand: number;
chain: SupersessionChainLink[];
+ supersededBy: SupersededByLink[];
+};
+
+const planningPath: Record<ItemType, (id: string) => string> = {
+ Part: path.to.partPlanning,
+ Material: path.to.materialPlanning,
+ Tool: path.to.toolPlanning,
+ Consumable: path.to.consumablePlanning
};
const ItemSupersessionForm = ({
@@ -65,14 +96,17 @@ const ItemSupersessionForm = ({
locationId,
itemReadableId,
quantityOnHand,
- chain
+ chain,
+ supersededBy
}: ItemSupersessionFormProps) => {
const permissions = usePermissions();
const { t } = useLingui();
+ const canUpdate = permissions.can("update", "parts");
const [mode, setMode] = useState<SupersessionMode | "">(
initialValues.supersessionMode ?? ""
);
+ const addPredecessorModal = useDisclosure();
const hasSuccessor = mode !== "" && mode !== "No Stock";
const hasReserve = mode === "Stock Only";
@@ -91,6 +125,11 @@ const ItemSupersessionForm = ({
.join(" → ")
: null;
+ const discontinuationDateHelp =
+ mode === "Consume First"
+ ? t`Optional. Stops new purchase suggestions after this date.`
+ : t`Stops new purchase suggestions after this date.`;
+
return (
<Card>
<ValidatedForm
@@ -98,16 +137,78 @@ const ItemSupersessionForm = ({
validator={itemSupersessionValidator}
defaultValues={initialValues}
>
- <CardHeader>
- <CardTitle>
- <Trans>Supersession</Trans>
- </CardTitle>
- </CardHeader>
+ <HStack className="justify-between">
+ <CardHeader>
+ <CardTitle>
+ <Trans>Supersession</Trans>
+ </CardTitle>
+ </CardHeader>
+ <CardAction>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="secondary"
+ leftIcon={<LuPlus />}
+ isDisabled={!canUpdate}
+ onClick={addPredecessorModal.onOpen}
+ >
+ <Trans>Add Predecessor</Trans>
+ </Button>
+ </div>
+ </CardAction>
+ </HStack>
<CardContent>
<Hidden name="intent" value="supersession" />
<Hidden name="itemId" />
<Hidden name="locationId" value={locationId} />
<VStack spacing={4}>
+ {supersededBy.length > 0 && (
+ <VStack spacing={1} className="w-full">
+ <p className="text-sm font-medium">
+ <Trans>Supersedes</Trans>
+ </p>
+ <p className="text-xs text-muted-foreground">
+ <Trans>
+ These parts are being replaced by this one. Each rule is set
+ on the old part; open it to change the rule.
+ </Trans>
+ </p>
+ <ul className="w-full divide-y divide-border rounded-md border">
+ {supersededBy.map((link) => (
+ <li
+ key={link.itemId}
+ className="flex items-center justify-between gap-4 px-3 py-2"
+ >
+ <HStack spacing={2} className="min-w-0">
+ <Link
+ to={planningPath[type](link.itemId)}
+ className="truncate font-mono text-sm hover:underline"
+ >
+ {link.predecessor?.readableIdWithRevision ??
+ link.itemId}
+ </Link>
+ <span className="truncate text-sm text-muted-foreground">
+ {link.predecessor?.name}
+ </span>
+ </HStack>
+ <HStack spacing={2} className="shrink-0">
+ {link.successorEffectivityDate && (
+ <span className="text-xs text-muted-foreground">
+ <Trans>from</Trans> {link.successorEffectivityDate}
+ </span>
+ )}
+ <Status
+ color={
+ supersessionModeMeta[link.supersessionMode].color
+ }
+ >
+ {link.supersessionMode}
+ </Status>
+ </HStack>
+ </li>
+ ))}
+ </ul>
+ </VStack>
+ )}
{hasChain && chainLabel && (
<Alert variant="destructive">
<LuTriangleAlert className="h-4 w-4 !top-3.5" />
@@ -161,8 +262,8 @@ const ItemSupersessionForm = ({
<DatePicker
name="discontinuationDate"
label={t`Discontinuation Date`}
- isRequired
- helperText={t`Stop raising purchase orders after this date`}
+ isRequired={mode !== "Consume First"}
+ helperText={discontinuationDateHelp}
/>
)}
{hasReserve && (
@@ -199,13 +300,137 @@ const ItemSupersessionForm = ({
</VStack>
</CardContent>
<CardFooter>
- <Submit isDisabled={!permissions.can("update", "parts")}>
+ <Submit isDisabled={!canUpdate}>
<Trans>Save</Trans>
</Submit>
</CardFooter>
</ValidatedForm>
+ {addPredecessorModal.isOpen && (
+ <AddPredecessorModal
+ itemId={initialValues.itemId}
+ itemReadableId={itemReadableId}
+ type={type}
+ onClose={addPredecessorModal.onClose}
+ />
+ )}
</Card>
);
};
+function AddPredecessorModal({
+ itemId,
+ itemReadableId,
+ type,
+ onClose
+}: {
+ itemId: string;
+ itemReadableId: string;
+ type: ItemType;
+ onClose: () => void;
+}) {
+ const { t } = useLingui();
+ const [mode, setMode] = useState<SupersessionMode>("Consume First");
+ const actionData = useActionData<{ fieldErrors?: unknown } | undefined>();
+ const actionDataRef = useRef(actionData);
+ actionDataRef.current = actionData;
+
+ const discontinuationDateHelp =
+ mode === "Consume First"
+ ? t`Optional. Stops new purchase suggestions for the old part after this date.`
+ : t`Stops new purchase suggestions for the old part after this date.`;
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ validator={predecessorSupersessionValidator}
+ defaultValues={{
+ supersessionMode: "Consume First",
+ conversionFactor: 1
+ }}
+ onAfterSubmit={() => {
+ if (!actionDataRef.current?.fieldErrors) onClose();
+ }}
+ >
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Add Predecessor</Trans>
+ </ModalTitle>
+ <ModalDescription>
+ <Trans>
+ Choose a part that {itemReadableId} replaces. The rule is saved
+ on that part with {itemReadableId} as its successor.
+ </Trans>
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <Hidden name="intent" value="supersession-predecessor" />
+ <VStack spacing={4}>
+ <Item
+ name="predecessorItemId"
+ label={t`Part Being Replaced`}
+ type={type}
+ isOptional={false}
+ blacklist={[itemId]}
+ />
+ <SelectForm
+ name="supersessionMode"
+ label={t`Supersession Mode`}
+ termId="supersession-mode"
+ helperText={supersessionModeMeta[mode].description}
+ options={supersessionModes
+ .filter((value) => value !== "No Stock")
+ .map((value) => ({
+ label: (
+ <Status color={supersessionModeMeta[value].color}>
+ {value}
+ </Status>
+ ),
+ value
+ }))}
+ onChange={(selected) => {
+ if (selected?.value) {
+ setMode(selected.value as SupersessionMode);
+ }
+ }}
+ />
+ <DatePicker
+ name="discontinuationDate"
+ label={t`Discontinuation Date`}
+ isRequired={mode !== "Consume First"}
+ helperText={discontinuationDateHelp}
+ />
+ <DatePicker
+ name="successorEffectivityDate"
+ label={t`Successor Effectivity Date`}
+ helperText={t`When MRP starts using this part for the old part's demand`}
+ />
+ <NumberForm
+ name="conversionFactor"
+ label={t`Conversion Factor`}
+ minValue={0}
+ helperText={t`How many of this part replace one old part`}
+ />
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Submit>
+ <Trans>Add</Trans>
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
+
export default ItemSupersessionForm;
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index d6e3561940..e0c56b50ee 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
import type { JobSource } from "@carbon/lib/telemetry";
import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";
@@ -1341,7 +1342,8 @@ export async function getJobMaterialShortfallByItem(
jobId: string,
companyId: string,
locationId: string,
- materials: JobItemAvailability[]
+ materials: JobItemAvailability[],
+ asOfDate?: string
): Promise<Record<string, ItemShortfall>> {
// Two pools per item, kept separate so allocation can hand out already-received
// on-hand stock BEFORE incoming supply. quantityOnPurchaseOrder /
@@ -1367,13 +1369,58 @@ export async function getJobMaterialShortfallByItem(
const itemIds = Array.from(onHandByItem.keys());
if (itemIds.length === 0) return {};
+ const successorByItem = new Map<string, { itemId: string; factor: number }>();
+ const rules = await client
+ .from("itemSupersession")
+ .select(
+ "itemId, successorItemId, successorEffectivityDate, conversionFactor"
+ )
+ .in("itemId", itemIds)
+ .eq("companyId", companyId)
+ .eq("supersessionMode", "Consume First");
+ for (const rule of rules.data ?? []) {
+ if (!rule.successorItemId) continue;
+ if (
+ asOfDate &&
+ rule.successorEffectivityDate &&
+ rule.successorEffectivityDate > asOfDate
+ ) {
+ continue;
+ }
+ successorByItem.set(rule.itemId, {
+ itemId: rule.successorItemId,
+ factor: Number(rule.conversionFactor ?? 1) || 1
+ });
+ }
+ const successorIds = Array.from(
+ new Set(
+ Array.from(successorByItem.values())
+ .map((s) => s.itemId)
+ .filter((id) => !onHandByItem.has(id))
+ )
+ );
+ for (const successorId of successorIds) {
+ const quantities = await client.rpc("get_inventory_quantities", {
+ location_id: locationId,
+ company_id: companyId,
+ item_id: successorId
+ });
+ const row = quantities.data?.[0];
+ onHandByItem.set(successorId, Number(row?.quantityOnHand ?? 0));
+ incomingByItem.set(
+ successorId,
+ Number(row?.quantityOnPurchaseOrder ?? 0) +
+ Number(row?.quantityOnProductionOrder ?? 0)
+ );
+ }
+
// Remaining demand for those items across every active job at this location.
const { data } = await client
.from("jobMaterial")
.select(
- "id, itemId, jobId, methodType, quantityToIssue, job!inner(priority, status, locationId)"
+ "id, itemId, jobId, methodType, quantity, quantityToIssue, job!inner(priority, status, locationId)"
)
- .in("itemId", itemIds)
+ .in("itemId", [...itemIds, ...successorIds])
.eq("companyId", companyId)
.neq("methodType", "Make to Order")
.in("job.status", ACTIVE_JOB_STATUSES)
@@ -1385,6 +1432,7 @@ export async function getJobMaterialShortfallByItem(
type Line = {
materialId: string;
remaining: number;
+ perAssembly: number;
methodType: MethodType | null;
};
const demandByItem = new Map<string, Map<string, Demand>>();
@@ -1411,7 +1459,12 @@ export async function getJobMaterialShortfallByItem(
if (rowJobId === jobId && row.id) {
const lines = thisJobLinesByItem.get(itemId) ?? [];
- lines.push({ materialId: row.id, remaining, methodType: row.methodType });
+ lines.push({
+ materialId: row.id,
+ remaining,
+ perAssembly: Number(row.quantity ?? 0),
+ methodType: row.methodType
+ });
thisJobLinesByItem.set(itemId, lines);
}
}
@@ -1448,8 +1501,12 @@ export async function getJobMaterialShortfallByItem(
? 1
: 0)
);
+ const consumeFirst = successorByItem.has(itemId);
for (const line of lines) {
- const fromOnHand = Math.min(line.remaining, Math.max(onHand, 0));
+ const usable = consumeFirst
+ ? consumableInWholeAssemblies(onHand, line.perAssembly)
+ : Math.max(onHand, 0);
+ const fromOnHand = Math.min(line.remaining, usable);
onHand -= fromOnHand;
let need = line.remaining - fromOnHand;
const fromIncoming = Math.min(need, Math.max(incoming, 0));
@@ -1462,6 +1519,33 @@ export async function getJobMaterialShortfallByItem(
};
}
}
+ onHandByItem.set(itemId, onHand);
+ incomingByItem.set(itemId, incoming);
+ }
+
+ for (const [itemId, lines] of thisJobLinesByItem) {
+ const successor = successorByItem.get(itemId);
+ if (!successor) continue;
+ for (const line of lines) {
+ const current = shortfallByMaterial[line.materialId];
+ if (!current || current.shortfall <= 0) continue;
+ let need = current.shortfall * successor.factor;
+ let onHand = onHandByItem.get(successor.itemId) ?? 0;
+ let incoming = incomingByItem.get(successor.itemId) ?? 0;
+ const fromOnHand = Math.min(need, Math.max(onHand, 0));
+ onHand -= fromOnHand;
+ need -= fromOnHand;
+ const fromIncoming = Math.min(need, Math.max(incoming, 0));
+ incoming -= fromIncoming;
+ need -= fromIncoming;
+ onHandByItem.set(successor.itemId, onHand);
+ incomingByItem.set(successor.itemId, incoming);
+ shortfallByMaterial[line.materialId] = {
+ shortfall: need > 0 ? need : 0,
+ coveredByOnHand: need <= 0 && fromIncoming === 0,
+ substituteItemId: successor.itemId
+ };
+ }
}
return shortfallByMaterial;
}
@@ -1485,7 +1569,8 @@ function getJobMaterialOrderStatus(
poLines: JobMaterialPurchaseOrderLine[],
supplyJobLines: JobMaterialSupplyJobLine[],
shortfall: number,
- coveredByOnHand: boolean
+ coveredByOnHand: boolean,
+ substituteItemId: string | null = null
): ItemOrderStatus {
// Fully pulled into the job (its whole requirement has been issued/consumed).
const estimated = material.estimatedQuantity ?? 0;
@@ -1527,6 +1612,7 @@ function getJobMaterialOrderStatus(
needsOrder,
needsJob,
shortfall,
+ substituteItemId,
status,
supplyJobStatus,
coveredByOnHand,
@@ -1563,19 +1649,22 @@ function getJobOrderStatusByMaterial(
const byMaterialId: Record<string, ItemOrderStatus> = {};
for (const material of materials) {
if (!material.id) continue;
- const poLines = material.jobMaterialItemId
- ? (linesByItemId.get(material.jobMaterialItemId) ?? [])
- : [];
- const jobLines = material.jobMaterialItemId
- ? (jobLinesByItemId.get(material.jobMaterialItemId) ?? [])
- : [];
const lineShortfall = shortfallByMaterialId[material.id];
+ const supplyItemIds = [
+ material.jobMaterialItemId,
+ lineShortfall?.substituteItemId
+ ].filter((id): id is string => Boolean(id));
+ const poLines = supplyItemIds.flatMap((id) => linesByItemId.get(id) ?? []);
+ const jobLines = supplyItemIds.flatMap(
+ (id) => jobLinesByItemId.get(id) ?? []
+ );
byMaterialId[material.id] = getJobMaterialOrderStatus(
material,
poLines,
jobLines,
lineShortfall?.shortfall ?? 0,
- lineShortfall?.coveredByOnHand ?? false
+ lineShortfall?.coveredByOnHand ?? false,
+ lineShortfall?.substituteItemId ?? null
);
}
return byMaterialId;
@@ -1591,7 +1680,8 @@ export async function getJobOrderStatusMap(
jobStatus: string | null | undefined,
materials: NonNullable<
Awaited<ReturnType<typeof getJobMaterialsWithQuantityOnHand>>["data"]
- >
+ >,
+ asOfDate?: string
): Promise<Record<string, ItemOrderStatus>> {
// Completed/Draft/Cancelled/Closed jobs show no procurement indicators.
if (isJobOrderStatusHidden(jobStatus)) return {};
@@ -1607,14 +1697,41 @@ export async function getJobOrderStatusMap(
jobId,
companyId,
locationId,
- materials
+ materials,
+ asOfDate
)
]);
+ const materialItemIds = new Set(
+ materials.map((material) => material.jobMaterialItemId)
+ );
+ const substitutes = Array.from(
+ new Set(
+ Object.values(shortfallByMaterialId)
+ .map((shortfall) => shortfall.substituteItemId)
+ .filter(
+ (id): id is string =>
+ typeof id === "string" && !materialItemIds.has(id)
+ )
+ )
+ ).map((jobMaterialItemId) => ({ jobMaterialItemId }));
+ const [substitutePurchaseOrderLines, substituteSupplyJobLines] =
+ substitutes.length > 0
+ ? await Promise.all([
+ getJobMaterialPurchaseOrderLines(client, substitutes, locationId),
+ getJobMaterialSupplyJobLines(
+ client,
+ substitutes,
+ companyId,
+ locationId
+ )
+ ])
+ : [[], []];
+
return getJobOrderStatusByMaterial(
materials,
- purchaseOrderLines,
- supplyJobLines,
+ purchaseOrderLines.concat(substitutePurchaseOrderLines),
+ supplyJobLines.concat(substituteSupplyJobLines),
shortfallByMaterialId
);
}
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index bb84baef27..b8a7b3c84a 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -143,6 +143,7 @@ export type ItemOrderStatus = {
needsOrder: boolean;
needsJob: boolean;
shortfall: number;
+ substituteItemId: string | null;
status: PurchaseOrderStatus | null;
supplyJobStatus: JobStatus | null;
coveredByOnHand: boolean;
@@ -165,6 +166,7 @@ export type JobOrderStatusCategory =
export type ItemShortfall = {
shortfall: number;
coveredByOnHand: boolean;
+ substituteItemId?: string | null;
};
export type ProductionEvent = NonNullable<
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index a8bbd945b1..81d4460cc8 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -1,3 +1,4 @@
+import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import {
Badge,
Button,
@@ -22,6 +23,7 @@ import {
LuFactory,
LuFlag,
LuHash,
+ LuPackageCheck,
LuRefreshCcwDot,
LuShoppingCart
} from "react-icons/lu";
@@ -37,6 +39,7 @@ import {
} from "~/components";
import { useFilters } from "~/components/Table/components/Filter/useFilters";
import { usePermissions, useRouteData, useUrlParams } from "~/hooks";
+import type { JobMaterialPick } from "~/modules/inventory";
import { type Item, useItems } from "~/stores";
import { path } from "~/utils/path";
import {
@@ -52,6 +55,15 @@ type JobMaterialsTableProps = {
nearExpiryWarningDays?: number | null;
jobItemIds: string[];
orderStatusByMaterialId: Record<string, ItemOrderStatus>;
+ picksByMaterialId?: Record<string, JobMaterialPick[]>;
+ consumeFirstByItemId?: Record<
+ string,
+ {
+ successorItemId: string;
+ successorReadableId: string;
+ conversionFactor: number;
+ }
+ >;
};
function HeaderTooltip({ label, hint }: { label: ReactNode; hint: ReactNode }) {
return (
@@ -85,7 +97,9 @@ const JobMaterialsTable = memo(
count,
nearExpiryWarningDays,
jobItemIds,
- orderStatusByMaterialId
+ orderStatusByMaterialId,
+ picksByMaterialId = {},
+ consumeFirstByItemId = {}
}: JobMaterialsTableProps) => {
const { jobId } = useParams();
const { t } = useLingui();
@@ -140,6 +154,28 @@ const JobMaterialsTable = memo(
? (items.find((i) => i.id === substitutedFromId)
?.readableIdWithRevision ?? substitutedFromId)
: null;
+ const picks = row.original.id
+ ? (picksByMaterialId[row.original.id] ?? [])
+ : [];
+ const consumeFirst =
+ consumeFirstByItemId[row.original.jobMaterialItemId];
+ const need = Math.max(
+ 0,
+ Number(row.original.estimatedQuantity ?? 0) -
+ Number(row.original.quantityIssued ?? 0)
+ );
+ const perAssembly = Number(row.original.quantityPerParent ?? 0);
+ const onHand = consumableInWholeAssemblies(
+ Number(row.original.quantityOnHandInStorageUnit ?? 0) +
+ Number(row.original.quantityOnHandNotInStorageUnit ?? 0),
+ perAssembly
+ );
+ const shortfall =
+ consumeFirst && picks.length === 0 && need > onHand
+ ? need - onHand
+ : 0;
+ const assembliesInStock =
+ perAssembly > 0 ? onHand / perAssembly : null;
return (
<HStack className="py-1">
<ItemThumbnail
@@ -182,6 +218,30 @@ const JobMaterialsTable = memo(
↩ <Trans>substituted from</Trans> {substitutedFrom}
</div>
)}
+ {shortfall > 0 && consumeFirst && (
+ <div className="w-full truncate text-xs text-blue-700 dark:text-blue-300">
+ ↩{" "}
+ {assembliesInStock !== null ? (
+ <Trans>
+ {formatter.format(onHand)} in stock, for{" "}
+ {formatter.format(assembliesInStock)} assemblies; the
+ remaining{" "}
+ {formatter.format(
+ shortfall * consumeFirst.conversionFactor
+ )}{" "}
+ will be picked as {consumeFirst.successorReadableId}
+ </Trans>
+ ) : (
+ <Trans>
+ {formatter.format(onHand)} in stock; the remaining{" "}
+ {formatter.format(
+ shortfall * consumeFirst.conversionFactor
+ )}{" "}
+ will be picked as {consumeFirst.successorReadableId}
+ </Trans>
+ )}
+ </div>
+ )}
</VStack>
</HStack>
);
@@ -252,6 +312,76 @@ const JobMaterialsTable = memo(
}
}
},
+ {
+ id: "picked",
+ header: () => (
+ <HeaderTooltip
+ label={t`Picked`}
+ hint={
+ <Trans>
+ What has actually been picked to lineside for this material,
+ per part. A pick can bring a different part than the material
+ names (a Consume First split, a Prefer New fallback) — this is
+ where you see which parts are at the machine.
+ </Trans>
+ }
+ />
+ ),
+ cell: ({ row }) => {
+ const picks = row.original.id
+ ? (picksByMaterialId[row.original.id] ?? [])
+ : [];
+ if (picks.length === 0) return null;
+ return (
+ <VStack spacing={1} className="py-1">
+ {picks.map((pick) => {
+ const isFullyPicked =
+ pick.quantityToPick > 0 &&
+ pick.quantityPicked >= pick.quantityToPick;
+ const isPartial = !isFullyPicked && pick.quantityPicked > 0;
+ return (
+ <HStack
+ key={`${pick.pickingListId}:${pick.itemId}`}
+ spacing={2}
+ >
+ <Badge
+ variant={
+ isFullyPicked
+ ? "green"
+ : isPartial
+ ? "orange"
+ : "secondary"
+ }
+ className="gap-1 shrink-0"
+ >
+ <LuPackageCheck className="size-3" />
+ {isFullyPicked
+ ? formatter.format(pick.quantityPicked)
+ : `${formatter.format(pick.quantityPicked)}/${formatter.format(pick.quantityToPick)}`}
+ {" × "}
+ {pick.itemReadableId}
+ </Badge>
+ {pick.isSubstitute && (
+ <span className="text-xs text-blue-700 dark:text-blue-300 whitespace-nowrap">
+ <Trans>in place of this item</Trans>
+ </span>
+ )}
+ <Hyperlink
+ to={path.to.pickingList(pick.pickingListId)}
+ className="text-xs text-muted-foreground whitespace-nowrap"
+ >
+ {pick.pickingListReadableId}
+ </Hyperlink>
+ </HStack>
+ );
+ })}
+ </VStack>
+ );
+ },
+ meta: {
+ icon: <LuPackageCheck />
+ }
+ },
{
accessorKey: "estimatedQuantity",
header: () => (
@@ -540,7 +670,9 @@ const JobMaterialsTable = memo(
isRequired,
formatter,
jobItemIdSet,
- orderStatusByMaterialId
+ orderStatusByMaterialId,
+ picksByMaterialId,
+ consumeFirstByItemId
]);
const renderContextMenu = useMemo(() => {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx
index a379453c21..a635c0a80c 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx
@@ -11,6 +11,7 @@ import {
import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
+import { useItems } from "~/stores";
import { getJobOrderStatusCategory } from "../../production.models";
import type { ItemOrderStatus } from "../../types";
@@ -31,6 +32,11 @@ export function JobOrderStatusBadge({
);
const category = getJobOrderStatusCategory(status);
+ const [items] = useItems();
+ const substitute = status?.substituteItemId
+ ? (items.find((i) => i.id === status.substituteItemId)
+ ?.readableIdWithRevision ?? status.substituteItemId)
+ : null;
switch (category) {
case "issued":
@@ -41,12 +47,22 @@ export function JobOrderStatusBadge({
case "inStock":
return badge(
<LuCircleCheck className="text-emerald-600" />,
- <Trans>In stock</Trans>
+ substitute ? (
+ <Trans>In stock, the remainder as {substitute}</Trans>
+ ) : (
+ <Trans>In stock</Trans>
+ )
);
case "needsOrder":
return badge(
<LuCircleAlert className="text-red-500" />,
- <Trans>Order {status?.shortfall} for this job</Trans>
+ substitute ? (
+ <Trans>
+ Order {status?.shortfall} × {substitute} for this job
+ </Trans>
+ ) : (
+ <Trans>Order {status?.shortfall} for this job</Trans>
+ )
);
case "needsJob":
return badge(
diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
index 67d88dc0ca..429e359527 100644
--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
@@ -1,6 +1,8 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { Database } from "@carbon/database";
+import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
@@ -32,6 +34,126 @@ const defaultResponse = {
const WEEKS_TO_FORECAST = 12 * 4;
+type OpenJobMaterialLine = NonNullable<
+ Awaited<ReturnType<typeof getOpenJobMaterials>>["data"]
+>[number] & { redirectedFromReadableId?: string | null };
+
+function redirectJobMaterialLines(
+ lines: OpenJobMaterialLine[],
+ mode: string,
+ onHand: number
+): { kept: OpenJobMaterialLine[]; moved: OpenJobMaterialLine[] } {
+ const kept: OpenJobMaterialLine[] = [];
+ const moved: OpenJobMaterialLine[] = [];
+ let remaining = mode === "Consume First" ? Math.max(0, onHand) : 0;
+ const sorted = [...lines].sort((a, b) =>
+ (a.dueDate ?? "9999").localeCompare(b.dueDate ?? "9999")
+ );
+ for (const line of sorted) {
+ const quantity = Number(line.quantity ?? 0);
+ const covered = Math.min(
+ quantity,
+ consumableInWholeAssemblies(
+ remaining,
+ Number(line.quantityPerParent ?? 0)
+ )
+ );
+ remaining -= covered;
+ if (covered > 0) kept.push({ ...line, quantity: covered });
+ if (quantity - covered > 0) {
+ moved.push({ ...line, quantity: quantity - covered });
+ }
+ }
+ return { kept, moved };
+}
+
+const REDIRECTING_MODES = new Set([
+ "Consume First",
+ "Prefer New",
+ "Stock Only"
+]);
+
+async function getRedirectedOpenJobMaterials(
+ client: Parameters<typeof getOpenJobMaterials>[0],
+ args: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ today: string;
+ onHand: number;
+ lines: OpenJobMaterialLine[];
+ }
+): Promise<OpenJobMaterialLine[]> {
+ const { itemId, locationId, companyId, today, onHand } = args;
+ const effective = (rule: {
+ supersessionMode: Database["public"]["Enums"]["supersessionMode"];
+ successorItemId: string | null;
+ successorEffectivityDate: string | null;
+ }) =>
+ REDIRECTING_MODES.has(rule.supersessionMode) &&
+ !!rule.successorItemId &&
+ (!rule.successorEffectivityDate || rule.successorEffectivityDate <= today);
+
+ const [own, incoming] = await Promise.all([
+ client
+ .from("itemSupersession")
+ .select("supersessionMode, successorItemId, successorEffectivityDate")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ client
+ .from("itemSupersession")
+ .select(
+ "itemId, supersessionMode, successorItemId, successorEffectivityDate, conversionFactor, predecessor:item!itemSupersession_itemId_fkey(readableIdWithRevision)"
+ )
+ .eq("successorItemId", itemId)
+ .eq("companyId", companyId)
+ ]);
+
+ if (own.error) throw new Error(own.error.message);
+ if (incoming.error) throw new Error(incoming.error.message);
+
+ let lines = args.lines;
+ if (own.data && effective(own.data)) {
+ lines = redirectJobMaterialLines(
+ lines,
+ own.data.supersessionMode,
+ onHand
+ ).kept;
+ }
+
+ for (const rule of incoming.data ?? []) {
+ if (!effective(rule)) continue;
+ const [predecessorLines, quantities] = await Promise.all([
+ getOpenJobMaterials(client, {
+ itemId: rule.itemId,
+ companyId,
+ locationId
+ }),
+ getItemQuantities(client, rule.itemId, companyId, locationId)
+ ]);
+ if (predecessorLines.error) {
+ throw new Error(predecessorLines.error.message);
+ }
+ if (quantities.error) throw new Error(quantities.error.message);
+ const factor = Number(rule.conversionFactor ?? 1) || 1;
+ const { moved } = redirectJobMaterialLines(
+ predecessorLines.data ?? [],
+ rule.supersessionMode,
+ Number(quantities.data?.quantityOnHand ?? 0)
+ );
+ for (const line of moved) {
+ lines.push({
+ ...line,
+ quantity: Number(line.quantity ?? 0) * factor,
+ redirectedFromReadableId:
+ rule.predecessor?.readableIdWithRevision ?? rule.itemId
+ });
+ }
+ }
+ return lines;
+}
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "parts"
@@ -41,10 +163,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!itemId) throw new Error("Could not find itemId");
if (!locationId) throw new Error("Could not find locationId");
- const periods = await getOrCreatePeriods(
- datetime.today(await getLocationTimeZone(client, locationId, companyId)),
- WEEKS_TO_FORECAST
+ const today = datetime.today(
+ await getLocationTimeZone(client, locationId, companyId)
);
+ const periods = await getOrCreatePeriods(today, WEEKS_TO_FORECAST);
const [
demand,
@@ -88,6 +210,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ const redirectedOpenJobMaterials = await getRedirectedOpenJobMaterials(
+ client,
+ {
+ itemId,
+ locationId,
+ companyId,
+ today: today.toString(),
+ onHand: Number(quantities.data?.quantityOnHand ?? 0),
+ lines: openJobMaterials.data ?? []
+ }
+ );
+
return {
demand: demand.actuals,
demandForecast: demand.forecasts,
@@ -102,7 +236,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
periods,
quantityOnHand: quantities.data?.quantityOnHand ?? 0,
openSalesOrderLines: openSalesOrderLines.data ?? [],
- openJobMaterials: openJobMaterials.data ?? [],
+ openJobMaterials: redirectedOpenJobMaterials,
openProductionOrders: openProductionOrders.data ?? [],
openPurchaseOrderLines: openPurchaseOrderLines.data ?? []
};
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index f4b2a69bd6..c09487a31e 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1564,
+ "totalTools": 1567,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
@@ -162,6 +162,7 @@
{"name":"documents_updateDocumentFavorite","classification":"DESTRUCTIVE","paramCount":2,"schema":"85769b943e30","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"documents:update","paginates":false},
{"name":"documents_updateDocumentLabels","classification":"DESTRUCTIVE","paramCount":2,"schema":"0adc09fa2bb3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"documents:update","paginates":false},
{"name":"documents_upsertDocument","classification":"WRITE","paramCount":11,"schema":"80aaa4f65fcb","response":"e44071b67bea","injectAuth":"companyId+createdBy+updatedBy","permission":"documents:create+update","paginates":false},
+ {"name":"inventory_cancelOpenPickingListsForJob","classification":"WRITE","paramCount":1,"schema":"4999bd4be598","response":"844f8eedb019","injectAuth":"companyId","permission":"inventory:update","paginates":false},
{"name":"inventory_correctStockMovement","classification":"WRITE","paramCount":3,"schema":"fb389b0474f2","response":"3797626bd17e","injectAuth":"companyId","permission":"inventory:update","paginates":false},
{"name":"inventory_createInventoryReconciliationJournal","classification":"WRITE","paramCount":1,"schema":"00e9099a963a","response":"a9f23ceb9dc1","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create","paginates":false},
{"name":"inventory_deleteBatchProperty","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},
@@ -204,14 +205,15 @@
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"114433bf62ba","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"dccc40b61694","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"cc66c1b66f31","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"07d244c0f017","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListRecommendations","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"24283057a15d","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingLists","classification":"READ","paramCount":6,"schema":"3599c50bdc36","response":"2112d9a1ea1d","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getPickingSchedule","classification":"READ","paramCount":2,"schema":"b3a9deeaf0d0","response":"19467666efcd","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickOrder","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"7fa0311f0d0a","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPicksByJobMaterial","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"b53992cb5f0c","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceipt","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"912bc3c9329d","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceiptFiles","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"5483e69d7515","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getReceiptLines","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"15b7b17f7652","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -296,7 +298,7 @@
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"114433bf62ba","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"dccc40b61694","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
@@ -399,7 +401,7 @@
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"114433bf62ba","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dccc40b61694","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -438,6 +440,7 @@
{"name":"items_getItemStorageUnitQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"880fa3aa7279","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemSupersededBy","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"8e2ea57c0664","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemSupersession","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"0c693c4f3dcb","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getItemSupersessionsForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"e06b6534cfe9","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemSupply","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"696523b54f52","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemUnitSalePrice","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"7281903c959e","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getJobMaterialUsageForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"67faac8214ed","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -473,7 +476,7 @@
{"name":"items_getMethodTree","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"18cc03a418b4","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getMethodTreeArray","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"6481a47cef6d","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getNextRevision","classification":"READ","paramCount":1,"schema":"96527a3bce32","response":"00404e686415","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getOpenJobMaterials","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"a4e238c7dc68","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getOpenJobMaterials","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"3df5c33eb3a4","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getOpenProductionOrders","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"6f4bb8737e15","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getOpenPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"ee9244a3a03b","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getOpenSalesOrderLines","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"ee9244a3a03b","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -700,7 +703,7 @@
{"name":"production_getJobMaterialItemIds","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"32068a500dfe","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"b12e99320d04","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"562cd876b859","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getJobMaterialShortfallByItem","classification":"READ","paramCount":3,"schema":"62385967084f","response":"f43f2fa5a47f","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getJobMaterialShortfallByItem","classification":"READ","paramCount":4,"schema":"644b4df6515a","response":"8a62dcc3c7f9","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialSupplyJobLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"8e048b6a60ce","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialsWithQuantityOnHand","classification":"READ","paramCount":3,"schema":"0e9e6edbd779","response":"be0a4b3c547b","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMethodTree","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"a0e7ca5d166e","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -719,7 +722,7 @@
{"name":"production_getJobOperationsForTimeline","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"6f0169823721","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperationsList","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"4e5425835530","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobOperationStepRecords","classification":"READ","paramCount":2,"schema":"2e4f0768fe43","response":"272548978b28","injectAuth":"companyId","permission":"production:view","paginates":true},
- {"name":"production_getJobOrderStatusMap","classification":"READ","paramCount":4,"schema":"ff6a888f05b8","response":"3f77244fd820","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getJobOrderStatusMap","classification":"READ","paramCount":5,"schema":"6158637094f4","response":"4437cc40ad52","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobPromiseDate","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"f6521bc077a4","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"309dea2a265c","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobReceiptSnapshot","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"af63ddd51939","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -777,13 +780,13 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"114433bf62ba","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"dccc40b61694","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"114433bf62ba","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"9feb22a88104","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"114433bf62ba","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"dccc40b61694","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"389763929620","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"dccc40b61694","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx
index 3d15fe20b8..e4deae1b2c 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx
@@ -4,8 +4,11 @@ import { flash } from "@carbon/auth/session.server";
import { useMount, VStack } from "@carbon/react";
import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect, useLoaderData } from "react-router";
+import { redirect, useLoaderData, useParams } from "react-router";
import { usePanels } from "~/components/Layout";
+import { useRealtime } from "~/hooks";
+import { getPicksByJobMaterial } from "~/modules/inventory";
+import { getItemSupersessionsForItems } from "~/modules/items";
import {
getJob,
getJobMaterialItemIds,
@@ -44,7 +47,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const locationId = job.data.locationId ?? "";
// Independent — run in parallel.
- const [materials, settings, jobItems] = await Promise.all([
+ const [materials, settings, jobItems, picks] = await Promise.all([
getJobMaterialsWithQuantityOnHand(client, jobId, companyId, locationId, {
search,
limit,
@@ -60,7 +63,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
)
}),
getCompanySettings(client, companyId),
- getJobMaterialItemIds(client, jobId, companyId)
+ getJobMaterialItemIds(client, jobId, companyId),
+ getPicksByJobMaterial(client, jobId, companyId)
]);
if (materials.error) {
@@ -73,6 +77,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ if (picks.error) {
+ throw redirect(
+ path.to.production,
+ await flash(request, error(picks.error, "Failed to fetch picks"))
+ );
+ }
+
const rows = materials.data ?? [];
const nearExpiryWarningDays =
(
@@ -81,24 +92,64 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
} | null
)?.nearExpiryWarningDays ?? null;
- // Both depend on the materials but not on each other.
- const [expiredItemIds, orderStatusByMaterialId] = await Promise.all([
- getExpiredItemIds(
- client,
- companyId,
- rows,
- nearExpiryWarningDays,
- locationId
- ),
- getJobOrderStatusMap(
- client,
- jobId,
- companyId,
- locationId,
- job.data.status,
+ const materialItemIds = Array.from(
+ new Set(
rows
+ .map((m) => m.jobMaterialItemId)
+ .filter((id): id is string => Boolean(id))
)
- ]);
+ );
+
+ const today = datetime
+ .today(await getLocationTimeZone(client, locationId, companyId))
+ .toString();
+
+ const [expiredItemIds, orderStatusByMaterialId, supersessions] =
+ await Promise.all([
+ getExpiredItemIds(
+ client,
+ companyId,
+ rows,
+ nearExpiryWarningDays,
+ locationId
+ ),
+ getJobOrderStatusMap(
+ client,
+ jobId,
+ companyId,
+ locationId,
+ job.data.status,
+ rows,
+ today
+ ),
+ getItemSupersessionsForItems(client, materialItemIds, companyId)
+ ]);
+ if (supersessions.error) {
+ throw redirect(
+ path.to.production,
+ await flash(
+ request,
+ error(supersessions.error, "Failed to fetch supersessions")
+ )
+ );
+ }
+ const consumeFirstByItemId: Record<string, ConsumeFirstRule> = {};
+ for (const rule of supersessions.data ?? []) {
+ if (rule.supersessionMode !== "Consume First") continue;
+ if (!rule.successorItemId) continue;
+ if (
+ rule.successorEffectivityDate &&
+ rule.successorEffectivityDate > today
+ ) {
+ continue;
+ }
+ consumeFirstByItemId[rule.itemId] = {
+ successorItemId: rule.successorItemId,
+ successorReadableId:
+ rule.successor?.readableIdWithRevision ?? rule.successorItemId,
+ conversionFactor: Number(rule.conversionFactor ?? 1) || 1
+ };
+ }
const jobItemIds = Array.from(
new Set(
@@ -116,10 +167,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
hasExpiredBatch: expiredItemIds.has(m.jobMaterialItemId ?? "")
})),
nearExpiryWarningDays,
- orderStatusByMaterialId
+ orderStatusByMaterialId,
+ picksByMaterialId: picks.data,
+ consumeFirstByItemId
};
}
+export type ConsumeFirstRule = {
+ successorItemId: string;
+ successorReadableId: string;
+ conversionFactor: number;
+};
+
// Item ids with stock already past its expiration date (the "Expired batch" badge).
async function getExpiredItemIds(
client: Parameters<typeof getJob>[0],
@@ -160,10 +219,15 @@ export default function JobMaterialsRoute() {
materials,
nearExpiryWarningDays,
jobItemIds,
- orderStatusByMaterialId
+ orderStatusByMaterialId,
+ picksByMaterialId,
+ consumeFirstByItemId
} = useLoaderData<typeof loader>();
+ const { jobId } = useParams();
const { setIsExplorerCollapsed } = usePanels();
+ useRealtime("pickingListLine", `jobId=eq.${jobId}`);
+
useMount(() => {
setIsExplorerCollapsed(true);
});
@@ -179,6 +243,8 @@ export default function JobMaterialsRoute() {
nearExpiryWarningDays={nearExpiryWarningDays}
jobItemIds={jobItemIds}
orderStatusByMaterialId={orderStatusByMaterialId}
+ picksByMaterialId={picksByMaterialId}
+ consumeFirstByItemId={consumeFirstByItemId}
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
index 3a3eb25941..52fa84c749 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
@@ -18,15 +18,12 @@ vi.mock("@carbon/auth/client.server", () => ({
vi.mock("@carbon/auth/session.server", () => ({
flash: vi.fn(async () => ({}))
}));
-vi.mock("@carbon/logger", () => ({
- getLogger: () => ({ error: vi.fn() })
-}));
-// Scheduling moved OUT of the `schedule` edge function and into Node in #1151:
-// the release path now regenerates the job's whole location in-process via
-// `runLocationSchedule` instead of `serviceRole.functions.invoke("schedule")`.
vi.mock("@carbon/ee/planning", () => ({
runLocationSchedule: vi.fn()
}));
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ error: vi.fn() })
+}));
vi.mock("~/services/database.server", () => ({
getDatabaseClient: vi.fn(() => ({}))
}));
@@ -39,6 +36,9 @@ vi.mock("~/utils/path", () => ({
},
requestReferrer: () => null
}));
+vi.mock("~/modules/inventory", () => ({
+ cancelOpenPickingListsForJob: vi.fn()
+}));
vi.mock("~/modules/production", () => ({
jobStatus: [
"Draft",
@@ -51,11 +51,16 @@ vi.mock("~/modules/production", () => ({
"Cancelled"
],
recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),
+ returnPickedRemaindersForJob: vi.fn(),
runMRP: vi.fn(async () => ({ data: null, error: null })),
updateJobStatus: vi.fn()
}));
-import { updateJobStatus } from "~/modules/production";
+import { cancelOpenPickingListsForJob } from "~/modules/inventory";
+import {
+ returnPickedRemaindersForJob,
+ updateJobStatus
+} from "~/modules/production";
import { action } from "./$jobId.status";
type QueryResult = { data: unknown; error: unknown };
@@ -114,12 +119,29 @@ function setup() {
});
vi.mocked(runLocationSchedule).mockImplementation(async () => {
events.push("runLocationSchedule");
- return {} as any;
+ return undefined as any;
+ });
+ vi.mocked(returnPickedRemaindersForJob).mockImplementation(async () => {
+ events.push("returnPickedRemainders");
+ return { data: {}, error: null } as any;
+ });
+ vi.mocked(cancelOpenPickingListsForJob).mockImplementation(async () => {
+ events.push("cancelOpenPickingLists");
+ return { error: null };
});
return { client, serviceRole };
}
+function cancelRequest() {
+ const body = new FormData();
+ body.set("status", "Cancelled");
+ return new Request("http://localhost/x/job/job-1/status", {
+ method: "POST",
+ body
+ });
+}
+
function releaseRequest() {
const body = new FormData();
body.set("status", "Ready");
@@ -158,12 +180,32 @@ describe("Job release status action", () => {
expect(updateJobStatus).toHaveBeenCalledOnce();
expect(events).toContain("updateJobStatus");
expect(events).toContain("runLocationSchedule");
- // Regression guard: the scheduler only batches jobs already Ready/In
- // Progress/Paused. If the status is committed AFTER the scheduler runs, the
- // freshly released job is filtered out of its own schedule run and never
- // lands in capacityReservation / the forecast.
+ // Ready/In Progress/Paused. If the status is committed AFTER the scheduler
+ // runs, the freshly released job is filtered out of its own schedule run and
+ // never lands in capacityReservation / the forecast.
expect(events.indexOf("updateJobStatus")).toBeLessThan(
events.indexOf("runLocationSchedule")
);
});
});
+
+describe("Job cancel status action", () => {
+ it("returns staged material, then cancels the job's open picking lists", async () => {
+ await expect(
+ action({
+ request: cancelRequest(),
+ params: { jobId: "job-1" },
+ context: {}
+ } as any)
+ ).rejects.toBeInstanceOf(Response);
+
+ expect(returnPickedRemaindersForJob).toHaveBeenCalledOnce();
+ expect(cancelOpenPickingListsForJob).toHaveBeenCalledWith(
+ expect.anything(),
+ { jobId: "job-1", companyId: "company-1", userId: "user-1" }
+ );
+ expect(events.indexOf("returnPickedRemainders")).toBeLessThan(
+ events.indexOf("cancelOpenPickingLists")
+ );
+ });
+});
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index de3a0f400c..2d11e39d33 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -6,9 +6,11 @@ import { runLocationSchedule } from "@carbon/ee/planning";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
+import { cancelOpenPickingListsForJob } from "~/modules/inventory";
import {
jobStatus,
recalculateJobRequirements,
+ returnPickedRemaindersForJob,
runMRP,
updateJobStatus
} from "~/modules/production";
@@ -81,6 +83,40 @@ export async function action({ request, params }: ActionFunctionArgs) {
// (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.
+ if (status === "Cancelled") {
+ const sweep = await returnPickedRemaindersForJob(getCarbonServiceRole(), {
+ jobId: id,
+ userId,
+ companyId
+ });
+ if (sweep.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(
+ request,
+ error(sweep.error, "Cancel aborted: returning picked material failed")
+ )
+ );
+ }
+ const picks = await cancelOpenPickingListsForJob(getDatabaseClient(), {
+ jobId: id,
+ companyId,
+ userId
+ });
+ if (picks.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(
+ request,
+ error(
+ picks.error,
+ "Cancel aborted: its picking lists could not be closed"
+ )
+ )
+ );
+ }
+ }
+
const update = await updateJobStatus(client, {
id,
companyId,
diff --git a/apps/erp/app/routes/x+/job+/$jobId.tsx b/apps/erp/app/routes/x+/job+/$jobId.tsx
index 81e0b09a7e..5dabdc6686 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.tsx
@@ -2,6 +2,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { activeJobStatuses } from "@carbon/database";
+import { datetime } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { Suspense, useMemo } from "react";
@@ -33,6 +34,7 @@ import {
} from "~/modules/production/ui/Jobs";
import type { JobOrderStatusData } from "~/modules/production/ui/Jobs/JobBoMExplorer";
import { getTagsList } from "~/modules/shared";
+import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -61,7 +63,10 @@ async function getJobOrderStatus(
companyId,
locationId,
jobStatus,
- materials.data ?? []
+ materials.data ?? [],
+ datetime
+ .today(await getLocationTimeZone(client, locationId, companyId))
+ .toString()
);
}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx b/apps/erp/app/routes/x+/part+/$itemId.planning.tsx
index 47522e1e4b..cc33bf32a7 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.planning.tsx
@@ -13,6 +13,8 @@ import {
getSupersessionChain,
itemPlanningValidator,
itemSupersessionValidator,
+ predecessorSupersessionValidator,
+ SUPERSESSION_CYCLE_CODE,
upsertItemPlanning,
upsertItemSupersession
} from "~/modules/items";
@@ -90,6 +92,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
partPlanning: partPlanning.data,
supersession: supersession.data,
supersessionChain: supersessionChain.chain,
+ supersededBy: supersessionChain.supersededBy,
quantityOnHand: quantities.data?.quantityOnHand ?? 0,
locationId
};
@@ -123,6 +126,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
updatedBy: userId
});
if (updateSupersession.error) {
+ if (updateSupersession.error.code === SUPERSESSION_CYCLE_CODE) {
+ return validationError({
+ fieldErrors: { successorItemId: updateSupersession.error.message },
+ formId: supersessionValidation.formId
+ });
+ }
throw redirect(
path.to.part(itemId),
await flash(
@@ -143,6 +152,77 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (formData.get("intent") === "supersession-predecessor") {
+ const predecessorValidation = await validator(
+ predecessorSupersessionValidator
+ ).validate(formData);
+
+ if (predecessorValidation.error) {
+ return validationError(predecessorValidation.error);
+ }
+
+ const { predecessorItemId, ...supersession } = predecessorValidation.data;
+ const fieldError = (message: string) =>
+ validationError({
+ fieldErrors: { predecessorItemId: message },
+ formId: predecessorValidation.formId
+ });
+
+ if (predecessorItemId === itemId) {
+ return fieldError("A part cannot be its own predecessor");
+ }
+
+ const [predecessor, existing] = await Promise.all([
+ client
+ .from("item")
+ .select("id, readableIdWithRevision")
+ .eq("id", predecessorItemId)
+ .eq("companyId", companyId)
+ .maybeSingle(),
+ getItemSupersession(client, predecessorItemId, companyId)
+ ]);
+ if (!predecessor.data) {
+ return fieldError("Part not found");
+ }
+ if (existing.error) {
+ return fieldError("Failed to read the part's supersession");
+ }
+ if (
+ existing.data?.successorItemId &&
+ existing.data.successorItemId !== itemId
+ ) {
+ return fieldError(
+ `${predecessor.data.readableIdWithRevision ?? predecessorItemId} already has a successor (${existing.data.successor?.readableIdWithRevision ?? existing.data.successorItemId}). Change it from that part's planning page.`
+ );
+ }
+
+ const insertSupersession = await upsertItemSupersession(client, {
+ ...supersession,
+ itemId: predecessorItemId,
+ successorItemId: itemId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+ if (insertSupersession.error) {
+ if (insertSupersession.error.code === SUPERSESSION_CYCLE_CODE) {
+ return fieldError(insertSupersession.error.message);
+ }
+ throw redirect(
+ path.to.partPlanning(itemId),
+ await flash(
+ request,
+ error(insertSupersession.error, "Failed to add predecessor")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.partPlanning(itemId),
+ await flash(request, success("Added predecessor"))
+ );
+ }
+
const validation = await validator(itemPlanningValidator).validate(formData);
if (validation.error) {
@@ -180,6 +260,7 @@ export default function PartPlanningRoute() {
partPlanning,
supersession,
supersessionChain,
+ supersededBy,
quantityOnHand,
locationId
} = useLoaderData<typeof loader>();
@@ -224,6 +305,7 @@ export default function PartPlanningRoute() {
}
quantityOnHand={quantityOnHand}
chain={supersessionChain}
+ supersededBy={supersededBy}
/>
<ItemPlanningChart
itemId={partPlanning.itemId}
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index a6a1e9c9ef..42cd9589a7 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -229,6 +229,54 @@ function PickedBadge({
);
}
+function PickedBreakdown({
+ materialItemId,
+ pickedByItem
+}: {
+ materialItemId: string | null | undefined;
+ pickedByItem?:
+ | {
+ itemId: string;
+ itemReadableId: string;
+ quantityPicked: number;
+ quantityToPick: number;
+ }[]
+ | null;
+}) {
+ const picks = pickedByItem ?? [];
+ if (!picks.some((p) => p.itemId !== materialItemId)) return null;
+ return (
+ <div className="flex flex-wrap items-center gap-1 text-xs text-blue-700 dark:text-blue-300">
+ <span>
+ <Trans>Picked as</Trans>
+ </span>
+ {picks.map((pick) => {
+ const isFullyPicked =
+ pick.quantityToPick > 0 && pick.quantityPicked >= pick.quantityToPick;
+ return (
+ <Badge
+ key={pick.itemId}
+ variant={
+ isFullyPicked
+ ? "green"
+ : pick.quantityPicked > 0
+ ? "orange"
+ : "secondary"
+ }
+ className="gap-1 shrink-0"
+ >
+ {isFullyPicked
+ ? pick.quantityPicked
+ : `${pick.quantityPicked}/${pick.quantityToPick}`}
+ {" × "}
+ {pick.itemReadableId}
+ </Badge>
+ );
+ })}
+ </div>
+ );
+}
+
export const JobOperation = ({
batch,
events,
@@ -1360,6 +1408,21 @@ export const JobOperation = ({
<span className="text-muted-foreground text-sm truncate max-w-full">
{material.description}
</span>
+ <PickedBreakdown
+ materialItemId={material.itemId}
+ pickedByItem={
+ (
+ material as {
+ pickedByItem?: {
+ itemId: string;
+ itemReadableId: string;
+ quantityPicked: number;
+ quantityToPick: number;
+ }[];
+ }
+ ).pickedByItem
+ }
+ />
</VStack>
{material.requiresBatchTracking ? (
<Badge variant="secondary">
@@ -1561,6 +1624,23 @@ export const JobOperation = ({
<span className="text-muted-foreground text-xs truncate max-w-full">
{kittedChild.description}
</span>
+ <PickedBreakdown
+ materialItemId={
+ kittedChild.itemId
+ }
+ pickedByItem={
+ (
+ kittedChild as {
+ pickedByItem?: {
+ itemId: string;
+ itemReadableId: string;
+ quantityPicked: number;
+ quantityToPick: number;
+ }[];
+ }
+ ).pickedByItem
+ }
+ />
</VStack>
{kittedChild.requiresBatchTracking ? (
<Badge variant="secondary">
diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.tsx
index bce9d5b85a..e72efc14d2 100644
--- a/apps/mes/app/routes/x+/picking.$pickingListId.tsx
+++ b/apps/mes/app/routes/x+/picking.$pickingListId.tsx
@@ -444,6 +444,46 @@ function PickLineItem({
const lineItem = line.item as { name: string; readableId: string } | null;
const item = items.find((i) => i.id === line.itemId);
const itemName = item?.name ?? lineItem?.name ?? "";
+ const sourceMaterial = (
+ line as {
+ jobMaterial?: {
+ itemId?: string | null;
+ quantity?: number | string | null;
+ substitutionFactor?: number | string | null;
+ item?: {
+ readableId?: string | null;
+ itemSupersession?: {
+ conversionFactor?: number | string | null;
+ } | null;
+ } | null;
+ } | null;
+ }
+ ).jobMaterial;
+ const substitutedFrom =
+ sourceMaterial?.itemId && sourceMaterial.itemId !== line.itemId
+ ? (items.find((i) => i.id === sourceMaterial.itemId)
+ ?.readableIdWithRevision ??
+ sourceMaterial.item?.readableId ??
+ sourceMaterial.itemId)
+ : null;
+ const substitutedAssemblies = (() => {
+ if (!substitutedFrom || !sourceMaterial) return null;
+ const perAssembly = Number(sourceMaterial.quantity ?? 0);
+ if (!(perAssembly > 0)) return null;
+ const substitutionFactor = Number(sourceMaterial.substitutionFactor ?? 0);
+ const conversionFactor = Number(
+ sourceMaterial.item?.itemSupersession?.conversionFactor ?? 0
+ );
+ const factor =
+ substitutionFactor > 0
+ ? 1 / substitutionFactor
+ : conversionFactor > 0
+ ? conversionFactor
+ : null;
+ if (factor === null) return null;
+ const n = Number(line.quantityToPick ?? 0) / (perAssembly * factor);
+ return Number.isInteger(n) ? n : null;
+ })();
const source = (line.storageUnit as { name?: string } | null)?.name;
const availableQuantity = Number(
(line as { availableQuantity?: number }).availableQuantity ?? 0
@@ -557,6 +597,21 @@ function PickLineItem({
<p className="truncate font-mono text-sm text-muted-foreground">
{item?.readableIdWithRevision ?? lineItem?.readableId}
</p>
+ {substitutedFrom && (
+ <p className="truncate text-sm text-blue-700 dark:text-blue-300">
+ ↩{" "}
+ {substitutedAssemblies !== null ? (
+ <Trans>
+ picking in place of {substitutedFrom}, the item on the job,
+ for {substitutedAssemblies} assemblies
+ </Trans>
+ ) : (
+ <Trans>
+ picking in place of {substitutedFrom}, the item on the job
+ </Trans>
+ )}
+ </p>
+ )}
{isTracked && !isFullyPicked && (
<RecommendedLots resolve={recommendations} lineId={line.id} />
)}
diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
index d54d6a03a7..191bba0d62 100644
--- a/apps/mes/app/services/inventory.service.ts
+++ b/apps/mes/app/services/inventory.service.ts
@@ -350,9 +350,17 @@ export async function getSuggestedAllocationForMaterial(
return greedyFillAllocation(ordered, args.quantity);
}
+export type JobMaterialPickedItem = {
+ itemId: string;
+ itemReadableId: string;
+ quantityPicked: number;
+ quantityToPick: number;
+};
+
export type JobMaterialPickedQuantity = {
quantityPicked: number;
quantityToPick: number;
+ pickedByItem: JobMaterialPickedItem[];
};
/**
@@ -375,7 +383,7 @@ export async function getPickedQuantitiesByJobMaterial(
const { data, error } = await client
.from("pickingListLine")
.select(
- "jobMaterialId, quantityToPick, quantityPicked, quantityReturned, pickingList!inner(status)"
+ "jobMaterialId, itemId, quantityToPick, quantityPicked, quantityReturned, pickingList!inner(status), item(readableIdWithRevision)"
)
.in("jobMaterialId", jobMaterialIds)
.neq("status", "Cancelled")
@@ -387,16 +395,33 @@ export async function getPickedQuantitiesByJobMaterial(
if (!line.jobMaterialId) continue;
const entry = (picked[line.jobMaterialId] ??= {
quantityPicked: 0,
- quantityToPick: 0
+ quantityToPick: 0,
+ pickedByItem: []
});
// 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(
+ const quantityPicked = Math.max(
0,
Number(line.quantityPicked ?? 0) - Number(line.quantityReturned ?? 0)
);
- entry.quantityToPick += Number(line.quantityToPick ?? 0);
+ const quantityToPick = Number(line.quantityToPick ?? 0);
+ entry.quantityPicked += quantityPicked;
+ entry.quantityToPick += quantityToPick;
+
+ if (!line.itemId) continue;
+ let byItem = entry.pickedByItem.find((p) => p.itemId === line.itemId);
+ if (!byItem) {
+ byItem = {
+ itemId: line.itemId,
+ itemReadableId: line.item?.readableIdWithRevision ?? line.itemId,
+ quantityPicked: 0,
+ quantityToPick: 0
+ };
+ entry.pickedByItem.push(byItem);
+ }
+ byItem.quantityPicked += quantityPicked;
+ byItem.quantityToPick += quantityToPick;
}
return picked;
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 8d807454c7..6f42454731 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -849,7 +849,8 @@ export async function getJobMaterialsByOperationId(
const pickedFor = (materialId: string | null) =>
(materialId ? pickedByMaterial[materialId] : undefined) ?? {
quantityPicked: 0,
- quantityToPick: 0
+ quantityToPick: 0,
+ pickedByItem: []
};
if (requiresSerialTracking) {
diff --git a/apps/mes/app/services/picking.service.ts b/apps/mes/app/services/picking.service.ts
index 95af7849f1..453b119a0d 100644
--- a/apps/mes/app/services/picking.service.ts
+++ b/apps/mes/app/services/picking.service.ts
@@ -29,7 +29,7 @@ export async function getPickingListForExecution(
const { data: lines, error: lineError } = await client
.from("pickingListLine")
.select(
- "*, item:item(name, readableId), job:job(jobId), jobOperation:jobOperation(order, processId, workCenterId, process:process(name), workCenter:workCenter(name)), storageUnit:storageUnit!pickingListLine_storageUnitId_fkey(name), toStorageUnit:storageUnit!pickingListLine_toStorageUnitId_fkey(name)"
+ "*, item:item(name, readableId), jobMaterial:jobMaterial(itemId, quantity, substitutionFactor, item(readableId, itemSupersession!itemSupersession_itemId_fkey(conversionFactor))), job:job(jobId), jobOperation:jobOperation(order, processId, workCenterId, process:process(name), workCenter:workCenter(name)), storageUnit:storageUnit!pickingListLine_storageUnitId_fkey(name), toStorageUnit:storageUnit!pickingListLine_toStorageUnitId_fkey(name)"
)
.eq("pickingListId", pickingListId)
.order("jobOperationId")
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index e8170675bb..84f7dbed73 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -42,7 +42,8 @@ pnpm --filter @carbon/database typecheck
| `./logging` | Node re-export of `supabase/functions/lib/logging.ts` (`getFunctionLogger`) |
| `./mrp-engine` | Node re-export of `supabase/functions/lib/mrp-engine.ts` (`explodeBom`, `makeKey`, `makeLocationItemKey`, `makeActualKey`, …) — the pure MRP compute engine consumed by `@carbon/ee/planning`'s `runMrp` (the engine STAYS in the edge-lib; still used by the Deno `recalculate` function) |
| `./fetch-all` | Node re-export of `supabase/functions/lib/fetch-all.ts` (`fetchAll` — paginated PostgREST reads) |
-| `./supersession-pick` | Node re-export of `supabase/functions/lib/supersession-pick.ts` (`buildSupersessionRedirectMap`) |
+| `./supersession-pick` | Node re-export of `supabase/functions/lib/supersession-pick.ts` (`buildSupersessionRedirectMap`, `buildConsumeFirstHops`, `settleConsumeFirstLine`, `resolveMadeLinePull`, `consumableInWholeAssemblies`, …) |
+| `./picked-consumption` | Node re-export of `supabase/functions/lib/picked-consumption.ts` (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush |
| `./event` | `QueueMessage`, `EventSchema`, `createEventSystemSubscription`, `deleteEventSystemSubscription` |
| `./quality` | Inspection execution engine shared by ERP + MES (`upsertInspectionSample`, `upsertInspectionMeasurement`, `dispositionInspection` — optional one-shot `requireOpen`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`, `getOrCreateJobOperationInspection`, pure `valuateMeasurement`); Passed/Failed/Partial are all hard-terminal and samples linked from `productionQuantity.inspectionSampleId` are locked; every fn takes a `Kysely<KyselyDatabase>` first arg — authorize at the route, see `.claude/rules/inspection-system.md` |
| `./sampling` | Node-side re-export of `supabase/functions/shared/sampling-engine.ts` (Z1.4 / ISO 2859-1 resolvers) |
diff --git a/packages/database/package.json b/packages/database/package.json
index 0ef1b7fc53..885332824b 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -24,6 +24,7 @@
"./methods": "./src/methods.ts",
"./mrp-engine": "./src/mrp-engine.ts",
"./supersession-pick": "./src/supersession-pick.ts",
+ "./picked-consumption": "./src/picked-consumption.ts",
"./datasets": "./src/datasets/index.ts",
"./event": "./src/event.ts",
"./quality": "./src/quality.ts",
diff --git a/packages/database/src/picked-consumption.ts b/packages/database/src/picked-consumption.ts
new file mode 100644
index 0000000000..96491e071c
--- /dev/null
+++ b/packages/database/src/picked-consumption.ts
@@ -0,0 +1 @@
+export * from "../supabase/functions/lib/picked-consumption.ts";
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index d8fa575a9f..942e9765c2 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -30132,6 +30132,9 @@ export default {
{
$ref: "#/parameters/rowFilter.openJobMaterialLines.dueDate"
},
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.quantityPerParent"
+ },
{
$ref: "#/parameters/select"
},
@@ -100397,6 +100400,125 @@ export default {
tags: ["(rpc) get_material_naming_details"]
}
},
+ "/rpc/get_lineside_credit": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "p_company_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_location_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_storage_unit_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_item_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_job_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_job_material_id",
+ required: true,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_lineside_credit"]
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_item_id: {
+ format: "text",
+ type: "string"
+ },
+ p_job_id: {
+ format: "text",
+ type: "string"
+ },
+ p_job_material_id: {
+ format: "text",
+ type: "string"
+ },
+ p_location_id: {
+ format: "text",
+ type: "string"
+ },
+ p_storage_unit_id: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: [
+ "p_company_id",
+ "p_location_id",
+ "p_storage_unit_id",
+ "p_item_id",
+ "p_job_id",
+ "p_job_material_id"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_lineside_credit"]
+ }
+ },
"/rpc/get_api_key_scopes": {
post: {
parameters: [
@@ -118249,6 +118371,10 @@ export default {
dueDate: {
format: "date",
type: "string"
+ },
+ quantityPerParent: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -163767,6 +163893,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.openJobMaterialLines.quantityPerParent": {
+ name: "quantityPerParent",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.workflowTriggerEvent": {
name: "workflowTriggerEvent",
description: "workflowTriggerEvent",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a70da7c666..50d394cdaf 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -70458,6 +70458,7 @@ export type Database = {
leadTime: number | null
locationId: string | null
parentMaterialId: string | null
+ quantityPerParent: number | null
quantityToIssue: number | null
replenishmentSystem:
| Database["public"]["Enums"]["itemReplenishmentSystem"]
@@ -81633,6 +81634,17 @@ export type Database = {
thumbnailPath: string
}[]
}
+ get_lineside_credit: {
+ Args: {
+ p_company_id: string
+ p_item_id: string
+ p_job_id: string
+ p_job_material_id: string
+ p_location_id: string
+ p_storage_unit_id: string
+ }
+ Returns: number
+ }
get_maintenance_dispatches_by_location: {
Args: { p_company_id: string; p_location_id: string }
Returns: {
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index d7d978e15e..95b1e39e2c 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -32,9 +32,19 @@ import { toJson } from "../lib/json.ts";
import { KyselyDatabase } from "../lib/postgres/index.ts";
import { importTypeScript } from "../lib/sandbox.ee.ts";
import { getStorageUnitId } from "../lib/storage-units.ts";
+import { effectiveReplenishment } from "../lib/mrp-engine.ts";
import {
buildSupersessionRedirectMap,
type SupersessionRow,
+ pullBackQuantities,
+ buildConsumeFirstHops,
+ buildConsumeFirstRules,
+ consumeFirstStockItems,
+ reserveConsumeFirstStock,
+ resolveMadeLinePull,
+ settleConsumeFirstLine,
+ type SupersessionContext,
+ withoutStockedConsumeFirst,
} from "../lib/supersession-pick.ts";
import { toTiptapDoc } from "../shared/tiptap.ts";
import {
@@ -523,11 +533,12 @@ serve(async (req: Request) => {
// build date, using the SAME shared logic as MRP so the job's materials
// match what planning already redirected. Applied to Buy/Pick lines in the
// mapper below.
- const supersessionRedirect = await loadSupersessionRedirect(
+ const supersessionContext = await loadSupersessionRedirect(
client,
companyId,
job.data
);
+ const supersessionRedirect = supersessionContext.redirect;
const hydratedConfiguration = await hydrateConfiguration(
client,
@@ -802,6 +813,7 @@ serve(async (req: Request) => {
}, {});
await db.transaction().execute(async (trx) => {
+ const insertedJobMaterialIds: string[] = [];
if (isConfigured) {
await trx.updateTable("job")
.set({
@@ -1364,6 +1376,7 @@ serve(async (req: Request) => {
let substitutionFactor: number | null = null;
// Captured before the swap so the revert below can undo it whole.
const quantityBeforeSupersession = quantity;
+ const methodTypeBeforeSupersession = methodType;
// Post-configuration, pre-supersession. A configuration rule may
// already have moved this line off the BOM's item, and that choice
// has to survive a failed successor lookup — see the fallback chain
@@ -1377,6 +1390,21 @@ serve(async (req: Request) => {
itemId = redirect.to;
quantity = quantity * redirect.factor;
}
+ } else {
+ const pulledFrom = resolveMadeLinePull(
+ itemId,
+ quantity,
+ supersessionContext
+ );
+ if (pulledFrom) {
+ methodType = "Pull from Inventory";
+ if (pulledFrom.itemId !== itemId) {
+ substitutedFromItemId = itemId;
+ substitutionFactor = pulledFrom.factor;
+ itemId = pulledFrom.itemId;
+ quantity = quantity * pulledFrom.factor;
+ }
+ }
}
// Fall back in order of preference: the successor, then whatever a
@@ -1426,6 +1454,7 @@ serve(async (req: Request) => {
// plausible-looking but wrong quantity nothing downstream can
// detect or repair.
quantity = quantityBeforeSupersession;
+ methodType = methodTypeBeforeSupersession;
substitutedFromItemId = null;
substitutionFactor = null;
}
@@ -1475,7 +1504,7 @@ serve(async (req: Request) => {
),
itemId,
itemType,
- kit: child.data.kit,
+ kit: methodType === "Make to Order" && child.data.kit,
methodType,
order: child.data.order,
description,
@@ -1516,7 +1545,7 @@ serve(async (req: Request) => {
let materialsWithConfiguredFields = jobMaterialResults.filter(
(m): m is NonNullable<typeof m> => m !== null
);
- const configuredChildren = validJobMaterialIndices.map(i => node.children[i]);
+ let configuredChildren = validJobMaterialIndices.map(i => node.children[i]);
const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;
let bomConfiguration: string[] | null = null;
@@ -1529,20 +1558,31 @@ serve(async (req: Request) => {
}
if (bomConfiguration) {
- // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
- materialsWithConfiguredFields = bomConfiguration
- .map((readableIdWithRevision, index) => {
- const material = materialsWithConfiguredFields.find(
- (material) => material.itemId === itemId
- );
- if (material) {
- return {
- ...material,
- order: index + 1,
- };
+ const pairByReadableId = new Map<
+ string,
+ { material: (typeof materialsWithConfiguredFields)[number]; child: MethodTreeItem }
+ >();
+ configuredChildren.forEach((child, i) => {
+ const material = materialsWithConfiguredFields[i];
+ if (!material) return;
+ const data = child.data as {
+ itemReadableId?: string | null;
+ readableIdWithRevision?: string | null;
+ };
+ for (const key of [data.readableIdWithRevision, data.itemReadableId]) {
+ if (key && !pairByReadableId.has(key)) {
+ pairByReadableId.set(key, { material, child });
}
- })
- .filter(Boolean);
+ }
+ });
+ const pairs = bomConfiguration.flatMap((readableId, index) => {
+ const pair = pairByReadableId.get(readableId);
+ return pair
+ ? [{ material: { ...pair.material, order: index + 1 }, child: pair.child }]
+ : [];
+ });
+ materialsWithConfiguredFields = pairs.map((pair) => pair.material);
+ configuredChildren = pairs.map((pair) => pair.child);
}
const madeMaterials = materialsWithConfiguredFields.filter(
@@ -1555,7 +1595,8 @@ serve(async (req: Request) => {
);
const madeChildren = configuredChildren.filter(
- (child) => child.data.methodType === "Make to Order"
+ (_, i) =>
+ materialsWithConfiguredFields[i]?.methodType === "Make to Order"
);
if (madeMaterials.length > 0) {
@@ -1563,6 +1604,7 @@ serve(async (req: Request) => {
...m,
id: nanoid(),
}));
+ insertedJobMaterialIds.push(...madeMaterialsWithIds.map((m) => m.id));
await trx
.insertInto("jobMaterial")
@@ -1650,6 +1692,7 @@ serve(async (req: Request) => {
...m,
id: (m as { id?: string }).id ?? nanoid(),
}));
+ insertedJobMaterialIds.push(...pickedWithIds.map((m) => m.id));
await trx
.insertInto("jobMaterial")
.values(
@@ -1696,6 +1739,16 @@ serve(async (req: Request) => {
assemblyOperationsToLink,
companyId
);
+
+ await settleConsumeFirstLines({
+ client,
+ trx,
+ companyId,
+ jobId: jobId,
+ jobMaterialIds: insertedJobMaterialIds,
+ locationId: job.data?.locationId,
+ asOfDate: jobBuildDate(job.data),
+ });
});
break;
@@ -1814,11 +1867,12 @@ serve(async (req: Request) => {
// reads sequentially inside the transaction holding the pool's single
// connection. The map depends only on the company and the job's build
// date, both fixed for the request, so per-node reload bought nothing.
- const supersessionRedirect = await loadSupersessionRedirect(
+ const supersessionContext = await loadSupersessionRedirect(
client,
companyId,
job.data
);
+ const supersessionRedirect = supersessionContext.redirect;
const getLaborAndOverheadRates = getRatesFromWorkCenters(
workCenters?.data
@@ -1836,6 +1890,7 @@ serve(async (req: Request) => {
}, {});
await db.transaction().execute(async (trx: Transaction) => {
+ const insertedJobMaterialIds: string[] = [];
// Delete existing jobMakeMethodOperation, jobMakeMethodMaterial
await Promise.all([
parts.billOfMaterial
@@ -2149,15 +2204,33 @@ serve(async (req: Request) => {
// Buy/Pick only — resolveJobMaterialSupersession returns null for
// Make to Order, which swapMadeSubAssembly handles during its own
// explosion.
- const supersession = await resolveJobMaterialSupersession(
- client,
- companyId,
- supersessionRedirect,
- {
- itemId: child.data.itemId,
- methodType: child.data.methodType,
- }
- );
+ const pulledFrom =
+ child.data.methodType === "Make to Order"
+ ? resolveMadeLinePull(
+ child.data.itemId,
+ child.data.quantity ?? 1,
+ supersessionContext
+ )
+ : null;
+ const methodType = pulledFrom
+ ? "Pull from Inventory"
+ : child.data.methodType;
+ const supersession =
+ pulledFrom && pulledFrom.itemId === child.data.itemId
+ ? null
+ : await resolveJobMaterialSupersession(
+ client,
+ companyId,
+ pulledFrom
+ ? new Map([
+ [
+ child.data.itemId,
+ { to: pulledFrom.itemId, factor: pulledFrom.factor },
+ ],
+ ])
+ : supersessionRedirect,
+ { itemId: child.data.itemId, methodType }
+ );
const itemId = supersession?.itemId ?? child.data.itemId;
// 1 old part = `factor` successors. The line's methodType and unit
// of measure are deliberately preserved; the factor translates the
@@ -2189,7 +2262,7 @@ serve(async (req: Request) => {
// For Make: estimatedQuantity is the good quantity (without scrap)
// For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
const childEstimatedQuantity =
- child.data.methodType === "Make to Order"
+ methodType === "Make to Order"
? childTargetQuantity
: childTotalWithScrap;
@@ -2212,9 +2285,9 @@ serve(async (req: Request) => {
methodStepsToJobSteps
),
itemId,
- kit: child.data.kit,
+ kit: methodType === "Make to Order" && child.data.kit,
itemType: supersession?.itemType ?? child.data.itemType,
- methodType: child.data.methodType,
+ methodType,
order: child.data.order,
description:
supersession?.description ?? child.data.description,
@@ -2257,17 +2330,16 @@ serve(async (req: Request) => {
const madeMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
[];
+ const madeChildren: MethodTreeItem[] = [];
const pickedOrBoughtMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
[];
for await (const child of node.children) {
- // A zero-quantity BOM line is removed from the method. `madeChildren`
- // below filters the same way, so a skipped made row stays index-aligned
- // and its sub-tree is never exploded.
if (isZeroQuantity(child.data.quantity)) continue;
const material = await mapMethodMaterialToJobMaterial(child);
- if (child.data.methodType === "Make to Order") {
+ if (material.methodType === "Make to Order") {
madeMaterials.push(material);
+ madeChildren.push(child);
} else {
pickedOrBoughtMaterials.push(material);
}
@@ -2283,6 +2355,7 @@ serve(async (req: Request) => {
...m,
id: nanoid(),
}));
+ insertedJobMaterialIds.push(...madeMaterialsWithIds.map((m) => m.id));
await trx
.insertInto("jobMaterial")
@@ -2317,12 +2390,6 @@ serve(async (req: Request) => {
.execute();
}
- const madeChildren = node.children.filter(
- (child) =>
- child.data.methodType === "Make to Order" &&
- !isZeroQuantity(child.data.quantity)
- );
-
for (const [index, child] of madeChildren.entries()) {
const materialId = madeMaterialsWithIds[index].id;
const newMakeMethodId = nanoid();
@@ -2375,6 +2442,7 @@ serve(async (req: Request) => {
...m,
id: (m as { id?: string }).id ?? nanoid(),
}));
+ insertedJobMaterialIds.push(...pickedWithIds.map((m) => m.id));
await trx
.insertInto("jobMaterial")
.values(
@@ -2420,6 +2488,16 @@ serve(async (req: Request) => {
assemblyOperationsToLink,
companyId
);
+
+ await settleConsumeFirstLines({
+ client,
+ trx,
+ companyId,
+ jobId: jobMakeMethod.data.jobId,
+ jobMaterialIds: insertedJobMaterialIds,
+ locationId: job.data?.locationId,
+ asOfDate: jobBuildDate(job.data),
+ });
});
break;
}
@@ -4356,11 +4434,8 @@ serve(async (req: Request) => {
// path does. The source job's rows were swapped live at ITS creation;
// this re-resolves as-of the TARGET job's build date, so a supersession
// that became effective since then still redirects the copy.
- const supersessionRedirect = await loadSupersessionRedirect(
- client,
- companyId,
- targetJob.data
- );
+ const { redirect: supersessionRedirect } =
+ await loadSupersessionRedirect(client, companyId, targetJob.data);
let selfConsumedItem: string | null = null;
traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {
@@ -4439,6 +4514,7 @@ serve(async (req: Request) => {
: Promise.resolve(),
]);
+ const insertedJobMaterialIds: string[] = [];
await traverseJobMethodAsync(
jobMethodTree,
async (node: JobMethodTreeItem) => {
@@ -4641,6 +4717,9 @@ serve(async (req: Request) => {
.insertInto("jobMaterial")
.values(jobMaterialInserts)
.execute();
+ insertedJobMaterialIds.push(
+ ...jobMaterialInserts.flatMap((m) => (m.id ? [m.id] : []))
+ );
}
if (parts.billOfMaterial && jobMakeMethodInserts.length > 0) {
@@ -4959,6 +5038,16 @@ serve(async (req: Request) => {
assemblyOperationsToLink,
companyId
);
+
+ await settleConsumeFirstLines({
+ client,
+ trx,
+ companyId,
+ jobId: targetJobId,
+ jobMaterialIds: insertedJobMaterialIds,
+ locationId: targetJob.data?.locationId,
+ asOfDate: jobBuildDate(targetJob.data),
+ });
});
break;
@@ -6036,11 +6125,8 @@ serve(async (req: Request) => {
// nodes issued N full-table reads sequentially inside the transaction
// holding the pool's single connection. The map depends only on the
// company and the job's build date, both fixed for the request.
- const supersessionRedirect = await loadSupersessionRedirect(
- client,
- companyId,
- job.data
- );
+ const { redirect: supersessionRedirect } =
+ await loadSupersessionRedirect(client, companyId, job.data);
const quoteMaterialIdToJobMaterialId: Record<string, string> = {};
const quoteMakeMethodIdToJobMakeMethodId: Record<string, string> = {};
@@ -6083,6 +6169,7 @@ serve(async (req: Request) => {
: Promise.resolve(),
]);
+ const insertedJobMaterialIds: string[] = [];
await traverseQuoteMethod(
quoteMethodTree,
async (node: QuoteMethodTreeItem) => {
@@ -6295,6 +6382,9 @@ serve(async (req: Request) => {
.insertInto("jobMaterial")
.values(jobMaterialInserts)
.execute();
+ insertedJobMaterialIds.push(
+ ...jobMaterialInserts.flatMap((m) => (m.id ? [m.id] : []))
+ );
}
if (parts.billOfMaterial && jobMakeMethodInserts.length > 0) {
@@ -6492,6 +6582,16 @@ serve(async (req: Request) => {
assemblyOperationsToLink,
companyId
);
+
+ await settleConsumeFirstLines({
+ client,
+ trx,
+ companyId,
+ jobId: jobId,
+ jobMaterialIds: insertedJobMaterialIds,
+ locationId: job.data?.locationId,
+ asOfDate: jobBuildDate(job.data),
+ });
});
break;
@@ -7431,8 +7531,15 @@ function jobBuildDate(
async function loadSupersessionRedirect(
client: SupabaseClient<Database>,
companyId: string,
- job: { startDate?: string | null; dueDate?: string | null } | null | undefined
-): Promise<Map<string, { to: string; factor: number }>> {
+ job:
+ | {
+ locationId?: string | null;
+ startDate?: string | null;
+ dueDate?: string | null;
+ }
+ | null
+ | undefined
+): Promise<SupersessionContext> {
// Paged, exactly like MRP's read of the same table (mrp/index.ts): a bare
// select stops at PostgREST's 1000-row `max_rows` cap and silently drops the
// rest, so a tenant past that many supersessions would redirect an arbitrary
@@ -7462,10 +7569,96 @@ async function loadSupersessionRedirect(
`Failed to load supersessions: ${supersessionRows.error.message}`
);
}
- return buildSupersessionRedirectMap(
- supersessionRows.data ?? [],
- jobBuildDate(job)
- );
+ let rows = supersessionRows.data ?? [];
+
+ const consumeFirstItemIds = rows
+ .filter((r) => r.supersessionMode === "Consume First")
+ .map((r) => r.itemId);
+ const consumeFirstOnHand = new Map<string, number>();
+ if (consumeFirstItemIds.length > 0 && job?.locationId) {
+ const [stock, items] = await Promise.all([
+ fetchAll<{ itemId: string; quantityOnHand: number | string | null }>(() =>
+ client
+ .from("itemStockQuantities")
+ .select("itemId, quantityOnHand")
+ .eq("companyId", companyId)
+ .eq("locationId", job.locationId!)
+ .in("itemId", consumeFirstItemIds)
+ .order("itemId")
+ ),
+ fetchAll<{ id: string; replenishmentSystem: string | null }>(() =>
+ client
+ .from("item")
+ .select("id, replenishmentSystem")
+ .eq("companyId", companyId)
+ .in("id", consumeFirstItemIds)
+ .order("id")
+ ),
+ ]);
+ if (stock.error) {
+ throw new Error(
+ `Failed to load predecessor stock: ${stock.error.message}`
+ );
+ }
+ if (items.error) {
+ throw new Error(
+ `Failed to load predecessor replenishment: ${items.error.message}`
+ );
+ }
+ const onHandByItem = new Map<string, number>();
+ for (const r of stock.data ?? []) {
+ onHandByItem.set(
+ r.itemId,
+ (onHandByItem.get(r.itemId) ?? 0) + Number(r.quantityOnHand ?? 0)
+ );
+ }
+ const madeItemIds = new Set(
+ (items.data ?? [])
+ .filter((i) => effectiveReplenishment(i.replenishmentSystem) === "Make")
+ .map((i) => i.id)
+ );
+ for (const id of madeItemIds) {
+ consumeFirstOnHand.set(id, onHandByItem.get(id) ?? 0);
+ }
+ rows = withoutStockedConsumeFirst(
+ rows,
+ new Set(
+ [...onHandByItem]
+ .filter(([id, onHand]) => onHand > 0 && !madeItemIds.has(id))
+ .map(([id]) => id)
+ )
+ );
+ }
+
+ const redirect = buildSupersessionRedirectMap(rows, jobBuildDate(job));
+ const consumeFirstHops = buildConsumeFirstHops(rows, jobBuildDate(job));
+ for (const id of [...consumeFirstOnHand.keys()]) {
+ if (!redirect.has(id)) consumeFirstOnHand.delete(id);
+ }
+ const boughtSuccessors = new Set<string>();
+ const successorIds = [...new Set([...redirect.values()].map((r) => r.to))];
+ if (successorIds.length > 0) {
+ const successors = await fetchAll<{ id: string; replenishmentSystem: string | null }>(
+ () =>
+ client
+ .from("item")
+ .select("id, replenishmentSystem")
+ .eq("companyId", companyId)
+ .in("id", successorIds)
+ .order("id")
+ );
+ if (successors.error) {
+ throw new Error(
+ `Failed to load successor replenishment: ${successors.error.message}`
+ );
+ }
+ for (const i of successors.data ?? []) {
+ if (effectiveReplenishment(i.replenishmentSystem) !== "Make") {
+ boughtSuccessors.add(i.id);
+ }
+ }
+ }
+ return { redirect, consumeFirstOnHand, consumeFirstHops, boughtSuccessors };
}
// EVERY jobMaterial field that is a function of WHICH ITEM the row is for, in
@@ -7628,6 +7821,138 @@ async function swapMadeSubAssembly(opts: {
return true;
}
+async function settleConsumeFirstLines(opts: {
+ client: SupabaseClient<Database>;
+ trx: Transaction<DB>;
+ companyId: string;
+ jobId: string;
+ jobMaterialIds: string[];
+ locationId: string | null | undefined;
+ asOfDate: string;
+}) {
+ const { client, trx, companyId, jobId, jobMaterialIds, locationId, asOfDate } =
+ opts;
+ if (!locationId || jobMaterialIds.length === 0) return;
+
+ const rules = await fetchAll<{
+ itemId: string;
+ successorItemId: string | null;
+ successorEffectivityDate: string | null;
+ conversionFactor: number | string | null;
+ }>(() =>
+ client
+ .from("itemSupersession")
+ .select(
+ "itemId, successorItemId, successorEffectivityDate, conversionFactor"
+ )
+ .eq("companyId", companyId)
+ .eq("supersessionMode", "Consume First")
+ .not("successorItemId", "is", null)
+ .order("itemId")
+ );
+ if (rules.error) {
+ throw new Error(`Failed to load supersessions: ${rules.error.message}`);
+ }
+ const consumeFirstRules = buildConsumeFirstRules(rules.data ?? [], asOfDate);
+ const { successorByPredecessor, predecessorsBySuccessor } = consumeFirstRules;
+ if (successorByPredecessor.size === 0) return;
+
+ const materials = await trx
+ .selectFrom("jobMaterial")
+ .select([
+ "id",
+ "itemId",
+ "quantity",
+ "estimatedQuantity",
+ "scrapQuantity",
+ "substitutedFromItemId",
+ "substitutionFactor",
+ ])
+ .where("jobId", "=", jobId)
+ .where("companyId", "=", companyId)
+ .where("id", "in", jobMaterialIds)
+ .where("methodType", "!=", "Make to Order")
+ .where((eb) =>
+ eb.or([
+ eb("quantityIssued", "is", null),
+ eb("quantityIssued", "<=", 0),
+ ])
+ )
+ .where("itemId", "in", [
+ ...new Set([
+ ...successorByPredecessor.keys(),
+ ...predecessorsBySuccessor.keys(),
+ ]),
+ ])
+ .execute();
+ if (materials.length === 0) return;
+
+ const predecessorIds = new Set<string>();
+ for (const m of materials) {
+ for (const id of consumeFirstStockItems(m, consumeFirstRules)) {
+ predecessorIds.add(id);
+ }
+ }
+ const stock = await trx
+ .selectFrom("itemStockQuantities")
+ .select(["itemId", "quantityOnHand"])
+ .where("companyId", "=", companyId)
+ .where("locationId", "=", locationId)
+ .where("itemId", "in", [...predecessorIds])
+ .execute();
+ const onHandByItem = new Map<string, number>();
+ for (const row of stock) {
+ onHandByItem.set(
+ row.itemId,
+ (onHandByItem.get(row.itemId) ?? 0) + Number(row.quantityOnHand ?? 0)
+ );
+ }
+
+ const swapLine = async (
+ m: (typeof materials)[number],
+ toItemId: string,
+ factor: number,
+ provenance: {
+ substitutedFromItemId: string | null;
+ substitutionFactor: number | null;
+ }
+ ) => {
+ const fields = await itemDerivedJobMaterialFields({
+ client,
+ trx,
+ companyId,
+ itemId: toItemId,
+ locationId,
+ });
+ if (!fields) return;
+ const quantities = pullBackQuantities(m, factor, fields.itemScrapPercentage);
+ await trx
+ .updateTable("jobMaterial")
+ .set({
+ ...fields,
+ ...quantities,
+ ...provenance,
+ })
+ .where("id", "=", m.id)
+ .execute();
+ };
+
+ materials.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+ for (const m of materials) {
+ const settlement = settleConsumeFirstLine(m, consumeFirstRules, onHandByItem);
+ reserveConsumeFirstStock(m, settlement, consumeFirstRules, onHandByItem);
+ if (!settlement) continue;
+ await swapLine(
+ m,
+ settlement.toItemId,
+ settlement.factor,
+ settlement.kind === "revert"
+ ? { substitutedFromItemId: null, substitutionFactor: null }
+ : { substitutedFromItemId: m.itemId, substitutionFactor: settlement.factor }
+ );
+ }
+}
+
// Shared by every *-ToJob path. For a Buy/Pick job-material row whose item has an
// effective supersession successor (per the redirect map), returns the successor's
// item fields so the row points at the right part with consistent tracking / type /
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 2453c296cd..c5cdeda16e 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -29,6 +29,15 @@ import {
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
import { calculateCOGS } from "../shared/calculate-cogs.ts";
+import {
+ allocateAcrossBudgets,
+ getOperationLinesideBin,
+ getPickedBudgets,
+ orderOldFirst,
+ recordSharedTakes,
+ type SharedTakes,
+ splitTakeByBin,
+} from "../lib/picked-consumption.ts";
import { resolveTrackedEntityBin } from "./resolve-tracked-entity-bin.ts";
type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
@@ -215,6 +224,11 @@ async function issueJobOperationMaterials(
const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
[];
+ const opStorageUnitId = await getOperationLinesideBin(trx, {
+ jobOperationId,
+ companyId,
+ });
+ const takenShared: SharedTakes = new Map();
for await (const material of materialsToIssue) {
// Cap the backflush at the material's remaining unissued requirement,
// mirroring backflush_job_materials. Without this, materials already
@@ -231,85 +245,122 @@ async function issueJobOperationMaterials(
if (quantityToIssue <= 0) continue;
- let proposedStorageUnitId = material.storageUnitId;
+ const budgets = orderOldFirst(
+ await getPickedBudgets(trx, {
+ material,
+ locationId: job.locationId,
+ companyId,
+ opStorageUnitId,
+ takenShared,
+ }),
+ material.itemId
+ );
+ const { takes, remaining } = allocateAcrossBudgets(
+ quantityToIssue,
+ budgets,
+ Number(material.quantity ?? 0)
+ );
+ recordSharedTakes(takenShared, takes);
+ for (const take of takes) {
+ if (!take.budget.isInventory) continue;
+ for (const row of splitTakeByBin(take)) {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: jobId,
+ documentLineId: jobOperationId,
+ companyId,
+ itemId: take.budget.itemId,
+ quantity: -row.quantity,
+ locationId: job.locationId,
+ storageUnitId: row.storageUnitId,
+ postingDate: today,
+ createdBy: userId,
+ });
+ }
+ }
- if (!proposedStorageUnitId) {
- if (material.defaultStorageUnit) {
- const pickMethod = await trx
- .selectFrom("pickMethod")
- .where("itemId", "=", material.itemId)
- .where("locationId", "=", job.locationId!)
- .where("companyId", "=", companyId)
- .select("defaultStorageUnitId")
- .executeTakeFirst();
+ if (remaining > 0) {
+ let proposedStorageUnitId = material.storageUnitId;
- proposedStorageUnitId = pickMethod?.defaultStorageUnitId;
+ if (!proposedStorageUnitId) {
+ if (material.defaultStorageUnit) {
+ const pickMethod = await trx
+ .selectFrom("pickMethod")
+ .where("itemId", "=", material.itemId)
+ .where("locationId", "=", job.locationId!)
+ .where("companyId", "=", companyId)
+ .select("defaultStorageUnitId")
+ .executeTakeFirst();
+
+ proposedStorageUnitId = pickMethod?.defaultStorageUnitId;
- if (!proposedStorageUnitId) {
+ if (!proposedStorageUnitId) {
+ proposedStorageUnitId = await getStorageUnitWithHighestQuantity(
+ trx,
+ material.itemId,
+ job.locationId!
+ );
+ }
+ } else {
proposedStorageUnitId = await getStorageUnitWithHighestQuantity(
trx,
material.itemId,
job.locationId!
);
}
- } else {
- proposedStorageUnitId = await getStorageUnitWithHighestQuantity(
- trx,
- material.itemId,
- job.locationId!
- );
}
- }
- const currentStorageUnitQuantity = await trx
- .selectFrom("itemLedger")
- .select((eb) => eb.fn.sum("quantity").as("quantity"))
- .where("itemId", "=", material.itemId)
- .where("locationId", "=", job.locationId!)
- .where("storageUnitId", "=", proposedStorageUnitId ?? "")
- .executeTakeFirst();
+ const currentStorageUnitQuantity = await trx
+ .selectFrom("itemLedger")
+ .select((eb) => eb.fn.sum("quantity").as("quantity"))
+ .where("itemId", "=", material.itemId)
+ .where("locationId", "=", job.locationId!)
+ .where("storageUnitId", "=", proposedStorageUnitId ?? "")
+ .executeTakeFirst();
- const allStorageUnitQuantities = await trx
- .selectFrom("itemLedger")
- .select([
- "storageUnitId",
- (eb) => eb.fn.sum("quantity").as("quantity"),
- ])
- .where("itemId", "=", material.itemId)
- .where("locationId", "=", job.locationId!)
- .groupBy("storageUnitId")
- .having((eb) => eb.fn.sum("quantity"), ">", 0)
- .execute();
+ const allStorageUnitQuantities = await trx
+ .selectFrom("itemLedger")
+ .select([
+ "storageUnitId",
+ (eb) => eb.fn.sum("quantity").as("quantity"),
+ ])
+ .where("itemId", "=", material.itemId)
+ .where("locationId", "=", job.locationId!)
+ .groupBy("storageUnitId")
+ .having((eb) => eb.fn.sum("quantity"), ">", 0)
+ .execute();
- let finalStorageUnitId = proposedStorageUnitId;
- const currentQuantity = Number(currentStorageUnitQuantity?.quantity ?? 0);
+ let finalStorageUnitId = proposedStorageUnitId;
+ const currentQuantity = Number(currentStorageUnitQuantity?.quantity ?? 0);
- if (
- currentQuantity < quantityToIssue &&
- allStorageUnitQuantities.length > 0
- ) {
- const bestStorageUnit = allStorageUnitQuantities.reduce((best, current) =>
- Number(current.quantity) > Number(best.quantity) ? current : best
- );
- finalStorageUnitId = bestStorageUnit.storageUnitId ?? null;
- }
+ if (
+ currentQuantity < remaining &&
+ allStorageUnitQuantities.length > 0
+ ) {
+ const bestStorageUnit = allStorageUnitQuantities.reduce((best, current) =>
+ Number(current.quantity) > Number(best.quantity) ? current : best
+ );
+ finalStorageUnitId = bestStorageUnit.storageUnitId ?? null;
+ }
- const isTracked = itemIdIsTracked.get(material.itemId);
+ const isTracked = itemIdIsTracked.get(material.itemId);
- if (isTracked) {
- itemLedgerInserts.push({
- entryType: "Consumption",
- documentType: "Job Consumption",
- documentId: jobId,
- documentLineId: jobOperationId,
- companyId,
- itemId: material.itemId,
- quantity: -quantityToIssue,
- locationId: job.locationId,
- storageUnitId: finalStorageUnitId,
- postingDate: today,
- createdBy: userId,
- });
+ if (isTracked) {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: jobId,
+ documentLineId: jobOperationId,
+ companyId,
+ itemId: material.itemId,
+ quantity: -remaining,
+ locationId: job.locationId,
+ storageUnitId: finalStorageUnitId,
+ postingDate: today,
+ createdBy: userId,
+ });
+ }
}
await trx
@@ -1992,25 +2043,62 @@ serve(async (req: Request) => {
? Number(quantity)
: Number(quantity) - Number(material?.quantityIssued); // set quantity
- if (
- material?.methodType !== "Make to Order" &&
- item?.itemTrackingType === "Inventory"
- ) {
- itemLedgerInserts.push({
- entryType: "Consumption",
- documentType: "Job Consumption",
- documentId: material?.jobId,
- documentLineId: id,
- companyId,
- itemId: material?.itemId!,
- locationId: job?.locationId,
- storageUnitId,
- quantity:
- adjustmentType === "Positive Adjmt."
- ? Number(quantityToIssue)
- : -Number(quantityToIssue),
- createdBy: userId,
- });
+ if (material && material.methodType !== "Make to Order") {
+ let remaining = Number(quantityToIssue);
+ if (adjustmentType !== "Positive Adjmt." && remaining > 0) {
+ const budgets = orderOldFirst(
+ await getPickedBudgets(trx, {
+ material,
+ locationId: job?.locationId!,
+ companyId,
+ opStorageUnitId: await getOperationLinesideBin(trx, {
+ jobOperationId: material.jobOperationId,
+ companyId,
+ }),
+ }),
+ material.itemId
+ );
+ const allocation = allocateAcrossBudgets(
+ remaining,
+ budgets,
+ Number(material.quantity ?? 0)
+ );
+ remaining = allocation.remaining;
+ for (const take of allocation.takes) {
+ if (!take.budget.isInventory) continue;
+ for (const row of splitTakeByBin(take)) {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: material.jobId,
+ documentLineId: id,
+ companyId,
+ itemId: take.budget.itemId,
+ locationId: job?.locationId,
+ storageUnitId: row.storageUnitId,
+ quantity: -row.quantity,
+ createdBy: userId,
+ });
+ }
+ }
+ }
+ if (item?.itemTrackingType === "Inventory" && remaining !== 0) {
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: material.jobId,
+ documentLineId: id,
+ companyId,
+ itemId: material.itemId,
+ locationId: job?.locationId,
+ storageUnitId,
+ quantity:
+ adjustmentType === "Positive Adjmt."
+ ? Number(remaining)
+ : -Number(remaining),
+ createdBy: userId,
+ });
+ }
}
await trx
diff --git a/packages/database/supabase/functions/lib/mrp-engine.test.ts b/packages/database/supabase/functions/lib/mrp-engine.test.ts
index a480153f13..dc03c5878c 100644
--- a/packages/database/supabase/functions/lib/mrp-engine.test.ts
+++ b/packages/database/supabase/functions/lib/mrp-engine.test.ts
@@ -5,6 +5,7 @@ import {
import {
computeLowLevelCodes,
explodeBom,
+ netConsumeFirstContributors,
makeActualKey,
makeKey,
makeLocationItemKey,
@@ -193,3 +194,428 @@ Deno.test("a clean parent still explodes onto a cycle item, but nothing explodes
// cyc1 is a leaf, so no phantom demand is manufactured around the loop.
assertEquals(bomDerivedDemand.get(makeKey(loc, "p1", "cyc2")), undefined);
});
+
+
+Deno.test("Consume First made predecessor: stock covers first, only the successor's BOM explodes for the shortfall", () => {
+ const top = "top", oldPart = "old-bracket", newPart = "new-bracket";
+ const plateA = "plate-a", plateB = "plate-b";
+ const location = "loc";
+ const periods = [{ id: "p1" }];
+ const noLead = new Map([
+ [oldPart, 0],
+ [newPart, 0],
+ [plateA, 0],
+ [plateB, 0],
+ ]);
+
+ const bomByItem = new Map<string, BomChild[]>([
+ [top, [{ itemId: oldPart, quantity: 1, methodType: "Pull from Inventory" }]],
+ [oldPart, [{ itemId: plateA, quantity: 1, methodType: "Purchase to Order" }]],
+ [newPart, [{ itemId: plateB, quantity: 1, methodType: "Purchase to Order" }]],
+ ]);
+
+ const { bomDerivedDemand, demandContributors } = explodeBom({
+ grossDemand: new Map([[makeKey(location, "p1", top), 10]]),
+ bomByItem,
+ replenishmentSystemByItem: new Map([
+ [top, "Make"],
+ [oldPart, "Make"],
+ [newPart, "Make"],
+ [plateA, "Buy"],
+ [plateB, "Buy"],
+ ]),
+ leadTimeByItem: noLead,
+ periods,
+ onHandByLocationItem: new Map([
+ [makeLocationItemKey(location, oldPart), 3],
+ ]),
+ jobSupplyByLocationPeriodItem: new Map(),
+ topLevelContributors: new Map([
+ [
+ makeKey(location, "p1", top),
+ [
+ {
+ sourceType: "Sales Order" as const,
+ salesOrderLineId: "so-1",
+ parentItemId: top,
+ quantity: 10,
+ },
+ ],
+ ],
+ ]),
+ consumeFirstRedirect: new Map([[oldPart, { to: newPart, factor: 1 }]]),
+ });
+
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", oldPart)), 3);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", newPart)), 7);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", plateB)), 7);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", plateA)), undefined);
+ const moved = demandContributors.get(makeKey(location, "p1", newPart)) ?? [];
+ assertEquals(moved.length, 1);
+ assertEquals(moved[0]!.quantity, 7);
+ assertEquals(moved[0]!.redirectedFromItemId, oldPart);
+ const plateBContributors =
+ demandContributors.get(makeKey(location, "p1", plateB)) ?? [];
+ assertEquals(plateBContributors[0]!.redirectedFromItemId, oldPart);
+});
+
+Deno.test("Consume First nets in whole assemblies per contributor and converts the shortfall by the factor", () => {
+ const top = "top", oldPart = "old", newPart = "new";
+ const location = "loc";
+ const periods = [{ id: "p1" }];
+
+ const bomByItem = new Map<string, BomChild[]>([
+ [top, [{ itemId: oldPart, quantity: 2, methodType: "Pull from Inventory" }]],
+ ]);
+
+ const { bomDerivedDemand, demandContributors } = explodeBom({
+ grossDemand: new Map([[makeKey(location, "p1", top), 5]]),
+ bomByItem,
+ replenishmentSystemByItem: new Map([
+ [top, "Make"],
+ [oldPart, "Buy"],
+ [newPart, "Buy"],
+ ]),
+ leadTimeByItem: new Map([[oldPart, 0]]),
+ periods,
+ onHandByLocationItem: new Map([
+ [makeLocationItemKey(location, oldPart), 3],
+ ]),
+ jobSupplyByLocationPeriodItem: new Map(),
+ topLevelContributors: new Map([
+ [
+ makeKey(location, "p1", top),
+ [
+ {
+ sourceType: "Job Material" as const,
+ jobId: "job-1",
+ parentItemId: top,
+ quantity: 5,
+ },
+ ],
+ ],
+ ]),
+ consumeFirstRedirect: new Map([[oldPart, { to: newPart, factor: 2 }]]),
+ });
+
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", oldPart)), 2);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", newPart)), 16);
+ const kept = demandContributors.get(makeKey(location, "p1", oldPart)) ?? [];
+ assertEquals(kept.map((c) => c.quantity), [2]);
+ const moved = demandContributors.get(makeKey(location, "p1", newPart)) ?? [];
+ assertEquals(moved.map((c) => c.quantity), [16]);
+});
+
+Deno.test("a Consume First successor that sits shallower in another BOM still receives the redirected demand", () => {
+ const top = "top", sub = "sub", other = "other";
+ const oldPart = "old", newPart = "new", plateB = "plate-b";
+ const location = "loc";
+ const periods = [{ id: "p1" }];
+
+ const bomByItem = new Map<string, BomChild[]>([
+ [top, [{ itemId: sub, quantity: 1, methodType: "Make to Order" }]],
+ [sub, [{ itemId: oldPart, quantity: 1, methodType: "Pull from Inventory" }]],
+ [other, [{ itemId: newPart, quantity: 1, methodType: "Pull from Inventory" }]],
+ [newPart, [{ itemId: plateB, quantity: 1, methodType: "Purchase to Order" }]],
+ ]);
+
+ const { bomDerivedDemand } = explodeBom({
+ grossDemand: new Map([[makeKey(location, "p1", top), 4]]),
+ bomByItem,
+ replenishmentSystemByItem: new Map([
+ [top, "Make"],
+ [sub, "Make"],
+ [other, "Make"],
+ [oldPart, "Make"],
+ [newPart, "Make"],
+ [plateB, "Buy"],
+ ]),
+ leadTimeByItem: new Map([
+ [sub, 0],
+ [oldPart, 0],
+ [newPart, 0],
+ [plateB, 0],
+ ]),
+ periods,
+ onHandByLocationItem: new Map(),
+ jobSupplyByLocationPeriodItem: new Map(),
+ topLevelContributors: new Map(),
+ consumeFirstRedirect: new Map([[oldPart, { to: newPart, factor: 1 }]]),
+ });
+
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", oldPart)), undefined);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", newPart)), 4);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", plateB)), 4);
+});
+
+Deno.test("Consume First: a bought successor of inline made demand is planned as forecast", () => {
+ const top = "top", oldPart = "old", newPart = "new";
+ const location = "loc";
+ const periods = [{ id: "p1" }];
+
+ const bomByItem = new Map<string, BomChild[]>([
+ [top, [{ itemId: oldPart, quantity: 1, methodType: "Make to Order" }]],
+ ]);
+
+ const { bomDerivedDemand } = explodeBom({
+ grossDemand: new Map([[makeKey(location, "p1", top), 6]]),
+ bomByItem,
+ replenishmentSystemByItem: new Map([
+ [top, "Make"],
+ [oldPart, "Make"],
+ [newPart, "Buy"],
+ ]),
+ leadTimeByItem: new Map([[oldPart, 0]]),
+ periods,
+ onHandByLocationItem: new Map([[makeLocationItemKey(location, oldPart), 2]]),
+ jobSupplyByLocationPeriodItem: new Map(),
+ topLevelContributors: new Map(),
+ consumeFirstRedirect: new Map([[oldPart, { to: newPart, factor: 1 }]]),
+ });
+
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", oldPart)), undefined);
+ assertEquals(bomDerivedDemand.get(makeKey(location, "p1", newPart)), 4);
+});
+
+
+function trialBom() {
+ return new Map<string, BomChild[]>([
+ ["top", [{ itemId: "old", quantity: 1, methodType: "Pull from Inventory" }]],
+ ["old", [{ itemId: "plate-a", quantity: 1, methodType: "Purchase to Order" }]],
+ ["new", [{ itemId: "plate-b", quantity: 1, methodType: "Purchase to Order" }]],
+ ]);
+}
+const trialReplenishment = () =>
+ new Map<string, "Make" | "Buy">([
+ ["top", "Make"],
+ ["old", "Make"],
+ ["new", "Make"],
+ ["plate-a", "Buy"],
+ ["plate-b", "Buy"],
+ ]);
+const noLead = () =>
+ new Map([["old", 0], ["new", 0], ["plate-a", 0], ["plate-b", 0], ["sub", 0]]);
+
+function runTrial(args: {
+ demand: number;
+ oldOnHand?: number;
+ oldSupply?: number;
+ bomByItem?: Map<string, BomChild[]>;
+ replenishment?: Map<string, "Make" | "Buy">;
+}) {
+ const location = "loc";
+ const key = (item: string) => makeKey(location, "p1", item);
+ const out = explodeBom({
+ grossDemand: new Map([[key("top"), args.demand]]),
+ bomByItem: args.bomByItem ?? trialBom(),
+ replenishmentSystemByItem: args.replenishment ?? trialReplenishment(),
+ leadTimeByItem: noLead(),
+ periods: [{ id: "p1" }],
+ onHandByLocationItem: new Map([
+ [makeLocationItemKey(location, "old"), args.oldOnHand ?? 0],
+ ]),
+ jobSupplyByLocationPeriodItem: new Map(
+ args.oldSupply ? [[key("old"), args.oldSupply]] : []
+ ),
+ topLevelContributors: new Map([
+ [
+ key("top"),
+ [
+ {
+ sourceType: "Sales Order" as const,
+ salesOrderLineId: "so-1",
+ parentItemId: "top",
+ quantity: args.demand,
+ },
+ ],
+ ],
+ ]),
+ consumeFirstRedirect: new Map([["old", { to: "new", factor: 1 }]]),
+ });
+ const q = (item: string) => out.bomDerivedDemand.get(key(item));
+ return { q };
+}
+
+Deno.test("case 6: no old stock — everything is built as NEW", () => {
+ const { q } = runTrial({ demand: 10, oldOnHand: 0 });
+ assertEquals(q("old"), undefined);
+ assertEquals(q("new"), 10);
+ assertEquals(q("plate-b"), 10);
+ assertEquals(q("plate-a"), undefined);
+});
+
+Deno.test("case 7: old stock covers everything — nothing moves to NEW", () => {
+ const { q } = runTrial({ demand: 10, oldOnHand: 12 });
+ assertEquals(q("old"), 10);
+ assertEquals(q("new"), undefined);
+ assertEquals(q("plate-b"), undefined);
+ assertEquals(q("plate-a"), undefined);
+});
+
+Deno.test("case 16: an open job producing OLD counts as available before redirecting", () => {
+ const { q } = runTrial({ demand: 10, oldOnHand: 0, oldSupply: 4 });
+ assertEquals(q("old"), 4);
+ assertEquals(q("new"), 6);
+ assertEquals(q("plate-b"), 6);
+});
+
+Deno.test("case 11: bought predecessor and successor net the same way and never explode", () => {
+ const replenishment = trialReplenishment();
+ replenishment.set("old", "Buy");
+ replenishment.set("new", "Buy");
+ const { q } = runTrial({ demand: 10, oldOnHand: 3, replenishment });
+ assertEquals(q("old"), 3);
+ assertEquals(q("new"), 7);
+ assertEquals(q("plate-a"), undefined);
+ assertEquals(q("plate-b"), undefined);
+});
+
+Deno.test("nested: a Consume First sub-sub-assembly nets its stock two levels down", () => {
+ const bomByItem = new Map<string, BomChild[]>([
+ ["top", [{ itemId: "sub", quantity: 1, methodType: "Make to Order" }]],
+ ["sub", [{ itemId: "old", quantity: 2, methodType: "Pull from Inventory" }]],
+ ["old", [{ itemId: "plate-a", quantity: 1, methodType: "Purchase to Order" }]],
+ ["new", [{ itemId: "plate-b", quantity: 1, methodType: "Purchase to Order" }]],
+ ]);
+ const replenishment = trialReplenishment();
+ replenishment.set("sub", "Make");
+ const { q } = runTrial({ demand: 4, oldOnHand: 5, bomByItem, replenishment });
+ assertEquals(q("old"), 4);
+ assertEquals(q("new"), 4);
+ assertEquals(q("plate-b"), 4);
+ assertEquals(q("plate-a"), undefined);
+});
+
+Deno.test("fix 3: the successor's shortfall is pulled earlier by its own longer lead time, never later", () => {
+ const location = "loc";
+ const key = (item: string, p: string) => makeKey(location, p, item);
+ const run = (leads: Record<string, number>) =>
+ explodeBom({
+ grossDemand: new Map([[key("top", "p3"), 4]]),
+ bomByItem: trialBom(),
+ replenishmentSystemByItem: trialReplenishment(),
+ leadTimeByItem: new Map(Object.entries({ "plate-a": 0, "plate-b": 0, ...leads })),
+ periods: [{ id: "p0" }, { id: "p1" }, { id: "p2" }, { id: "p3" }],
+ onHandByLocationItem: new Map(),
+ jobSupplyByLocationPeriodItem: new Map(),
+ topLevelContributors: new Map(),
+ consumeFirstRedirect: new Map([["old", { to: "new", factor: 1 }]]),
+ }).bomDerivedDemand;
+
+ const slower = run({ old: 7, new: 14 });
+ assertEquals(slower.get(key("new", "p1")), 4);
+ assertEquals(slower.get(key("new", "p2")), undefined);
+
+ const faster = run({ old: 14, new: 7 });
+ assertEquals(faster.get(key("new", "p1")), 4);
+ assertEquals(faster.get(key("new", "p2")), undefined);
+});
+
+Deno.test("fix 2: a Consume First chain uses the middle part's stock before moving on", () => {
+ const location = "loc";
+ const key = (item: string) => makeKey(location, "p1", item);
+ const bomByItem = new Map<string, BomChild[]>([
+ ["top", [{ itemId: "old", quantity: 1, methodType: "Pull from Inventory" }]],
+ ["old", [{ itemId: "plate-a", quantity: 1, methodType: "Purchase to Order" }]],
+ ["mid", [{ itemId: "plate-m", quantity: 1, methodType: "Purchase to Order" }]],
+ ["new", [{ itemId: "plate-b", quantity: 1, methodType: "Purchase to Order" }]],
+ ]);
+ const { bomDerivedDemand } = explodeBom({
+ grossDemand: new Map([[key("top"), 10]]),
+ bomByItem,
+ replenishmentSystemByItem: new Map([
+ ["top", "Make"], ["old", "Make"], ["mid", "Make"], ["new", "Make"],
+ ["plate-a", "Buy"], ["plate-m", "Buy"], ["plate-b", "Buy"],
+ ]),
+ leadTimeByItem: new Map([["old", 0], ["mid", 0], ["new", 0], ["plate-a", 0], ["plate-m", 0], ["plate-b", 0]]),
+ periods: [{ id: "p1" }],
+ onHandByLocationItem: new Map([
+ [makeLocationItemKey(location, "old"), 2],
+ [makeLocationItemKey(location, "mid"), 3],
+ ]),
+ jobSupplyByLocationPeriodItem: new Map(),
+ topLevelContributors: new Map(),
+ consumeFirstRedirect: new Map([
+ ["old", { to: "mid", factor: 1 }],
+ ["mid", { to: "new", factor: 1 }],
+ ]),
+ });
+ assertEquals(bomDerivedDemand.get(key("old")), 2);
+ assertEquals(bomDerivedDemand.get(key("mid")), 3);
+ assertEquals(bomDerivedDemand.get(key("new")), 5);
+ assertEquals(bomDerivedDemand.get(key("plate-b")), 5);
+ assertEquals(bomDerivedDemand.get(key("plate-m")), undefined);
+ assertEquals(bomDerivedDemand.get(key("plate-a")), undefined);
+});
+
+Deno.test("netConsumeFirstContributors nets each job line in whole assemblies and the rest by the unit", () => {
+ const job = (jobId: string, quantity: number, perAssemblyQuantity?: number) => ({
+ sourceType: "Job Material" as const,
+ jobId,
+ parentItemId: "asm",
+ quantity,
+ perAssemblyQuantity,
+ });
+ const out = netConsumeFirstContributors({
+ itemId: "old",
+ contributors: [job("j1", 4, 2), job("j2", 3)],
+ grossQty: 7,
+ running: 3,
+ factor: 1,
+ perAssemblyOf: (c) => c.perAssemblyQuantity ?? 0,
+ });
+ assertEquals(out.consumed, 3);
+ assertEquals(out.running, 0);
+ assertEquals(out.kept.map((c) => c.quantity), [2, 1]);
+ assertEquals(out.moved.map((c) => [c.quantity, c.redirectedFromItemId]), [
+ [2, "old"],
+ [2, "old"],
+ ]);
+});
+
+Deno.test("netConsumeFirstContributors nets demand no contributor accounts for by the unit, after the lines", () => {
+ const out = netConsumeFirstContributors({
+ itemId: "old",
+ contributors: [
+ { sourceType: "Sales Order", salesOrderLineId: "s1", parentItemId: "asm", quantity: 2, perAssemblyQuantity: 2 },
+ ],
+ grossQty: 5,
+ running: 3,
+ factor: 2,
+ perAssemblyOf: (c) => c.perAssemblyQuantity ?? 0,
+ });
+ assertEquals(out.consumed, 3);
+ assertEquals(out.kept.map((c) => c.quantity), [2]);
+ assertEquals(out.moved, []);
+ assertEquals(out.running, 0);
+});
+
+Deno.test("netConsumeFirstContributors keeps the origin and converts the per-assembly quantity when moving", () => {
+ const out = netConsumeFirstContributors({
+ itemId: "mid",
+ contributors: [
+ {
+ sourceType: "Job Material",
+ jobId: "j1",
+ parentItemId: "asm",
+ quantity: 4,
+ perAssemblyQuantity: 2,
+ redirectedFromItemId: "old",
+ },
+ ],
+ grossQty: 4,
+ running: 0,
+ factor: 3,
+ perAssemblyOf: (c) => c.perAssemblyQuantity ?? 0,
+ });
+ assertEquals(out.moved, [
+ {
+ sourceType: "Job Material",
+ jobId: "j1",
+ parentItemId: "asm",
+ quantity: 12,
+ perAssemblyQuantity: 6,
+ redirectedFromItemId: "old",
+ },
+ ]);
+});
diff --git a/packages/database/supabase/functions/lib/mrp-engine.ts b/packages/database/supabase/functions/lib/mrp-engine.ts
index d951ea0f1d..bd4a01cbe3 100644
--- a/packages/database/supabase/functions/lib/mrp-engine.ts
+++ b/packages/database/supabase/functions/lib/mrp-engine.ts
@@ -1,5 +1,11 @@
// Pure MRP engine functions shared across Supabase edge functions.
+import {
+ consumableInWholeAssemblies,
+ type Redirect,
+} from "./supersession-pick.ts";
+import { round, RoundingMode } from "../shared/precision.ts";
+
export type MethodType =
| "Make to Order"
| "Pull from Inventory"
@@ -20,6 +26,7 @@ type DemandContributorBase = {
quantity: number;
// The discontinued part this demand was redirected from, if any.
redirectedFromItemId?: string;
+ perAssemblyQuantity?: number;
};
export type DemandContributor =
@@ -45,6 +52,7 @@ export type BomExplosionInput = {
onHandByLocationItem: Map<string, number>;
jobSupplyByLocationPeriodItem: Map<string, number>;
topLevelContributors: Map<string, DemandContributor[]>;
+ consumeFirstRedirect?: Map<string, Redirect>;
};
export type BomExplosionOutput = {
@@ -101,7 +109,7 @@ export function splitActualKey(
return [parts[0]!, parts[1]!, parts[2]!, parts[3]!];
}
-function effectiveReplenishment(
+export function effectiveReplenishment(
repSys: ReplenishmentSystem | undefined
): "Buy" | "Make" | undefined {
return repSys === "Buy and Make"
@@ -183,8 +191,24 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {
const bomDerivedDemand = new Map<string, number>();
const demandContributors = new Map<string, DemandContributor[]>();
+ const consumeFirstRedirect =
+ input.consumeFirstRedirect ?? new Map<string, Redirect>();
+
+ const levelingBom =
+ consumeFirstRedirect.size === 0
+ ? bomByItem
+ : (() => {
+ const withEdges = new Map(bomByItem);
+ for (const [oldItemId, { to }] of consumeFirstRedirect) {
+ withEdges.set(oldItemId, [
+ ...(withEdges.get(oldItemId) ?? []),
+ { itemId: to, quantity: 0, methodType: "Pull from Inventory" },
+ ]);
+ }
+ return withEdges;
+ })();
- const { llc, cycleItemIds } = computeLowLevelCodes(bomByItem);
+ const { llc, cycleItemIds } = computeLowLevelCodes(levelingBom);
// A cycle cannot be leveled (rose seeds -> rose -> bouquet -> rose seeds is
// real production data). Failing the whole company's run for one corrupt
@@ -248,6 +272,39 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {
const grossQty = grossDemand.get(periodKey) ?? 0;
if (grossQty <= 0) continue;
+ const redirect = consumeFirstRedirect.get(itemId);
+ if (redirect) {
+ const weeks = (id: string) =>
+ round((leadTimeByItem.get(id) ?? 7) / 7, 0, RoundingMode.Up);
+ const currentPeriodIndex = periodIndexById.get(period.id) ?? 0;
+ const successorPeriodIndex = Math.max(
+ 0,
+ Math.min(
+ currentPeriodIndex,
+ currentPeriodIndex + weeks(itemId) - weeks(redirect.to)
+ )
+ );
+ const successorPeriod =
+ periods[successorPeriodIndex] ?? period;
+ running = redirectConsumeFirstShortfall({
+ itemId,
+ periodKey,
+ successorKey: makeKey(locationId, successorPeriod.id, redirect.to),
+ factor: redirect.factor,
+ grossQty,
+ running,
+ successorIsMake:
+ effectiveReplenishment(
+ replenishmentSystemByItem.get(redirect.to)
+ ) === "Make",
+ bomByItem,
+ grossDemand,
+ bomDerivedDemand,
+ demandContributors,
+ });
+ continue;
+ }
+
const netRequirement = Math.max(0, grossQty - Math.max(0, running));
running = Math.max(0, running - grossQty);
@@ -306,6 +363,7 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {
// demand can be shown as "redirected from <old part>".
redirectedFromItemId:
child.redirectedFromItemId ?? pc.redirectedFromItemId,
+ perAssemblyQuantity: child.quantity,
});
}
demandContributors.set(childKey, childContributors);
@@ -321,3 +379,130 @@ export function explodeBom(input: BomExplosionInput): BomExplosionOutput {
return { grossDemand, bomDerivedDemand, demandContributors, cycleItemIds };
}
+
+export function netConsumeFirstContributors(args: {
+ itemId: string;
+ contributors: DemandContributor[];
+ grossQty: number;
+ running: number;
+ factor: number;
+ perAssemblyOf: (c: DemandContributor) => number;
+}): {
+ kept: DemandContributor[];
+ moved: DemandContributor[];
+ consumed: number;
+ running: number;
+} {
+ const { itemId, contributors, grossQty, factor, perAssemblyOf } = args;
+ let running = Math.max(0, args.running);
+ const kept: DemandContributor[] = [];
+ const moved: DemandContributor[] = [];
+ let attributed = 0;
+ let consumed = 0;
+ for (const c of contributors) {
+ const take = Math.min(
+ c.quantity,
+ consumableInWholeAssemblies(running, perAssemblyOf(c))
+ );
+ running -= take;
+ attributed += c.quantity;
+ consumed += take;
+ if (take > 0) kept.push({ ...c, quantity: take });
+ if (c.quantity - take > 0) {
+ moved.push({
+ ...c,
+ quantity: (c.quantity - take) * factor,
+ redirectedFromItemId: c.redirectedFromItemId ?? itemId,
+ perAssemblyQuantity:
+ c.perAssemblyQuantity == null
+ ? undefined
+ : c.perAssemblyQuantity * factor,
+ });
+ }
+ }
+ const unattributed = Math.max(0, grossQty - attributed);
+ const unitTake = Math.min(running, unattributed);
+ running -= unitTake;
+ consumed += unitTake;
+ return { kept, moved, consumed, running };
+}
+
+function redirectConsumeFirstShortfall(args: {
+ itemId: string;
+ periodKey: string;
+ successorKey: string;
+ factor: number;
+ grossQty: number;
+ running: number;
+ successorIsMake: boolean;
+ bomByItem: Map<string, BomChild[]>;
+ grossDemand: Map<string, number>;
+ bomDerivedDemand: Map<string, number>;
+ demandContributors: Map<string, DemandContributor[]>;
+}): number {
+ const {
+ itemId,
+ periodKey,
+ successorKey,
+ factor,
+ grossQty,
+ successorIsMake,
+ bomByItem,
+ grossDemand,
+ bomDerivedDemand,
+ demandContributors,
+ } = args;
+
+ const contributors = demandContributors.get(periodKey) ?? [];
+ const { kept, moved, consumed, running } = netConsumeFirstContributors({
+ itemId,
+ contributors,
+ grossQty,
+ running: args.running,
+ factor,
+ perAssemblyOf: (c) =>
+ c.perAssemblyQuantity ??
+ bomByItem
+ .get(c.parentItemId)
+ ?.find((child) => child.itemId === itemId)?.quantity ??
+ 0,
+ });
+
+ const shortfall = grossQty - consumed;
+ if (shortfall <= 0) return running;
+
+ const keptShare = consumed / grossQty;
+ const derivedOld = bomDerivedDemand.get(periodKey) ?? 0;
+ const keptDerived = derivedOld * keptShare;
+ if (keptDerived > 0) {
+ bomDerivedDemand.set(periodKey, keptDerived);
+ } else {
+ bomDerivedDemand.delete(periodKey);
+ }
+ grossDemand.set(
+ successorKey,
+ (grossDemand.get(successorKey) ?? 0) + shortfall * factor
+ );
+ const movedDerived = successorIsMake
+ ? (derivedOld - keptDerived) * factor
+ : shortfall * factor;
+ if (movedDerived > 0) {
+ bomDerivedDemand.set(
+ successorKey,
+ (bomDerivedDemand.get(successorKey) ?? 0) + movedDerived
+ );
+ }
+
+ if (contributors.length > 0) {
+ if (kept.length > 0) {
+ demandContributors.set(periodKey, kept);
+ } else {
+ demandContributors.delete(periodKey);
+ }
+ demandContributors.set(
+ successorKey,
+ (demandContributors.get(successorKey) ?? []).concat(moved)
+ );
+ }
+ return running;
+}
diff --git a/packages/database/supabase/functions/lib/picked-consumption.test.ts b/packages/database/supabase/functions/lib/picked-consumption.test.ts
new file mode 100644
index 0000000000..745187bf5b
--- /dev/null
+++ b/packages/database/supabase/functions/lib/picked-consumption.test.ts
@@ -0,0 +1,219 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ allocateAcrossBudgets,
+ orderOldFirst,
+ type PickedBudget,
+ pickFactor,
+ linesideCredit,
+ recordSharedTakes,
+ sharedTakeKey,
+ type SharedTakes,
+ splitTakeByBin,
+} from "./picked-consumption.ts";
+
+const budget = (overrides: Partial<PickedBudget>): PickedBudget => {
+ const own = overrides.own ?? overrides.available ?? 0;
+ const unclaimed = overrides.unclaimed ?? 0;
+ return {
+ itemId: "OLD",
+ factor: 1,
+ storageUnitId: "shelf",
+ sharedStorageUnitId: "shelf",
+ isInventory: true,
+ isPredecessor: false,
+ ...overrides,
+ own,
+ unclaimed,
+ available: own + unclaimed,
+ };
+};
+
+Deno.test("orderOldFirst puts predecessors before the line item, then the rest", () => {
+ const ordered = orderOldFirst(
+ [
+ budget({ itemId: "NEW" }),
+ budget({ itemId: "LINE" }),
+ budget({ itemId: "OLD", isPredecessor: true }),
+ ],
+ "LINE"
+ );
+ assertEquals(
+ ordered.map((b) => b.itemId),
+ ["OLD", "LINE", "NEW"]
+ );
+});
+
+Deno.test("allocateAcrossBudgets consumes the predecessor first, then the successor", () => {
+ const { takes, remaining } = allocateAcrossBudgets(4, [
+ budget({ itemId: "OLD", available: 3 }),
+ budget({ itemId: "NEW", available: 1 }),
+ ]);
+ assertEquals(
+ takes.map((t) => [t.budget.itemId, t.quantity]),
+ [
+ ["OLD", 3],
+ ["NEW", 1],
+ ]
+ );
+ assertEquals(remaining, 0);
+});
+
+Deno.test("allocateAcrossBudgets converts by the factor and reports the shortfall", () => {
+ const { takes, remaining } = allocateAcrossBudgets(4, [
+ budget({ itemId: "OLD", available: 2 }),
+ budget({ itemId: "NEW", factor: 2, available: 2 }),
+ ]);
+ assertEquals(
+ takes.map((t) => [t.budget.itemId, t.quantity]),
+ [
+ ["OLD", 2],
+ ["NEW", 2],
+ ]
+ );
+ assertEquals(remaining, 1);
+});
+
+Deno.test("allocateAcrossBudgets takes a partial completion from the predecessor only", () => {
+ const { takes, remaining } = allocateAcrossBudgets(2, [
+ budget({ itemId: "OLD", available: 3 }),
+ budget({ itemId: "NEW", available: 1 }),
+ ]);
+ assertEquals(
+ takes.map((t) => [t.budget.itemId, t.quantity]),
+ [["OLD", 2]]
+ );
+ assertEquals(remaining, 0);
+});
+
+Deno.test("allocateAcrossBudgets with nothing staged leaves everything to the fallback", () => {
+ const { takes, remaining } = allocateAcrossBudgets(3, []);
+ assertEquals(takes, []);
+ assertEquals(remaining, 3);
+});
+
+Deno.test("pickFactor follows the rule in either direction", () => {
+ const rules = new Map([
+ ["OLD", { itemId: "OLD", successorItemId: "NEW", conversionFactor: 2 }],
+ ]);
+ assertEquals(pickFactor({ itemId: "OLD" }, "OLD", rules), 1);
+ assertEquals(pickFactor({ itemId: "OLD" }, "NEW", rules), 2);
+ assertEquals(pickFactor({ itemId: "NEW" }, "OLD", rules), 0.5);
+ assertEquals(
+ pickFactor(
+ { itemId: "NEW", substitutedFromItemId: "X", substitutionFactor: 4 },
+ "X",
+ rules
+ ),
+ 0.25
+ );
+ assertEquals(pickFactor({ itemId: "NEW" }, "Z", rules), 1);
+});
+
+Deno.test("linesideCredit: own live picks plus what no job's live pick claims", () => {
+ const consumedByJob = new Map([["j-old", 3]]);
+ const credit = linesideCredit({
+ onHand: 4,
+ claims: [
+ { jobId: "j-old", jobMaterialId: "m-old", staged: 3 },
+ { jobId: "j-me", jobMaterialId: "m-me", staged: 2 },
+ ],
+ consumedByJob,
+ jobId: "j-me",
+ jobMaterialId: "m-me",
+ });
+ assertEquals(credit, { own: 2, unclaimed: 2 });
+});
+
+Deno.test("linesideCredit: a cancelled pick leaves its material unclaimed, and the job's consumption reduces its own claim", () => {
+ assertEquals(
+ linesideCredit({
+ onHand: 5,
+ claims: [{ jobId: "j-me", jobMaterialId: "m-me", staged: 4 }],
+ consumedByJob: new Map([["j-me", 1]]),
+ jobId: "j-me",
+ jobMaterialId: "m-me",
+ }),
+ { own: 3, unclaimed: 2 }
+ );
+ assertEquals(
+ linesideCredit({ onHand: 2, claims: [], consumedByJob: new Map(), jobId: "j", jobMaterialId: "m" }),
+ { own: 0, unclaimed: 2 }
+ );
+});
+
+Deno.test("allocateAcrossBudgets takes a predecessor only in whole assemblies", () => {
+ const budgets = [
+ budget({ itemId: "old", storageUnitId: "ws", available: 3, isPredecessor: true }),
+ budget({ itemId: "new", storageUnitId: "ws", available: 4 }),
+ ];
+ const { takes, remaining } = allocateAcrossBudgets(4, budgets, 2);
+ assertEquals(takes.map((t) => [t.budget.itemId, t.quantity]), [["old", 2], ["new", 2]]);
+ assertEquals(remaining, 0);
+});
+
+Deno.test("allocateAcrossBudgets attributes a take to the own pick first, then the shared stock", () => {
+ const { takes } = allocateAcrossBudgets(7, [
+ budget({ itemId: "X", own: 4, unclaimed: 5 }),
+ ]);
+ assertEquals(
+ takes.map((t) => [t.quantity, t.fromOwn, t.fromShared]),
+ [[7, 4, 3]]
+ );
+});
+
+Deno.test("recordSharedTakes ignores what came from a material's own pick", () => {
+ const takenShared: SharedTakes = new Map();
+ const { takes } = allocateAcrossBudgets(10, [
+ budget({ itemId: "X", own: 10, unclaimed: 0, sharedStorageUnitId: "lineside" }),
+ ]);
+ recordSharedTakes(takenShared, takes);
+ assertEquals(takenShared.size, 0);
+});
+
+Deno.test("recordSharedTakes accumulates the shared portion per item and bin", () => {
+ const takenShared: SharedTakes = new Map();
+ const first = allocateAcrossBudgets(6, [
+ budget({ itemId: "X", own: 4, unclaimed: 5, sharedStorageUnitId: "lineside" }),
+ ]);
+ recordSharedTakes(takenShared, first.takes);
+ const second = allocateAcrossBudgets(1, [
+ budget({ itemId: "X", own: 0, unclaimed: 3, sharedStorageUnitId: "lineside" }),
+ budget({ itemId: "X", own: 0, unclaimed: 3, sharedStorageUnitId: "other" }),
+ ]);
+ recordSharedTakes(takenShared, second.takes);
+ assertEquals(takenShared.get(sharedTakeKey("X", "lineside")), 3);
+ assertEquals(takenShared.get(sharedTakeKey("X", "other")), undefined);
+});
+
+Deno.test("a whole-assembly predecessor take still splits own-first", () => {
+ const { takes } = allocateAcrossBudgets(
+ 4,
+ [budget({ itemId: "OLD", own: 1, unclaimed: 2, isPredecessor: true })],
+ 2
+ );
+ assertEquals(
+ takes.map((t) => [t.quantity, t.fromOwn, t.fromShared]),
+ [[2, 1, 1]]
+ );
+});
+
+Deno.test("splitTakeByBin writes one row when the pools share a bin", () => {
+ const { takes } = allocateAcrossBudgets(7, [
+ budget({ itemId: "X", own: 4, unclaimed: 5, storageUnitId: "ws", sharedStorageUnitId: "ws" }),
+ ]);
+ assertEquals(splitTakeByBin(takes[0]), [{ storageUnitId: "ws", quantity: 7 }]);
+});
+
+Deno.test("splitTakeByBin charges each pool's own bin when they differ", () => {
+ const { takes } = allocateAcrossBudgets(7, [
+ budget({ itemId: "X", own: 4, unclaimed: 5, storageUnitId: "cart", sharedStorageUnitId: "ws" }),
+ ]);
+ assertEquals(splitTakeByBin(takes[0]), [
+ { storageUnitId: "cart", quantity: 4 },
+ { storageUnitId: "ws", quantity: 3 },
+ ]);
+ const shared = allocateAcrossBudgets(2, [
+ budget({ itemId: "X", own: 0, unclaimed: 5, storageUnitId: "cart", sharedStorageUnitId: "ws" }),
+ ]);
+ assertEquals(splitTakeByBin(shared.takes[0]), [{ storageUnitId: "ws", quantity: 2 }]);
+});
diff --git a/packages/database/supabase/functions/lib/picked-consumption.ts b/packages/database/supabase/functions/lib/picked-consumption.ts
new file mode 100644
index 0000000000..4eab0c9173
--- /dev/null
+++ b/packages/database/supabase/functions/lib/picked-consumption.ts
@@ -0,0 +1,429 @@
+
+import { consumableInWholeAssemblies } from "./supersession-pick.ts";
+
+export type LinesideClaim = { jobId: string; jobMaterialId: string; staged: number };
+
+export function linesideCredit(args: {
+ onHand: number;
+ claims: LinesideClaim[];
+ consumedByJob: Map<string, number>;
+ jobId: string;
+ jobMaterialId: string;
+}): { own: number; unclaimed: number } {
+ const { claims, consumedByJob, jobId, jobMaterialId } = args;
+ const stagedByJob = new Map<string, number>();
+ let ownStaged = 0;
+ for (const claim of claims) {
+ const staged = Math.max(0, claim.staged);
+ stagedByJob.set(claim.jobId, (stagedByJob.get(claim.jobId) ?? 0) + staged);
+ if (claim.jobMaterialId === jobMaterialId) ownStaged += staged;
+ }
+ let claimed = 0;
+ for (const [job, staged] of stagedByJob) {
+ claimed += Math.max(0, staged - (consumedByJob.get(job) ?? 0));
+ }
+ const own = Math.max(0, ownStaged - (consumedByJob.get(jobId) ?? 0));
+ const unclaimed = Math.max(0, Math.max(0, args.onHand) - claimed);
+ return { own, unclaimed };
+}
+
+export type PickedBudget = {
+ itemId: string;
+ factor: number;
+ storageUnitId: string | null;
+ sharedStorageUnitId: string | null;
+ own: number;
+ unclaimed: number;
+ available: number;
+ isInventory: boolean;
+ isPredecessor: boolean;
+};
+
+export type Take = {
+ budget: PickedBudget;
+ quantity: number;
+ fromOwn: number;
+ fromShared: number;
+};
+
+export type SharedTakes = Map<string, number>;
+
+export function sharedTakeKey(itemId: string, storageUnitId: string | null) {
+ return `${itemId}\u0000${storageUnitId ?? ""}`;
+}
+
+export function recordSharedTakes(takenShared: SharedTakes, takes: Take[]) {
+ for (const take of takes) {
+ if (take.fromShared <= 0) continue;
+ const key = sharedTakeKey(take.budget.itemId, take.budget.sharedStorageUnitId);
+ takenShared.set(key, (takenShared.get(key) ?? 0) + take.fromShared);
+ }
+}
+
+export function splitTakeByBin(
+ take: Take
+): { storageUnitId: string | null; quantity: number }[] {
+ const { budget, fromOwn, fromShared } = take;
+ if (
+ fromShared <= 0 ||
+ fromOwn <= 0 ||
+ budget.storageUnitId === budget.sharedStorageUnitId
+ ) {
+ return [
+ {
+ storageUnitId: fromOwn > 0 ? budget.storageUnitId : budget.sharedStorageUnitId,
+ quantity: take.quantity,
+ },
+ ];
+ }
+ return [
+ { storageUnitId: budget.storageUnitId, quantity: fromOwn },
+ { storageUnitId: budget.sharedStorageUnitId, quantity: fromShared },
+ ];
+}
+
+export function orderOldFirst(
+ budgets: PickedBudget[],
+ lineItemId: string
+): PickedBudget[] {
+ const rank = (b: PickedBudget) =>
+ b.isPredecessor ? 0 : b.itemId === lineItemId ? 1 : 2;
+ return [...budgets].sort(
+ (a, b) => rank(a) - rank(b) || a.itemId.localeCompare(b.itemId)
+ );
+}
+
+export function allocateAcrossBudgets(
+ quantity: number,
+ budgets: PickedBudget[],
+ perAssembly = 0
+): { takes: Take[]; remaining: number } {
+ const takes: Take[] = [];
+ let remaining = quantity;
+ for (const budget of budgets) {
+ if (remaining <= 0) break;
+ if (budget.available <= 0 || budget.factor <= 0) continue;
+ const usable =
+ budget.isPredecessor && perAssembly > 0
+ ? consumableInWholeAssemblies(
+ budget.available,
+ perAssembly * budget.factor
+ )
+ : budget.available;
+ const take = Math.min(remaining * budget.factor, usable);
+ if (take <= 0) continue;
+ const fromOwn = Math.min(take, Math.max(0, budget.own));
+ takes.push({ budget, quantity: take, fromOwn, fromShared: take - fromOwn });
+ remaining -= take / budget.factor;
+ }
+ return { takes, remaining: Math.max(0, remaining) };
+}
+
+type Rule = { itemId: string; successorItemId: string | null; conversionFactor: number };
+
+export function pickFactor(
+ material: {
+ itemId: string;
+ substitutedFromItemId?: string | null;
+ substitutionFactor?: number | string | null;
+ },
+ pickedItemId: string,
+ ruleByItem: Map<string, Rule>
+): number {
+ if (pickedItemId === material.itemId) return 1;
+ const lineRule = ruleByItem.get(material.itemId);
+ if (lineRule?.successorItemId === pickedItemId) return lineRule.conversionFactor;
+ const pickedRule = ruleByItem.get(pickedItemId);
+ if (pickedRule?.successorItemId === material.itemId) {
+ return 1 / pickedRule.conversionFactor;
+ }
+ const sf = Number(material.substitutionFactor ?? 0);
+ if (pickedItemId === material.substitutedFromItemId && sf > 0) return 1 / sf;
+ return 1;
+}
+
+type Trx = any;
+
+export async function getOperationLinesideBin(
+ trx: Trx,
+ args: { jobOperationId: string | null | undefined; companyId: string }
+): Promise<string | null> {
+ if (!args.jobOperationId) return null;
+ const operation: { workCenterId: string | null } | undefined = await trx
+ .selectFrom("jobOperation")
+ .select(["workCenterId"])
+ .where("id", "=", args.jobOperationId)
+ .executeTakeFirst();
+ if (!operation?.workCenterId) return null;
+ const bin: { id: string } | undefined = await trx
+ .selectFrom("storageUnit")
+ .select(["id"])
+ .where("workCenterId", "=", operation.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .orderBy("isWorkCenterDefault", "desc")
+ .orderBy("createdAt", "asc")
+ .executeTakeFirst();
+ return bin?.id ?? null;
+}
+
+async function getLinesideCredits(
+ trx: Trx,
+ args: {
+ itemIds: string[];
+ storageUnitId: string;
+ locationId: string;
+ companyId: string;
+ jobId: string;
+ jobMaterialId: string;
+ }
+): Promise<Map<string, { own: number; unclaimed: number }>> {
+ const { itemIds, storageUnitId, locationId, companyId } = args;
+ const [onHand, lines, consumed] = await Promise.all([
+ trx
+ .selectFrom("itemLedger")
+ .select(["itemId", (eb: Trx) => eb.fn.sum("quantity").as("quantity")])
+ .where("companyId", "=", companyId)
+ .where("storageUnitId", "=", storageUnitId)
+ .where("itemId", "in", itemIds)
+ .groupBy("itemId")
+ .execute() as Promise<{ itemId: string; quantity: number | string | null }[]>,
+ trx
+ .selectFrom("pickingListLine as pll")
+ .innerJoin("pickingList as pl", "pl.id", "pll.pickingListId")
+ .innerJoin("job as j", "j.id", "pll.jobId")
+ .select([
+ "pll.jobId",
+ "pll.jobMaterialId",
+ "pll.itemId",
+ "pll.quantityPicked",
+ "pll.quantityReturned",
+ ])
+ .where("pll.companyId", "=", companyId)
+ .where("pll.toStorageUnitId", "=", storageUnitId)
+ .where("pll.itemId", "in", itemIds)
+ .where("pll.status", "<>", "Cancelled")
+ .where("pl.status", "<>", "Cancelled")
+ .where("j.status", "in", ["Planned", "Ready", "In Progress", "Paused"])
+ .execute() as Promise<
+ {
+ jobId: string;
+ jobMaterialId: string;
+ itemId: string;
+ quantityPicked: number | string | null;
+ quantityReturned: number | string | null;
+ }[]
+ >,
+ trx
+ .selectFrom("itemLedger")
+ .select([
+ "itemId",
+ "documentId",
+ (eb: Trx) => eb.fn.sum("quantity").as("quantity"),
+ ])
+ .where("companyId", "=", companyId)
+ .where("locationId", "=", locationId)
+ .where("storageUnitId", "=", storageUnitId)
+ .where("documentType", "=", "Job Consumption")
+ .where("itemId", "in", itemIds)
+ .groupBy(["itemId", "documentId"])
+ .execute() as Promise<
+ { itemId: string; documentId: string | null; quantity: number | string | null }[]
+ >,
+ ]);
+ const onHandByItem = new Map(onHand.map((r) => [r.itemId, Number(r.quantity ?? 0)]));
+ const credits = new Map<string, { own: number; unclaimed: number }>();
+ for (const itemId of itemIds) {
+ const consumedByJob = new Map<string, number>();
+ for (const row of consumed) {
+ if (row.itemId !== itemId || !row.documentId) continue;
+ consumedByJob.set(row.documentId, Math.max(0, -Number(row.quantity ?? 0)));
+ }
+ credits.set(
+ itemId,
+ linesideCredit({
+ onHand: onHandByItem.get(itemId) ?? 0,
+ claims: lines
+ .filter((l) => l.itemId === itemId)
+ .map((l) => ({
+ jobId: l.jobId,
+ jobMaterialId: l.jobMaterialId,
+ staged: Number(l.quantityPicked ?? 0) - Number(l.quantityReturned ?? 0),
+ })),
+ consumedByJob,
+ jobId: args.jobId,
+ jobMaterialId: args.jobMaterialId,
+ })
+ );
+ }
+ return credits;
+}
+
+export async function getPickedBudgets(
+ trx: Trx,
+ args: {
+ material: {
+ id: string;
+ itemId: string;
+ jobId: string;
+ substitutedFromItemId?: string | null;
+ substitutionFactor?: number | string | null;
+ };
+ locationId: string;
+ companyId: string;
+ opStorageUnitId?: string | null;
+ takenShared?: SharedTakes;
+ }
+): Promise<PickedBudget[]> {
+ const { material, locationId, companyId, opStorageUnitId, takenShared } = args;
+
+ const lines: {
+ itemId: string;
+ quantityPicked: number | string | null;
+ quantityReturned: number | string | null;
+ toStorageUnitId: string | null;
+ }[] = 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", "<>", "Cancelled")
+ .select([
+ "pll.itemId",
+ "pll.quantityPicked",
+ "pll.quantityReturned",
+ "pll.toStorageUnitId",
+ ])
+ .execute();
+
+ const stagedByItem = new Map<string, number>();
+ const binByItem = new Map<string, Map<string, number>>();
+ for (const line of lines) {
+ const staged = Math.max(
+ 0,
+ Number(line.quantityPicked ?? 0) - Number(line.quantityReturned ?? 0)
+ );
+ if (staged <= 0) continue;
+ stagedByItem.set(line.itemId, (stagedByItem.get(line.itemId) ?? 0) + staged);
+ if (line.toStorageUnitId) {
+ const bins = binByItem.get(line.itemId) ?? new Map<string, number>();
+ bins.set(
+ line.toStorageUnitId,
+ (bins.get(line.toStorageUnitId) ?? 0) + staged
+ );
+ binByItem.set(line.itemId, bins);
+ }
+ }
+ const seed = [
+ ...new Set(
+ [material.itemId, material.substitutedFromItemId ?? null, ...stagedByItem.keys()].filter(
+ (id): id is string => !!id
+ )
+ ),
+ ];
+ const rules: {
+ itemId: string;
+ successorItemId: string | null;
+ conversionFactor: number | string | null;
+ }[] = await trx
+ .selectFrom("itemSupersession")
+ .select(["itemId", "successorItemId", "conversionFactor"])
+ .where("companyId", "=", companyId)
+ .where((eb: Trx) =>
+ eb.or([
+ eb("itemId", "in", seed),
+ eb("successorItemId", "in", seed),
+ ])
+ )
+ .execute();
+ const related = new Set(seed);
+ for (const r of rules) {
+ if (r.successorItemId === material.itemId) related.add(r.itemId);
+ if (r.itemId === material.itemId && r.successorItemId) related.add(r.successorItemId);
+ }
+ const relatedIds = [...related];
+
+ const credits = opStorageUnitId
+ ? await getLinesideCredits(trx, {
+ itemIds: relatedIds,
+ storageUnitId: opStorageUnitId,
+ locationId,
+ companyId,
+ jobId: material.jobId,
+ jobMaterialId: material.id,
+ })
+ : new Map<string, { own: number; unclaimed: number }>();
+
+ const budgetItemIds = relatedIds.filter(
+ (id) => (stagedByItem.get(id) ?? 0) > 0 || (credits.get(id)?.unclaimed ?? 0) > 0
+ );
+ if (budgetItemIds.length === 0) return [];
+ const pickedItemIds = budgetItemIds;
+ const involved = relatedIds;
+
+ const [consumed, items] = await Promise.all([
+ trx
+ .selectFrom("itemLedger")
+ .select(["itemId", (eb: Trx) => eb.fn.sum("quantity").as("quantity")])
+ .where("documentType", "=", "Job Consumption")
+ .where("documentId", "=", material.jobId)
+ .where("locationId", "=", locationId)
+ .where("companyId", "=", companyId)
+ .where("itemId", "in", pickedItemIds)
+ .groupBy("itemId")
+ .execute() as Promise<{ itemId: string; quantity: number | string | null }[]>,
+ trx
+ .selectFrom("item")
+ .select(["id", "itemTrackingType"])
+ .where("id", "in", pickedItemIds)
+ .execute() as Promise<{ id: string; itemTrackingType: string | null }[]>,
+ ]);
+
+ const consumedByItem = new Map(
+ consumed.map((c) => [c.itemId, Math.max(0, -Number(c.quantity ?? 0))])
+ );
+ const ruleByItem = new Map<string, Rule>(
+ rules.map((r) => [
+ r.itemId,
+ {
+ itemId: r.itemId,
+ successorItemId: r.successorItemId,
+ conversionFactor: Number(r.conversionFactor ?? 1) || 1,
+ },
+ ])
+ );
+ const trackingByItem = new Map(items.map((i) => [i.id, i.itemTrackingType]));
+ const involvedSet = new Set(involved);
+
+ return pickedItemIds.map((itemId) => {
+ const bins = binByItem.get(itemId);
+ const storageUnitId =
+ (bins
+ ? [...bins.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]
+ : undefined) ??
+ opStorageUnitId ??
+ null;
+ const successor = ruleByItem.get(itemId)?.successorItemId;
+ const own = Math.max(
+ 0,
+ (stagedByItem.get(itemId) ?? 0) - (consumedByItem.get(itemId) ?? 0)
+ );
+ const sharedStorageUnitId = opStorageUnitId ?? null;
+ const unclaimed = Math.max(
+ 0,
+ (credits.get(itemId)?.unclaimed ?? 0) -
+ (takenShared?.get(sharedTakeKey(itemId, sharedStorageUnitId)) ?? 0)
+ );
+ return {
+ itemId,
+ factor: pickFactor(material, itemId, ruleByItem),
+ storageUnitId,
+ sharedStorageUnitId,
+ own,
+ unclaimed,
+ available: own + unclaimed,
+ isInventory: trackingByItem.get(itemId) === "Inventory",
+ isPredecessor: !!successor && successor !== itemId && involvedSet.has(successor),
+ };
+ });
+}
diff --git a/packages/database/supabase/functions/lib/supersession-pick.test.ts b/packages/database/supabase/functions/lib/supersession-pick.test.ts
index f1497c3fc6..e1236a95ff 100644
--- a/packages/database/supabase/functions/lib/supersession-pick.test.ts
+++ b/packages/database/supabase/functions/lib/supersession-pick.test.ts
@@ -1,7 +1,19 @@
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import {
buildSupersessionRedirectMap,
+ consumableInWholeAssemblies,
+ pullBackQuantities,
type SupersessionRow,
+ withoutStockedConsumeFirst,
+ buildConsumeFirstRules,
+ consumeFirstStockItems,
+ keepsLineOnPredecessor,
+ settleConsumeFirstLine,
+ buildConsumeFirstHops,
+ firstStockedInConsumeFirstChain,
+ resolveMadeLinePull,
+ type SupersessionMode,
+ reserveConsumeFirstStock,
} from "./supersession-pick.ts";
// `buildSupersessionRedirectMap` is the single source of truth for "should this
@@ -38,15 +50,20 @@ Deno.test("redirects for Prefer New", () => {
assertEquals(map.get("A"), { to: "B", factor: 1 });
});
-// Stock Only keeps its successor as a reserve-governed reference and No Stock
-// has no successor to move demand to — neither redirects. Seeding a test with
-// one of these modes is the easiest way to "prove" a swap works when nothing
-// swapped at all.
-Deno.test("does not redirect for Stock Only or No Stock", () => {
- for (const supersessionMode of ["Stock Only", "No Stock"]) {
- const map = buildSupersessionRedirectMap([row({ supersessionMode })], ASOF);
- assertEquals(map.size, 0, supersessionMode);
- }
+Deno.test("redirects for Stock Only", () => {
+ const map = buildSupersessionRedirectMap(
+ [row({ supersessionMode: "Stock Only" })],
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "B", factor: 1 });
+});
+
+Deno.test("does not redirect for No Stock", () => {
+ const map = buildSupersessionRedirectMap(
+ [row({ supersessionMode: "No Stock", successorItemId: null })],
+ ASOF
+ );
+ assertEquals(map.size, 0);
});
Deno.test("does not redirect without a successor", () => {
@@ -214,3 +231,303 @@ Deno.test("last row wins for a duplicated itemId", () => {
Deno.test("returns an empty map for no rows", () => {
assertEquals(buildSupersessionRedirectMap([], ASOF).size, 0);
});
+
+Deno.test("withoutStockedConsumeFirst keeps a stocked Consume First predecessor", () => {
+ const rows = [
+ row({ itemId: "A", successorItemId: "B" }),
+ row({ itemId: "B", successorItemId: "C" }),
+ row({ itemId: "D", successorItemId: "E", supersessionMode: "Prefer New" }),
+ ];
+ const map = buildSupersessionRedirectMap(
+ withoutStockedConsumeFirst(rows, new Set(["A", "D"])),
+ ASOF
+ );
+ assertEquals(map.has("A"), false);
+ assertEquals(map.get("B"), { to: "C", factor: 1 });
+ assertEquals(map.get("D"), { to: "E", factor: 1 });
+});
+
+Deno.test("withoutStockedConsumeFirst redirects once the predecessor is out", () => {
+ const map = buildSupersessionRedirectMap(
+ withoutStockedConsumeFirst([row()], new Set()),
+ ASOF
+ );
+ assertEquals(map.get("A"), { to: "B", factor: 1 });
+});
+
+Deno.test("pullBackQuantities converts the target and re-derives scrap at the predecessor's rate", () => {
+ const result = pullBackQuantities(
+ { quantity: 2, estimatedQuantity: 11, scrapQuantity: 1 },
+ 0.5,
+ 0.2
+ );
+ assertEquals(result.quantity, 1);
+ assertEquals(result.scrapQuantity, 1); // ceil(5 * 0.2)
+ assertEquals(result.estimatedQuantity, 6);
+});
+
+Deno.test("pullBackQuantities with no predecessor scrap carries none over", () => {
+ const result = pullBackQuantities(
+ { quantity: "2", estimatedQuantity: "11", scrapQuantity: "1" },
+ 0.5,
+ 0
+ );
+ assertEquals(result, { quantity: 1, estimatedQuantity: 5, scrapQuantity: 0 });
+});
+
+Deno.test("consumableInWholeAssemblies rounds stock down to whole assemblies", () => {
+ assertEquals(consumableInWholeAssemblies(3, 2), 2);
+ assertEquals(consumableInWholeAssemblies(1, 2), 0);
+ assertEquals(consumableInWholeAssemblies(4, 2), 4);
+ assertEquals(consumableInWholeAssemblies(10, 3), 9);
+ assertEquals(consumableInWholeAssemblies(0, 2), 0);
+ assertEquals(consumableInWholeAssemblies(-2, 2), 0);
+});
+
+Deno.test("consumableInWholeAssemblies handles fractional and missing per-assembly quantities", () => {
+ assertEquals(consumableInWholeAssemblies(0.3, 0.1), 0.3);
+ assertEquals(consumableInWholeAssemblies(1.25, 0.5), 1);
+ assertEquals(consumableInWholeAssemblies(3, 0), 3);
+ assertEquals(consumableInWholeAssemblies(3, Number.NaN), 3);
+});
+
+
+const CF_ROWS = [
+ {
+ itemId: "old",
+ successorItemId: "new",
+ successorEffectivityDate: null,
+ conversionFactor: 1,
+ },
+];
+const cfRules = () => buildConsumeFirstRules(CF_ROWS, "2026-09-16");
+const stock = (entries: Record<string, number>) =>
+ new Map(Object.entries(entries));
+
+Deno.test("keepsLineOnPredecessor is one whole assembly, never a unit", () => {
+ assertEquals(keepsLineOnPredecessor(3, 1), true);
+ assertEquals(keepsLineOnPredecessor(3, 2), true); // one pair, one odd part left
+ assertEquals(keepsLineOnPredecessor(1, 2), false); // half a pair is nothing
+ assertEquals(keepsLineOnPredecessor(0, 1), false);
+ assertEquals(keepsLineOnPredecessor(undefined, 1), false);
+});
+
+Deno.test("buildConsumeFirstRules indexes both directions and gates on effectivity", () => {
+ const rules = buildConsumeFirstRules(
+ [
+ ...CF_ROWS,
+ {
+ itemId: "older",
+ successorItemId: "new",
+ successorEffectivityDate: "2026-10-01",
+ conversionFactor: "2",
+ },
+ { itemId: "loose", successorItemId: null, successorEffectivityDate: null, conversionFactor: 1 },
+ ],
+ "2026-09-16"
+ );
+ assertEquals(rules.successorByPredecessor.get("old"), { itemId: "new", factor: 1 });
+ assertEquals(rules.successorByPredecessor.has("older"), false); // not yet effective
+ assertEquals(rules.successorByPredecessor.has("loose"), false); // no successor
+ assertEquals(rules.predecessorsBySuccessor.get("new"), [{ itemId: "old", factor: 1 }]);
+});
+
+Deno.test("case 17: a made line swapped at creation is reverted onto a stocked predecessor", () => {
+ const line = { itemId: "new", quantity: 1, substitutedFromItemId: "old" };
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 3 })), {
+ kind: "revert",
+ toItemId: "old",
+ factor: 1,
+ });
+});
+
+Deno.test("case 18: a swapped line stays on the successor when the predecessor is empty", () => {
+ const line = { itemId: "new", quantity: 1, substitutedFromItemId: "old" };
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 0 })), null);
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({})), null);
+});
+
+Deno.test("case 19: no whole assembly in stock pushes a kept line to the successor", () => {
+ const line = { itemId: "old", quantity: 2, substitutedFromItemId: null };
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 1 })), {
+ kind: "push",
+ toItemId: "new",
+ factor: 1,
+ });
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 3 })), null);
+});
+
+Deno.test("case 20: a line the BOM names by the successor is pulled back onto a stocked predecessor", () => {
+ const line = { itemId: "new", quantity: 1, substitutedFromItemId: null };
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 3 })), {
+ kind: "pullBack",
+ toItemId: "old",
+ factor: 1,
+ });
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 0 })), null);
+});
+
+Deno.test("case 22: the factor converts the per-assembly quantity before the whole-assembly test", () => {
+ const rules = buildConsumeFirstRules(
+ [{ ...CF_ROWS[0]!, conversionFactor: 2 }],
+ "2026-09-16"
+ );
+ const line = { itemId: "new", quantity: 2, substitutedFromItemId: "old" };
+ assertEquals(settleConsumeFirstLine(line, rules, stock({ old: 1 })), {
+ kind: "revert",
+ toItemId: "old",
+ factor: 0.5,
+ });
+ const kept = { itemId: "old", quantity: 1, substitutedFromItemId: null };
+ assertEquals(settleConsumeFirstLine(kept, rules, stock({ old: 0 })), {
+ kind: "push",
+ toItemId: "new",
+ factor: 2,
+ });
+});
+
+Deno.test("case 21 (quantities): a revert recovers the target and re-derives scrap at the predecessor's rate", () => {
+ assertEquals(
+ pullBackQuantities({ quantity: 1, estimatedQuantity: 5, scrapQuantity: 0 }, 1, 0.1),
+ { quantity: 1, estimatedQuantity: 6, scrapQuantity: 1 }
+ );
+});
+
+Deno.test("a swapped row's provenance only counts when the predecessor's rule names this row's item", () => {
+ const rules = buildConsumeFirstRules(
+ [...CF_ROWS, { itemId: "older", successorItemId: "other", successorEffectivityDate: null, conversionFactor: 1 }],
+ "2026-09-16"
+ );
+ const line = { itemId: "new", quantity: 1, substitutedFromItemId: "older" };
+ assertEquals(settleConsumeFirstLine(line, rules, stock({ older: 5, old: 5 })), {
+ kind: "pullBack",
+ toItemId: "old",
+ factor: 1,
+ });
+});
+
+Deno.test("a line with no Consume First relation is left alone", () => {
+ const line = { itemId: "unrelated", quantity: 1, substitutedFromItemId: null };
+ assertEquals(settleConsumeFirstLine(line, cfRules(), stock({ old: 9 })), null);
+});
+
+Deno.test("consumeFirstStockItems names every item whose stock decides the line", () => {
+ const rules = cfRules();
+ assertEquals(consumeFirstStockItems({ itemId: "old", substitutedFromItemId: null }, rules), ["old"]);
+ assertEquals(consumeFirstStockItems({ itemId: "new", substitutedFromItemId: null }, rules), ["old"]);
+ assertEquals(consumeFirstStockItems({ itemId: "new", substitutedFromItemId: "old" }, rules), ["old"]);
+ assertEquals(consumeFirstStockItems({ itemId: "x", substitutedFromItemId: null }, rules), []);
+});
+
+
+const cfRow = (
+ itemId: string,
+ successorItemId: string | null,
+ supersessionMode: SupersessionMode = "Consume First",
+ conversionFactor: number | string | null = 1,
+ successorEffectivityDate: string | null = null
+) => ({ itemId, successorItemId, supersessionMode, conversionFactor, successorEffectivityDate });
+
+Deno.test("buildConsumeFirstHops stops at the next Consume First item instead of collapsing", () => {
+ const hops = buildConsumeFirstHops(
+ [cfRow("old", "mid"), cfRow("mid", "new")],
+ "2026-09-16"
+ );
+ assertEquals(hops.get("old"), { to: "mid", factor: 1 });
+ assertEquals(hops.get("mid"), { to: "new", factor: 1 });
+ assertEquals(
+ buildSupersessionRedirectMap([cfRow("old", "mid"), cfRow("mid", "new")], "2026-09-16").get("old"),
+ { to: "new", factor: 1 }
+ );
+});
+
+Deno.test("buildConsumeFirstHops collapses THROUGH a non-Consume-First hop and multiplies its factor", () => {
+ const hops = buildConsumeFirstHops(
+ [cfRow("old", "mid", "Consume First", 2), cfRow("mid", "new", "Prefer New", 3)],
+ "2026-09-16"
+ );
+ assertEquals(hops.get("old"), { to: "new", factor: 6 });
+ assertEquals(hops.has("mid"), false);
+});
+
+Deno.test("buildConsumeFirstHops honours effectivity per hop and drops cycles", () => {
+ const hops = buildConsumeFirstHops(
+ [
+ cfRow("old", "mid", "Consume First", 1, "2026-10-01"), // not yet
+ cfRow("mid", "new"),
+ cfRow("a", "b"),
+ cfRow("b", "a"),
+ ],
+ "2026-09-16"
+ );
+ assertEquals(hops.has("old"), false);
+ assertEquals(hops.get("mid"), { to: "new", factor: 1 });
+ assertEquals(hops.has("a"), false);
+ assertEquals(hops.has("b"), false);
+});
+
+Deno.test("firstStockedInConsumeFirstChain returns the first hop with a whole assembly, at the cumulative factor", () => {
+ const hops = buildConsumeFirstHops(
+ [cfRow("old", "mid", "Consume First", 2), cfRow("mid", "new")],
+ "2026-09-16"
+ );
+ const onHand = (m: Record<string, number>) => new Map(Object.entries(m));
+ assertEquals(firstStockedInConsumeFirstChain("old", 1, hops, onHand({ old: 1, mid: 9 })), {
+ itemId: "old",
+ factor: 1,
+ });
+ assertEquals(firstStockedInConsumeFirstChain("old", 1, hops, onHand({ old: 0, mid: 2 })), {
+ itemId: "mid",
+ factor: 2,
+ });
+ assertEquals(firstStockedInConsumeFirstChain("old", 1, hops, onHand({ old: 0, mid: 1 })), null);
+ assertEquals(firstStockedInConsumeFirstChain("old", 1, hops, onHand({ new: 50 })), null);
+ assertEquals(firstStockedInConsumeFirstChain("lonely", 1, hops, onHand({ lonely: 5 })), null);
+});
+
+Deno.test("resolveMadeLinePull: stocked chain first, then a bought successor, else build", () => {
+ const rows = [cfRow("old", "new")];
+ const ctx = {
+ redirect: buildSupersessionRedirectMap(rows, "2026-09-16"),
+ consumeFirstHops: buildConsumeFirstHops(rows, "2026-09-16"),
+ consumeFirstOnHand: new Map([["old", 0]]),
+ boughtSuccessors: new Set<string>(),
+ };
+ assertEquals(resolveMadeLinePull("old", 1, ctx), null);
+ assertEquals(
+ resolveMadeLinePull("old", 1, { ...ctx, consumeFirstOnHand: new Map([["old", 2]]) }),
+ { itemId: "old", factor: 1 }
+ );
+ assertEquals(
+ resolveMadeLinePull("old", 1, { ...ctx, boughtSuccessors: new Set(["new"]) }),
+ { itemId: "new", factor: 1 }
+ );
+ assertEquals(resolveMadeLinePull("other", 1, { ...ctx, boughtSuccessors: new Set(["new"]) }), null);
+});
+
+Deno.test("reserveConsumeFirstStock: a settled line draws its whole assemblies down for the next line", () => {
+ const rules = buildConsumeFirstRules([cfRow("old", "new")], "2026-09-16");
+ const onHand = new Map([["old", 6]]);
+ const first = { itemId: "old", quantity: 4, estimatedQuantity: 4, scrapQuantity: 0, substitutedFromItemId: null };
+ const second = { ...first };
+ const s1 = settleConsumeFirstLine(first, rules, onHand);
+ reserveConsumeFirstStock(first, s1, rules, onHand);
+ assertEquals(s1, null);
+ assertEquals(onHand.get("old"), 2);
+ assertEquals(settleConsumeFirstLine(second, rules, onHand), { kind: "push", toItemId: "new", factor: 1 });
+});
+
+Deno.test("reserveConsumeFirstStock: a revert reserves in the predecessor's units and a push reserves nothing", () => {
+ const rules = buildConsumeFirstRules([cfRow("old", "new", "Consume First", 2)], "2026-09-16");
+ const onHand = new Map([["old", 3]]);
+ const swapped = { itemId: "new", quantity: 2, estimatedQuantity: 8, scrapQuantity: 0, substitutedFromItemId: "old" };
+ const s = settleConsumeFirstLine(swapped, rules, onHand);
+ assertEquals(s, { kind: "revert", toItemId: "old", factor: 0.5 });
+ reserveConsumeFirstStock(swapped, s, rules, onHand);
+ assertEquals(onHand.get("old"), 0);
+ const kept = { itemId: "old", quantity: 1, estimatedQuantity: 2, scrapQuantity: 0, substitutedFromItemId: null };
+ const s3 = settleConsumeFirstLine(kept, rules, onHand);
+ assertEquals(s3, { kind: "push", toItemId: "new", factor: 2 });
+ reserveConsumeFirstStock(kept, s3, rules, onHand);
+ assertEquals(onHand.get("old"), 0);
+});
diff --git a/packages/database/supabase/functions/lib/supersession-pick.ts b/packages/database/supabase/functions/lib/supersession-pick.ts
index 89833d92f4..6d2954e31f 100644
--- a/packages/database/supabase/functions/lib/supersession-pick.ts
+++ b/packages/database/supabase/functions/lib/supersession-pick.ts
@@ -6,9 +6,15 @@
// that format and equivalent to a calendar-date compare, so no date library is
// needed (and the two callers stay byte-for-byte consistent).
+import { round, RoundingMode, scrapAllowance } from "../shared/precision.ts";
+import type { Database } from "./types.ts";
+
+export type SupersessionMode =
+ Database["public"]["Enums"]["supersessionMode"];
+
export type SupersessionRow = {
itemId: string;
- supersessionMode: string;
+ supersessionMode: SupersessionMode;
successorItemId: string | null;
successorEffectivityDate: string | null;
conversionFactor: number | string | null;
@@ -16,10 +22,21 @@ export type SupersessionRow = {
export type Redirect = { to: string; factor: number };
-// Only these phase-out modes redirect demand to the successor. Stock Only keeps
-// its successor as a reference (reserve-governed, no redirect); No Stock has no
-// successor. Must match the mode gating in mrp/index.ts.
-const REDIRECTING_MODES = new Set(["Consume First", "Prefer New"]);
+const REDIRECTING_MODES = new Set<SupersessionMode>([
+ "Consume First",
+ "Prefer New",
+ "Stock Only",
+]);
+
+export function withoutStockedConsumeFirst(
+ supersessions: SupersessionRow[],
+ stockedItemIds: Set<string>
+): SupersessionRow[] {
+ return supersessions.filter(
+ (s) =>
+ !(s.supersessionMode === "Consume First" && stockedItemIds.has(s.itemId))
+ );
+}
// Build `oldItemId -> { successor, cumulative factor }` for every item whose
// supersession is *effective* as of `asOfDate`, collapsing multi-hop chains
@@ -82,3 +99,279 @@ export function buildSupersessionRedirectMap(
return collapsed;
}
+
+export function pullBackQuantities(
+ successorRow: {
+ quantity: number | string | null;
+ estimatedQuantity: number | string | null;
+ scrapQuantity: number | string | null;
+ },
+ factor: number,
+ predecessorScrapPercentage: number
+): { quantity: number; estimatedQuantity: number; scrapQuantity: number } {
+ const successorTarget =
+ Number(successorRow.estimatedQuantity ?? 0) -
+ Number(successorRow.scrapQuantity ?? 0);
+ const targetQuantity = successorTarget * factor;
+ const scrapQuantity = scrapAllowance(
+ targetQuantity,
+ predecessorScrapPercentage
+ );
+ return {
+ quantity: Number(successorRow.quantity ?? 0) * factor,
+ estimatedQuantity: targetQuantity + scrapQuantity,
+ scrapQuantity,
+ };
+}
+
+export function consumableInWholeAssemblies(
+ onHand: number,
+ perAssembly: number
+): number {
+ const stock = Math.max(0, Number(onHand) || 0);
+ const per = Number(perAssembly) || 0;
+ if (per <= 0) return stock;
+ const assemblies = round(round(stock / per), 0, RoundingMode.Down);
+ return round(assemblies * per);
+}
+
+export function keepsLineOnPredecessor(
+ onHand: number | null | undefined,
+ perAssembly: number | string | null | undefined
+): boolean {
+ return (
+ consumableInWholeAssemblies(Number(onHand) || 0, Number(perAssembly) || 0) >
+ 0
+ );
+}
+
+export type ConsumeFirstRule = { itemId: string; factor: number };
+
+export type ConsumeFirstRules = {
+ successorByPredecessor: Map<string, ConsumeFirstRule>;
+ predecessorsBySuccessor: Map<string, ConsumeFirstRule[]>;
+};
+
+export function buildConsumeFirstRules(
+ rows: {
+ itemId: string;
+ successorItemId: string | null;
+ successorEffectivityDate: string | null;
+ conversionFactor: number | string | null;
+ }[],
+ asOfDate: string
+): ConsumeFirstRules {
+ const successorByPredecessor = new Map<string, ConsumeFirstRule>();
+ const predecessorsBySuccessor = new Map<string, ConsumeFirstRule[]>();
+ for (const r of rows) {
+ if (!r.successorItemId) continue;
+ if (r.successorEffectivityDate && r.successorEffectivityDate > asOfDate) {
+ continue;
+ }
+ const factor = Number(r.conversionFactor ?? 1) || 1;
+ successorByPredecessor.set(r.itemId, { itemId: r.successorItemId, factor });
+ predecessorsBySuccessor.set(r.successorItemId, [
+ ...(predecessorsBySuccessor.get(r.successorItemId) ?? []),
+ { itemId: r.itemId, factor },
+ ]);
+ }
+ return { successorByPredecessor, predecessorsBySuccessor };
+}
+
+export type ConsumeFirstSettlement = {
+ kind: "revert" | "pullBack" | "push";
+ toItemId: string;
+ factor: number;
+};
+
+export function consumeFirstSwappedFrom(
+ line: { itemId: string; substitutedFromItemId: string | null },
+ rules: ConsumeFirstRules
+): ConsumeFirstRule | null {
+ const from = line.substitutedFromItemId;
+ if (!from) return null;
+ const rule = rules.successorByPredecessor.get(from);
+ return rule && rule.itemId === line.itemId
+ ? { itemId: from, factor: rule.factor }
+ : null;
+}
+
+export function consumeFirstStockItems(
+ line: { itemId: string; substitutedFromItemId: string | null },
+ rules: ConsumeFirstRules
+): string[] {
+ const ids = new Set<string>();
+ if (rules.successorByPredecessor.has(line.itemId)) ids.add(line.itemId);
+ for (const p of rules.predecessorsBySuccessor.get(line.itemId) ?? []) {
+ ids.add(p.itemId);
+ }
+ const from = consumeFirstSwappedFrom(line, rules);
+ if (from) ids.add(from.itemId);
+ return [...ids];
+}
+
+export function settleConsumeFirstLine(
+ line: {
+ itemId: string;
+ quantity: number | string | null;
+ substitutedFromItemId: string | null;
+ },
+ rules: ConsumeFirstRules,
+ onHandByItem: Map<string, number>
+): ConsumeFirstSettlement | null {
+ const perAssembly = Number(line.quantity ?? 0);
+ const onHand = (id: string) => onHandByItem.get(id) ?? 0;
+
+ const from = consumeFirstSwappedFrom(line, rules);
+ if (from && keepsLineOnPredecessor(onHand(from.itemId), perAssembly / from.factor)) {
+ return { kind: "revert", toItemId: from.itemId, factor: 1 / from.factor };
+ }
+
+ const predecessor = (rules.predecessorsBySuccessor.get(line.itemId) ?? []).find(
+ (p) => keepsLineOnPredecessor(onHand(p.itemId), perAssembly / p.factor)
+ );
+ if (predecessor) {
+ return {
+ kind: "pullBack",
+ toItemId: predecessor.itemId,
+ factor: 1 / predecessor.factor,
+ };
+ }
+
+ const successor = rules.successorByPredecessor.get(line.itemId);
+ if (successor && !keepsLineOnPredecessor(onHand(line.itemId), perAssembly)) {
+ return { kind: "push", toItemId: successor.itemId, factor: successor.factor };
+ }
+ return null;
+}
+
+export function buildConsumeFirstHops(
+ supersessions: SupersessionRow[],
+ asOfDate: string
+): Map<string, Redirect> {
+ const byItem = new Map<string, SupersessionRow>();
+ for (const s of supersessions) byItem.set(s.itemId, s);
+ const effective = (s: SupersessionRow | undefined) =>
+ !!s &&
+ !!s.successorItemId &&
+ REDIRECTING_MODES.has(s.supersessionMode) &&
+ (!s.successorEffectivityDate || s.successorEffectivityDate <= asOfDate);
+
+ const chainTerminates = (oldId: string): boolean => {
+ const walked = new Set<string>([oldId]);
+ let current = byItem.get(oldId)!.successorItemId!;
+ while (effective(byItem.get(current))) {
+ if (walked.has(current)) return false;
+ walked.add(current);
+ current = byItem.get(current)!.successorItemId!;
+ }
+ return true;
+ };
+
+ const hops = new Map<string, Redirect>();
+ for (const [oldId, start] of byItem) {
+ if (start.supersessionMode !== "Consume First" || !effective(start)) {
+ continue;
+ }
+ if (!chainTerminates(oldId)) continue;
+ let to = start.successorItemId!;
+ let factor = Number(start.conversionFactor ?? 1) || 1;
+ const seen = new Set<string>([oldId]);
+ let next = byItem.get(to);
+ while (
+ effective(next) &&
+ next!.supersessionMode !== "Consume First" &&
+ !seen.has(to)
+ ) {
+ seen.add(to);
+ factor *= Number(next!.conversionFactor ?? 1) || 1;
+ to = next!.successorItemId!;
+ next = byItem.get(to);
+ }
+ hops.set(oldId, { to, factor });
+ }
+ return hops;
+}
+
+export function firstStockedInConsumeFirstChain(
+ itemId: string,
+ perAssembly: number,
+ hops: Map<string, Redirect>,
+ onHandByItem: Map<string, number>
+): { itemId: string; factor: number } | null {
+ let current = itemId;
+ let factor = 1;
+ const seen = new Set<string>();
+ while (hops.has(current) && !seen.has(current)) {
+ seen.add(current);
+ if (
+ onHandByItem.has(current) &&
+ keepsLineOnPredecessor(onHandByItem.get(current), perAssembly * factor)
+ ) {
+ return { itemId: current, factor };
+ }
+ const hop = hops.get(current)!;
+ factor *= hop.factor;
+ current = hop.to;
+ }
+ return null;
+}
+
+export type SupersessionContext = {
+ redirect: Map<string, Redirect>;
+ consumeFirstOnHand: Map<string, number>;
+ consumeFirstHops: Map<string, Redirect>;
+ boughtSuccessors: Set<string>;
+};
+
+export function resolveMadeLinePull(
+ itemId: string,
+ perAssembly: number,
+ ctx: SupersessionContext
+): { itemId: string; factor: number } | null {
+ const stocked = firstStockedInConsumeFirstChain(
+ itemId,
+ perAssembly,
+ ctx.consumeFirstHops,
+ ctx.consumeFirstOnHand
+ );
+ if (stocked) return stocked;
+ const redirect = ctx.redirect.get(itemId);
+ if (redirect && ctx.boughtSuccessors.has(redirect.to)) {
+ return { itemId: redirect.to, factor: redirect.factor };
+ }
+ return null;
+}
+
+export function reserveConsumeFirstStock(
+ line: {
+ itemId: string;
+ quantity: number | string | null;
+ estimatedQuantity: number | string | null;
+ scrapQuantity: number | string | null;
+ },
+ settlement: ConsumeFirstSettlement | null,
+ rules: ConsumeFirstRules,
+ onHandByItem: Map<string, number>
+): void {
+ const target = Math.max(
+ 0,
+ Number(line.estimatedQuantity ?? 0) - Number(line.scrapQuantity ?? 0)
+ );
+ let itemId = line.itemId;
+ let factor = 1;
+ if (settlement) {
+ if (settlement.kind === "push") return;
+ itemId = settlement.toItemId;
+ factor = settlement.factor;
+ } else if (!rules.successorByPredecessor.has(line.itemId)) {
+ return;
+ }
+ if (!onHandByItem.has(itemId)) return;
+ const perAssembly = Number(line.quantity ?? 0) * factor;
+ const reserved = Math.min(
+ target * factor,
+ consumableInWholeAssemblies(onHandByItem.get(itemId) ?? 0, perAssembly)
+ );
+ onHandByItem.set(itemId, Math.max(0, (onHandByItem.get(itemId) ?? 0) - reserved));
+}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a70da7c666..50d394cdaf 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -70458,6 +70458,7 @@ export type Database = {
leadTime: number | null
locationId: string | null
parentMaterialId: string | null
+ quantityPerParent: number | null
quantityToIssue: number | null
replenishmentSystem:
| Database["public"]["Enums"]["itemReplenishmentSystem"]
@@ -81633,6 +81634,17 @@ export type Database = {
thumbnailPath: string
}[]
}
+ get_lineside_credit: {
+ Args: {
+ p_company_id: string
+ p_item_id: string
+ p_job_id: string
+ p_job_material_id: string
+ p_location_id: string
+ p_storage_unit_id: string
+ }
+ Returns: number
+ }
get_maintenance_dispatches_by_location: {
Args: { p_company_id: string; p_location_id: string }
Returns: {
diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.ts
index 6b87d960b9..f4bec87215 100644
--- a/packages/database/supabase/functions/post-picking/index.ts
+++ b/packages/database/supabase/functions/post-picking/index.ts
@@ -12,6 +12,7 @@ import {
buildMergeRecords
} from "../shared/batch-split.ts";
import { round } from "../shared/precision.ts";
+import { getPickedBudgets, orderOldFirst } from "../lib/picked-consumption.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -1007,7 +1008,12 @@ serve(async (req: Request) => {
.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;
+ if (
+ (job.status !== "Completed" && job.status !== "Cancelled") ||
+ !job.locationId
+ ) {
+ return;
+ }
await runReturnSweep(trx, {
scope: "job",
@@ -1407,7 +1413,12 @@ async function returnUntrackedMaterialRemainder(
trx: any,
args: {
today: string;
- material: { id: string; itemId: string; quantityIssued: number | string | null };
+ material: {
+ id: string;
+ itemId: string;
+ jobId: string;
+ quantityIssued: number | string | null;
+ };
lines: ReturnSweepLine[];
owed: number;
locationId: string;
@@ -1428,9 +1439,21 @@ async function returnUntrackedMaterialRemainder(
.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));
+ const budgets = orderOldFirst(
+ await getPickedBudgets(trx, { material, locationId, companyId }),
+ material.itemId
+ );
+ const returnableByItem = new Map<string, number>();
+ let owedRemaining = Math.max(0, owed);
+ for (const budget of budgets) {
+ const hold =
+ budget.factor > 0
+ ? Math.min(budget.available, owedRemaining * budget.factor)
+ : 0;
+ owedRemaining -= budget.factor > 0 ? hold / budget.factor : 0;
+ returnableByItem.set(budget.itemId, Math.max(0, budget.available - hold));
+ }
+ let returnable = [...returnableByItem.values()].reduce((a, b) => a + b, 0);
if (returnable <= 0) return 0;
// Newest-first: return the most recently staged stock, deterministic.
@@ -1458,7 +1481,10 @@ async function returnUntrackedMaterialRemainder(
let totalReturned = 0;
for (const line of staged) {
if (returnable <= 0) break;
- const quantity = Math.min(line.stagedNet, returnable);
+ const itemReturnable = returnableByItem.get(line.itemId) ?? 0;
+ const quantity = Math.min(line.stagedNet, itemReturnable);
+ if (quantity <= 0) continue;
+ returnableByItem.set(line.itemId, itemReturnable - quantity);
// 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).
@@ -1550,6 +1576,7 @@ async function runReturnSweep(
.select([
"id",
"itemId",
+ "jobId",
"jobOperationId",
"quantityIssued",
"estimatedQuantity",
@@ -1615,7 +1642,13 @@ async function runReturnSweep(
await maybeRestoreJobMaterialSource(trx, {
scope,
- material: { id: material.id, quantityIssued: material.quantityIssued },
+ material: {
+ id: material.id,
+ itemId: material.itemId,
+ jobId: material.jobId,
+ quantityIssued: material.quantityIssued
+ },
+ locationId: job.locationId,
userId,
companyId
});
@@ -1633,12 +1666,18 @@ async function maybeRestoreJobMaterialSource(
trx: any,
args: {
scope: "operation" | "job";
- material: { id: string; quantityIssued: number | string | null };
+ material: {
+ id: string;
+ itemId: string;
+ jobId: string;
+ quantityIssued: number | string | null;
+ };
+ locationId: string;
userId: string;
companyId: string;
}
) {
- const { scope, material, userId, companyId } = args;
+ const { scope, material, locationId, userId, companyId } = args;
const liveLines = await trx
.selectFrom("pickingListLine as pll")
@@ -1651,13 +1690,12 @@ async function maybeRestoreJobMaterialSource(
.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 budgets = await getPickedBudgets(trx, {
+ material,
+ locationId,
+ companyId
+ });
+ if (budgets.some((b) => b.available > 0)) return;
}
const sourceLine = liveLines
diff --git a/packages/database/supabase/functions/shared/precision.ts b/packages/database/supabase/functions/shared/precision.ts
index 6922363a04..ed59f014e1 100644
--- a/packages/database/supabase/functions/shared/precision.ts
+++ b/packages/database/supabase/functions/shared/precision.ts
@@ -8,7 +8,8 @@ export const RoundingMode = {
/** Ties away from zero — matches Postgres round(). (Math.round(-2.5) = -2; Postgres = -3.) */
HalfUp: "halfUp",
/** Away from zero to the next step — scrap allowances. */
- Up: "up"
+ Up: "up",
+ Down: "down"
} as const;
export type RoundingMode = (typeof RoundingMode)[keyof typeof RoundingMode];
@@ -27,7 +28,9 @@ export function round(
const fn =
mode === RoundingMode.Up
? (n: number) => Math.sign(n) * Math.ceil(Math.abs(n))
- : (n: number) => Math.sign(n) * Math.round(Math.abs(n));
+ : mode === RoundingMode.Down
+ ? (n: number) => Math.sign(n) * Math.floor(Math.abs(n))
+ : (n: number) => Math.sign(n) * Math.round(Math.abs(n));
return shift(fn(shift(value, scale)), -scale);
}
diff --git a/packages/database/supabase/migrations/20260908211552_picking-supersession-consume-first.sql b/packages/database/supabase/migrations/20260908211552_picking-supersession-consume-first.sql
new file mode 100644
index 0000000000..b6210d2b86
--- /dev/null
+++ b/packages/database/supabase/migrations/20260908211552_picking-supersession-consume-first.sql
@@ -0,0 +1,409 @@
+
+CREATE OR REPLACE FUNCTION get_lineside_credit(
+ p_company_id TEXT,
+ p_location_id TEXT,
+ p_storage_unit_id TEXT,
+ p_item_id TEXT,
+ p_job_id TEXT,
+ p_job_material_id TEXT
+) RETURNS NUMERIC
+LANGUAGE sql
+STABLE
+AS $$
+ WITH on_hand AS (
+ SELECT COALESCE(SUM(il."quantity"), 0) AS qty
+ FROM "itemLedger" il
+ WHERE il."companyId" = p_company_id
+ AND il."itemId" = p_item_id
+ AND il."storageUnitId" = p_storage_unit_id
+ ),
+ claims AS (
+ SELECT pll."jobId", pll."jobMaterialId",
+ SUM(GREATEST(0, COALESCE(pll."quantityPicked", 0) - COALESCE(pll."quantityReturned", 0))) AS staged
+ FROM "pickingListLine" pll
+ JOIN "pickingList" pl ON pl."id" = pll."pickingListId"
+ JOIN "job" j ON j."id" = pll."jobId"
+ WHERE pll."companyId" = p_company_id
+ AND pll."itemId" = p_item_id
+ AND pll."toStorageUnitId" = p_storage_unit_id
+ AND pll."status" <> 'Cancelled'
+ AND pl."status" <> 'Cancelled'
+ AND j."status" IN ('Planned', 'Ready', 'In Progress', 'Paused')
+ GROUP BY pll."jobId", pll."jobMaterialId"
+ ),
+ consumed AS (
+ SELECT il."documentId" AS job_id, GREATEST(0, -SUM(il."quantity")) AS qty
+ FROM "itemLedger" il
+ WHERE il."companyId" = p_company_id
+ AND il."locationId" = p_location_id
+ AND il."storageUnitId" = p_storage_unit_id
+ AND il."itemId" = p_item_id
+ AND il."documentType" = 'Job Consumption'
+ GROUP BY il."documentId"
+ ),
+ per_job AS (
+ SELECT c."jobId", SUM(c.staged) AS staged, COALESCE(MAX(k.qty), 0) AS consumed
+ FROM claims c
+ LEFT JOIN consumed k ON k.job_id = c."jobId"
+ GROUP BY c."jobId"
+ ),
+ claimed AS (
+ SELECT COALESCE(SUM(GREATEST(0, staged - consumed)), 0) AS qty FROM per_job
+ ),
+ own AS (
+ SELECT GREATEST(
+ 0,
+ COALESCE((SELECT SUM(staged) FROM claims WHERE "jobMaterialId" = p_job_material_id), 0)
+ - COALESCE((SELECT qty FROM consumed WHERE job_id = p_job_id), 0)
+ ) AS qty
+ )
+ SELECT (SELECT qty FROM own) + GREATEST(0, (SELECT qty FROM on_hand) - (SELECT qty FROM claimed));
+$$;
+
+CREATE OR REPLACE FUNCTION get_picking_schedule(
+ p_location_id TEXT,
+ p_company_id TEXT,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "jobOperationId" TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobReadableId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "operationDescription" TEXT,
+ "processName" TEXT,
+ "workCenterId" TEXT,
+ "workCenterName" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "deadlineType" "deadlineType",
+ "dueDate" DATE,
+ "customerId" TEXT,
+ "customerName" TEXT,
+ "salesOrderId" TEXT,
+ "salesOrderLineId" TEXT,
+ "salesOrderReadableId" TEXT,
+ "thumbnailPath" TEXT,
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "tags" TEXT[],
+ "partsToPickCount" BIGINT,
+ "totalQuantityToPick" NUMERIC
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+AS $$
+ WITH
+ picks AS (
+ SELECT
+ jo2."id" AS "jobOperationId",
+ COUNT(*) AS "partsToPickCount",
+ SUM(jm."quantityToIssue") AS "totalQuantityToPick"
+ FROM "jobMaterial" jm
+ LEFT JOIN LATERAL (
+ SELECT fo."id"
+ FROM "jobOperation" fo
+ WHERE jm."jobOperationId" IS NULL
+ AND fo."jobMakeMethodId" = jm."jobMakeMethodId"
+ AND fo."companyId" = p_company_id
+ AND fo."status" NOT IN ('Done', 'Canceled')
+ ORDER BY fo."order" ASC, fo."id" ASC
+ LIMIT 1
+ ) first_op ON true
+ JOIN "jobOperation" jo2
+ ON jo2."id" = COALESCE(jm."jobOperationId", first_op."id")
+ LEFT JOIN LATERAL (
+ SELECT s.*
+ FROM "itemSupersession" s
+ WHERE s."companyId" = p_company_id
+ AND s."itemId" IN (jm."substitutedFromItemId", jm."itemId")
+ ORDER BY
+ (s."itemId" = jm."itemId"
+ AND s."successorItemId" = jm."substitutedFromItemId") IS TRUE DESC,
+ (s."itemId" = jm."substitutedFromItemId") IS TRUE DESC
+ LIMIT 1
+ ) ss ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ CASE
+ WHEN ss."itemId" IS NULL THEN NULL
+ WHEN ss."itemId" = jm."substitutedFromItemId" THEN jm."itemId"
+ WHEN ss."successorItemId" IS NOT NULL
+ AND (ss."successorEffectivityDate" IS NULL
+ OR ss."successorEffectivityDate" <= (now() AT TIME ZONE 'UTC')::date)
+ THEN ss."successorItemId"
+ ELSE NULL
+ END AS "successorItemId"
+ ) res ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ CASE
+ WHEN ss."itemId" = jm."substitutedFromItemId"
+ AND COALESCE(jm."substitutionFactor", 0) > 0
+ THEN jm."quantity" / jm."substitutionFactor"
+ ELSE jm."quantity"
+ END AS "perAssemblyOld"
+ ) per ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ CASE
+ WHEN ss."supersessionMode" = 'Consume First' THEN
+ COALESCE((
+ SELECT SUM(bin.qty)
+ FROM (
+ SELECT SUM(il."quantity") AS qty
+ FROM "itemLedger" il
+ WHERE il."itemId" = ss."itemId"
+ AND il."companyId" = p_company_id
+ AND il."locationId" = p_location_id
+ AND get_effective_work_center_id(il."storageUnitId") IS NULL
+ GROUP BY il."storageUnitId"
+ HAVING SUM(il."quantity") > 0
+ ) bin
+ ), 0) >= GREATEST(COALESCE(per."perAssemblyOld", 0), 0)
+ AND COALESCE((
+ SELECT SUM(bin.qty)
+ FROM (
+ SELECT SUM(il."quantity") AS qty
+ FROM "itemLedger" il
+ WHERE il."itemId" = ss."itemId"
+ AND il."companyId" = p_company_id
+ AND il."locationId" = p_location_id
+ AND get_effective_work_center_id(il."storageUnitId") IS NULL
+ GROUP BY il."storageUnitId"
+ HAVING SUM(il."quantity") > 0
+ ) bin
+ ), 0) > 0
+ ELSE EXISTS (
+ SELECT 1 FROM "itemLedger" il
+ WHERE il."itemId" = ss."itemId"
+ AND il."companyId" = p_company_id
+ AND il."locationId" = p_location_id
+ AND get_effective_work_center_id(il."storageUnitId") IS NULL
+ GROUP BY il."storageUnitId"
+ HAVING SUM(il."quantity") > 0
+ )
+ END AS "predecessorInStock",
+ EXISTS (
+ SELECT 1 FROM "itemLedger" il
+ WHERE il."itemId" = res."successorItemId"
+ AND il."companyId" = p_company_id
+ AND il."locationId" = p_location_id
+ AND get_effective_work_center_id(il."storageUnitId") IS NULL
+ GROUP BY il."storageUnitId"
+ HAVING SUM(il."quantity") > 0
+ ) AS "successorInStock"
+ WHERE ss."supersessionMode" IN ('Consume First', 'Prefer New')
+ AND res."successorItemId" IS NOT NULL
+ ) stk ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ CASE
+ WHEN ss."itemId" IS NULL THEN jm."itemId"
+ WHEN ss."itemId" = jm."substitutedFromItemId" THEN
+ CASE
+ WHEN ss."supersessionMode" = 'Consume First'
+ AND COALESCE(stk."predecessorInStock", true)
+ THEN jm."substitutedFromItemId"
+ WHEN ss."supersessionMode" = 'Prefer New'
+ AND NOT COALESCE(stk."successorInStock", true)
+ AND COALESCE(stk."predecessorInStock", true)
+ THEN jm."substitutedFromItemId"
+ ELSE jm."itemId"
+ END
+ WHEN ss."supersessionMode" = 'Consume First' THEN
+ CASE
+ WHEN res."successorItemId" IS NOT NULL
+ AND NOT COALESCE(stk."predecessorInStock", true)
+ AND COALESCE(stk."successorInStock", true)
+ THEN res."successorItemId"
+ ELSE jm."itemId"
+ END
+ WHEN ss."supersessionMode" = 'Prefer New' THEN
+ CASE
+ WHEN res."successorItemId" IS NOT NULL
+ AND (COALESCE(stk."successorInStock", true)
+ OR NOT COALESCE(stk."predecessorInStock", true))
+ THEN res."successorItemId"
+ ELSE jm."itemId"
+ END
+ WHEN ss."supersessionMode" = 'Stock Only' THEN res."successorItemId"
+ WHEN ss."supersessionMode" = 'No Stock' THEN NULL
+ ELSE jm."itemId"
+ END AS "pickItemId"
+ ) pick ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ pick."pickItemId",
+ CASE
+ WHEN pick."pickItemId" IS NULL OR pick."pickItemId" = jm."itemId" THEN 1
+ WHEN pick."pickItemId" = jm."substitutedFromItemId" THEN
+ CASE
+ WHEN COALESCE(jm."substitutionFactor", 0) > 0
+ THEN 1 / jm."substitutionFactor"
+ ELSE 1
+ END
+ ELSE COALESCE(ss."conversionFactor", 1)
+ END AS "pickFactor"
+ ) pit ON true
+ LEFT JOIN LATERAL (
+ SELECT su."id"
+ FROM "storageUnit" su
+ WHERE su."workCenterId" = jo2."workCenterId"
+ AND su."companyId" = p_company_id
+ ORDER BY su."isWorkCenterDefault" DESC, su."createdAt" ASC
+ LIMIT 1
+ ) wcl ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ CASE
+ WHEN ss."itemId" = jm."substitutedFromItemId"
+ AND COALESCE(jm."substitutionFactor", 0) > 0
+ THEN jm."quantityToIssue" / jm."substitutionFactor"
+ ELSE jm."quantityToIssue"
+ END AS need_old,
+ CASE
+ WHEN ss."itemId" = jm."substitutedFromItemId"
+ AND COALESCE(jm."substitutionFactor", 0) > 0
+ THEN jm."substitutionFactor"
+ ELSE GREATEST(COALESCE(ss."conversionFactor", 1), 0)
+ END AS new_per_old,
+ CASE WHEN wcl."id" IS NULL THEN 0 ELSE get_lineside_credit(
+ p_company_id, p_location_id, wcl."id", ss."itemId", jm."jobId", jm."id"
+ ) END AS staged_old,
+ CASE WHEN wcl."id" IS NULL OR res."successorItemId" IS NULL THEN 0 ELSE get_lineside_credit(
+ p_company_id, p_location_id, wcl."id", res."successorItemId", jm."jobId", jm."id"
+ ) END AS staged_new
+ ) cf ON true
+ WHERE jm."companyId" = p_company_id
+ AND jm."quantityToIssue" > 0
+ AND jm."methodType" != 'Make to Order'
+ AND pit."pickItemId" IS NOT NULL
+ AND (
+ wcl."id" IS NULL
+ OR CASE
+ WHEN ss."supersessionMode" = 'Consume First'
+ AND res."successorItemId" IS NOT NULL
+ AND COALESCE(per."perAssemblyOld", 0) > 0
+ AND cf.new_per_old > 0
+ THEN
+ floor(GREATEST(cf.staged_old, 0) / per."perAssemblyOld") * per."perAssemblyOld"
+ + floor(GREATEST(cf.staged_new, 0) / (per."perAssemblyOld" * cf.new_per_old)) * per."perAssemblyOld"
+ < cf.need_old
+ ELSE get_lineside_credit(
+ p_company_id, p_location_id, wcl."id", pit."pickItemId", jm."jobId", jm."id"
+ ) < jm."quantityToIssue" * pit."pickFactor"
+ END
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM "pickingListLine" pll
+ JOIN "pickingList" pl ON pl."id" = pll."pickingListId"
+ WHERE pll."jobOperationId" = jo2."id"
+ AND pll."status" <> 'Cancelled'
+ AND pl."status" IN ('Draft', 'In Progress', 'Partial')
+ )
+ GROUP BY jo2."id"
+ )
+ SELECT
+ jo."id" AS "jobOperationId",
+ j."id" AS "jobId",
+ jo."jobMakeMethodId",
+ j."jobId" AS "jobReadableId",
+ i."id" AS "itemId",
+ i."readableId" AS "itemReadableId",
+ i."name" AS "itemDescription",
+ jo."order" AS "operationOrder",
+ jo."description" AS "operationDescription",
+ p."name" AS "processName",
+ jo."workCenterId",
+ wc."name" AS "workCenterName",
+ CASE WHEN j."status" = 'Paused' THEN 'Paused'::"jobOperationStatus" ELSE jo."status" END AS "operationStatus",
+ j."deadlineType",
+ jo."dueDate",
+ j."customerId",
+ c."name" AS "customerName",
+ j."salesOrderId",
+ j."salesOrderLineId",
+ so."salesOrderId" AS "salesOrderReadableId",
+ COALESCE(mu."thumbnailPath", i."thumbnailPath") AS "thumbnailPath",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."tags",
+ pk."partsToPickCount",
+ pk."totalQuantityToPick"
+ FROM picks pk
+ JOIN "jobOperation" jo ON jo."id" = pk."jobOperationId"
+ JOIN "job" j ON jo."jobId" = j."id"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm."id"
+ LEFT JOIN "item" i ON jmm."itemId" = i."id"
+ LEFT JOIN "process" p ON jo."processId" = p."id"
+ LEFT JOIN "workCenter" wc ON jo."workCenterId" = wc."id"
+ LEFT JOIN "customer" c ON j."customerId" = c."id"
+ LEFT JOIN "salesOrder" so ON j."salesOrderId" = so."id"
+ LEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu."id"
+ WHERE j."companyId" = p_company_id
+ AND j."locationId" = p_location_id
+ AND j."status" IN ('Ready', 'In Progress', 'Paused')
+ AND jo."status" NOT IN ('Done', 'Canceled')
+ AND (
+ p_search IS NULL OR p_search = ''
+ OR j."jobId" ILIKE '%' || p_search || '%'
+ OR i."readableId" ILIKE '%' || p_search || '%'
+ OR jo."description" ILIKE '%' || p_search || '%'
+ )
+ ORDER BY jo."dueDate" NULLS LAST, j."jobId";
+$$;
+
+CREATE OR REPLACE VIEW "openJobMaterialLines" AS (
+ SELECT
+ jm."id",
+ jm."jobId",
+ jmm."parentMaterialId",
+ jm."jobMakeMethodId",
+ j."jobId" as "jobReadableId",
+ jm."itemId",
+ jm."quantityToIssue",
+ jm."unitOfMeasureCode",
+ jm."companyId",
+ i1."replenishmentSystem",
+ i1."itemTrackingType",
+ ir."leadTime" AS "leadTime",
+ j."locationId",
+ j."dueDate",
+ jm."quantity" AS "quantityPerParent"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ INNER JOIN "jobMakeMethod" jmm ON jm."jobMakeMethodId" = jmm."id"
+ INNER JOIN "item" i1 ON jm."itemId" = i1."id"
+ INNER JOIN "item" i2 ON j."itemId" = i2."id"
+ INNER JOIN "itemReplenishment" ir ON i2."id" = ir."itemId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+);
diff --git a/packages/database/supabase/migrations/20260916090000_picking-list-line-realtime.sql b/packages/database/supabase/migrations/20260916090000_picking-list-line-realtime.sql
new file mode 100644
index 0000000000..37aa67b400
--- /dev/null
+++ b/packages/database/supabase/migrations/20260916090000_picking-list-line-realtime.sql
@@ -0,0 +1 @@
+ALTER PUBLICATION supabase_realtime ADD TABLE "pickingListLine";
diff --git a/packages/ee/src/planning/mrp/mrp.ts b/packages/ee/src/planning/mrp/mrp.ts
index 407cd85372..e83df605d6 100644
--- a/packages/ee/src/planning/mrp/mrp.ts
+++ b/packages/ee/src/planning/mrp/mrp.ts
@@ -11,11 +11,16 @@ import {
makeActualKey,
makeKey,
makeLocationItemKey,
+ netConsumeFirstContributors,
type ReplenishmentSystem,
splitActualKey,
splitKey
} from "@carbon/database/mrp-engine";
-import { buildSupersessionRedirectMap } from "@carbon/database/supersession-pick";
+import {
+ buildConsumeFirstHops,
+ buildSupersessionRedirectMap,
+ type Redirect
+} from "@carbon/database/supersession-pick";
import {
type CalendarDate,
parseDate,
@@ -214,7 +219,7 @@ export async function runMrp(
// JS Date objects, which parseDate() can't take.
const supersessions = await fetchAll<{
itemId: string;
- supersessionMode: string;
+ supersessionMode: Database["public"]["Enums"]["supersessionMode"];
successorItemId: string | null;
successorEffectivityDate: string | null;
conversionFactor: number | null;
@@ -231,7 +236,7 @@ export async function runMrp(
const supersessionByItem = new Map<
string,
{
- supersessionMode: string;
+ supersessionMode: Database["public"]["Enums"]["supersessionMode"];
successorItemId: string | null;
successorEffectivityDate: string | null;
conversionFactor: number;
@@ -256,6 +261,10 @@ export async function runMrp(
supersessions.data ?? [],
today.toString()
);
+ const consumeFirstHops = buildConsumeFirstHops(
+ supersessions.data ?? [],
+ today.toString()
+ );
// Bulk-load inventory by location+item from the trigger-maintained
// aggregate: transactionally current and an indexed read of a few hundred
@@ -544,7 +553,8 @@ export async function runMrp(
sourceType: "Job Material",
jobId: line.jobId,
parentItemId: line.itemId,
- quantity: line.quantityToIssue
+ quantity: line.quantityToIssue,
+ perAssemblyQuantity: Number(line.quantityPerParent) || undefined
});
topLevelContributors.set(key, contributors);
}
@@ -559,16 +569,31 @@ export async function runMrp(
// outright (the old part stays available only as a manual fallback). The
// effectivity check is item-level: redirection begins on the first MRP run
// on/after successorEffectivityDate.
- for (const [oldItemId, { to: successorId, factor }] of redirectByItem) {
+ const remainingConsumeFirstOnHand = new Map<string, number>();
+ const redirectOrder: string[] = [];
+ const ordered = new Set<string>();
+ const orderAfterHops = (id: string) => {
+ if (ordered.has(id) || !redirectByItem.has(id)) return;
+ ordered.add(id);
+ const next = consumeFirstHops.get(id)?.to;
+ if (next) orderAfterHops(next);
+ redirectOrder.push(id);
+ };
+ for (const id of redirectByItem.keys()) orderAfterHops(id);
+ redirectOrder.reverse();
+ for (const oldItemId of redirectOrder) {
+ const collapsed = redirectByItem.get(oldItemId)!;
const consumeOnHand =
supersessionByItem.get(oldItemId)?.supersessionMode === "Consume First";
+ const { to: successorId, factor } =
+ (consumeOnHand ? consumeFirstHops.get(oldItemId) : undefined) ??
+ collapsed;
for (const location of locations.data) {
// Consume First draws down the old item's on-hand before redirecting.
+ const locationItemKey = makeLocationItemKey(location.id, oldItemId);
let oldOnHand = consumeOnHand
- ? (baseInventoryByLocationItem.get(
- makeLocationItemKey(location.id, oldItemId)
- ) ?? 0)
+ ? (baseInventoryByLocationItem.get(locationItemKey) ?? 0)
: 0;
for (const period of periods) {
@@ -576,33 +601,82 @@ export async function runMrp(
const demand = grossDemand.get(oldKey);
if (!demand) continue;
- const consumed = Math.min(oldOnHand, demand);
- oldOnHand -= consumed;
+ const contributors = topLevelContributors.get(oldKey) ?? [];
+ topLevelContributors.delete(oldKey);
+ const netted = netConsumeFirstContributors({
+ itemId: oldItemId,
+ contributors,
+ grossQty: demand,
+ running: consumeOnHand ? oldOnHand : 0,
+ factor,
+ perAssemblyOf: (c) => c.perAssemblyQuantity ?? 0
+ });
+ const consumed = netted.consumed;
+ if (consumeOnHand) oldOnHand = netted.running;
+ const movedContributors = netted.moved;
// Convert the redirected (old-part) shortfall into successor units.
const redirect = (demand - consumed) * factor;
grossDemand.delete(oldKey);
- const contributors = topLevelContributors.get(oldKey);
- topLevelContributors.delete(oldKey);
+
+ const keptShare = demand > 0 ? consumed / demand : 1;
+ const sumByType = (list: DemandContributor[], type: string) =>
+ list
+ .filter((c) => c.sourceType === type)
+ .reduce((sum, c) => sum + c.quantity, 0);
+ for (const [actuals, sourceType] of [
+ [jobMaterialDemandByKey, "Job Material"],
+ [salesDemandByKey, "Sales Order"]
+ ] as const) {
+ const actualKey = makeActualKey(
+ oldItemId,
+ location.id,
+ period.id ?? "",
+ sourceType
+ );
+ const actual = actuals.get(actualKey);
+ if (!actual) continue;
+ const attributed = contributors.some(
+ (c) => c.sourceType === sourceType
+ );
+ const kept = attributed
+ ? Math.min(actual, sumByType(netted.kept, sourceType))
+ : actual * keptShare;
+ if (kept > 0) actuals.set(actualKey, kept);
+ else actuals.delete(actualKey);
+ const moved = attributed
+ ? sumByType(movedContributors, sourceType)
+ : (actual - kept) * factor;
+ if (moved > 0) {
+ const newActualKey = makeActualKey(
+ successorId,
+ location.id,
+ period.id ?? "",
+ sourceType
+ );
+ actuals.set(
+ newActualKey,
+ (actuals.get(newActualKey) ?? 0) + moved
+ );
+ }
+ }
if (redirect > 0) {
const newKey = makeKey(location.id, period.id ?? "", successorId);
grossDemand.set(newKey, (grossDemand.get(newKey) ?? 0) + redirect);
- if (contributors) {
- // Mark the moved demand so it can be shown as redirected from the
- // old part on the successor's planning row (in successor units).
- const stamped = contributors.map((c) => ({
- ...c,
- quantity: c.quantity * factor,
- redirectedFromItemId: oldItemId
- }));
+ if (movedContributors.length > 0) {
topLevelContributors.set(
newKey,
- (topLevelContributors.get(newKey) ?? []).concat(stamped)
+ (topLevelContributors.get(newKey) ?? []).concat(
+ movedContributors
+ )
);
}
}
}
+ if (consumeOnHand) {
+ remainingConsumeFirstOnHand.set(locationItemKey, oldOnHand);
+ }
}
}
@@ -628,29 +702,40 @@ export async function runMrp(
// generates the successor's demand instead of the old part's. (Top-level
// demand was handled above; component demand is created here, during
// explosion, so it must be redirected at the BOM level.)
+ const consumeFirstRedirect = new Map<string, Redirect>(consumeFirstHops);
if (redirectByItem.size > 0) {
for (const children of bomByItem.values()) {
for (const child of children) {
const redirect = redirectByItem.get(child.itemId);
- if (redirect) {
- child.redirectedFromItemId = child.itemId;
- child.itemId = redirect.to;
- // 1 old part = `factor` successors.
- child.quantity = child.quantity * redirect.factor;
+ if (!redirect) continue;
+ if (
+ supersessionByItem.get(child.itemId)?.supersessionMode ===
+ "Consume First"
+ ) {
+ continue;
}
+ child.redirectedFromItemId = child.itemId;
+ child.itemId = redirect.to;
+ child.quantity = child.quantity * redirect.factor;
}
}
}
+ const onHandForExplosion = new Map(baseInventoryByLocationItem);
+ for (const [locationItemKey, remaining] of remainingConsumeFirstOnHand) {
+ onHandForExplosion.set(locationItemKey, remaining);
+ }
+
const { bomDerivedDemand, demandContributors, cycleItemIds } = explodeBom({
grossDemand,
bomByItem,
replenishmentSystemByItem,
leadTimeByItem,
periods: periods.map((p) => ({ id: p.id ?? "" })),
- onHandByLocationItem: new Map(baseInventoryByLocationItem),
+ onHandByLocationItem: onHandForExplosion,
jobSupplyByLocationPeriodItem: jobAndPoSupplyByLocationPeriodItem,
- topLevelContributors
+ topLevelContributors,
+ consumeFirstRedirect
});
if (cycleItemIds.size > 0) {
diff --git a/packages/form/src/ValidatedForm.tsx b/packages/form/src/ValidatedForm.tsx
index efa4a2ab0d..10d88f174a 100644
--- a/packages/form/src/ValidatedForm.tsx
+++ b/packages/form/src/ValidatedForm.tsx
@@ -385,6 +385,7 @@ export function ValidatedForm<
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
setFieldErrors(backendError?.fieldErrors ?? {});
+ if (backendError?.fieldErrors) endSubmit();
if (!disableFocusOnError && backendError?.fieldErrors) {
focusFirstInvalidInput(
backendError.fieldErrors,
@@ -396,6 +397,7 @@ export function ValidatedForm<
backendError?.fieldErrors,
customFocusHandlers,
disableFocusOnError,
+ endSubmit,
setFieldErrors,
setFieldError
]);
diff --git a/packages/form/src/components/DatePicker.tsx b/packages/form/src/components/DatePicker.tsx
index 0f2071c541..ba4f354bff 100644
--- a/packages/form/src/components/DatePicker.tsx
+++ b/packages/form/src/components/DatePicker.tsx
@@ -5,6 +5,7 @@ import {
DatePicker as DatePickerBase,
FormControl,
FormErrorMessage,
+ FormHelperText,
FormLabel,
LabelWithHelp
} from "@carbon/react";
@@ -86,16 +87,15 @@ const DatePicker = ({
);
useEffect(() => {
- if (value) {
+ if (value !== undefined) {
setDate(safeParseDate(value));
}
}, [value]);
const handleChange = async (newDate: CalendarDate | null) => {
- if (!newDate) return;
const formattedDate = newDate ? newDate.toString() : null;
flushSync(() => {
- setDate(newDate);
+ setDate(newDate ?? undefined);
});
if (inline) {
const result = await validate();
@@ -136,10 +136,14 @@ const DatePicker = ({
maxValue={maxValue}
onChange={handleChange as any}
inline={inline ? DatePickerPreview : undefined}
- helperText={helperText}
+ helperText={inline ? helperText : undefined}
label={label}
/>
- {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ !inline && helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
</FormControl>
);
};
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 495a21e0d8..86cb3d25ef 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} erfolgreich gelöscht"
msgid "{0} draft journal entries"
msgstr "{0} Entwurfs-Buchungszeilen"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} auf Lager für {1} Baugruppen; die verbleibenden {2} werden als {3} kommissioniert"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} auf Lager; die verbleibenden {1} werden als {2} kommissioniert"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} Fertigungsaufträge erstellt"
@@ -1419,6 +1432,9 @@ msgstr "Pfad hinzufügen"
msgid "Add Permissions"
msgstr "Berechtigungen hinzufügen"
+msgid "Add Predecessor"
+msgstr "Vorgänger hinzufügen"
+
msgid "Add Printer"
msgstr "Drucker hinzufügen"
@@ -3489,6 +3505,9 @@ msgstr "Wählen Sie einen batchfähigen Prozess, um die Operationen zu sehen, di
msgid "Choose a company"
msgstr "Wählen Sie ein Unternehmen"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Wählen Sie ein Teil aus, das {itemReadableId} ersetzt. Die Regel wird auf diesem Teil mit {itemReadableId} als Nachfolger gespeichert."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Wählen Sie eine Zeile auf der linken Seite, um zu sehen, woher der Bestand kommen kann."
@@ -7761,6 +7780,9 @@ msgstr "Häufigkeit"
msgid "Friday"
msgstr "Freitag"
+msgid "from"
+msgstr "von"
+
msgid "From"
msgstr "Von"
@@ -8298,6 +8320,9 @@ msgstr "Wie viele der Nachfolger ersetzen ein altes Teil"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Wie viele dieses Werkstoffs benötigt werden, um ein übergeordnetes Teil des Fertigungsauftrags herzustellen; multipliziert mit der Fertigungsauftrag-Menge, um den Verbrauch zu berechnen."
+msgid "How many of this part replace one old part"
+msgstr "Wie viele Einheiten dieses Teils ersetzen ein altes Teil"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Wie viele Einheiten jeder einzelne Auftrag in der Stapelcharge baut; die Menge des letzten Auftrags kann kleiner sein, wenn sich die Gesamtmenge nicht gleichmäßig teilt."
@@ -8485,6 +8510,9 @@ msgstr "Um diese Anfrage in ein Angebot umzuwandeln, muss ein Kunde vorhanden se
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Um diese RFQ an Lieferanten zu senden, müssen Sie zunächst Lieferanten zur RFQ hinzufügen."
+msgid "in place of this item"
+msgstr "anstelle von diesem Artikel"
+
msgid "In Process Only"
msgstr "Nur in Bearbeitung"
@@ -8509,6 +8537,9 @@ msgstr "Auf Lager"
msgid "In stock only"
msgstr "Nur auf Lager"
+msgid "In stock, the remainder as {substitute}"
+msgstr "Auf Lager; der Rest wird als {substitute} kommissioniert"
+
msgid "In the loop together"
msgstr "Im Prozess dabei"
@@ -11891,6 +11922,12 @@ msgstr "Optionale feste Rate, die bei der Umrechnung von Eigenkapitalsalden nach
msgid "Optional pages & sections"
msgstr "Optionale Seiten & Abschnitte"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Optional. Beendet neue Kaufvorschläge nach diesem Datum."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Optional. Beendet neue Kaufvorschläge für den alten Teil nach diesem Datum."
+
msgid "Options"
msgstr "Optionen"
@@ -11906,6 +11943,10 @@ msgstr "Oder geben Sie dieses Geheimnis manuell ein:"
msgid "Order"
msgstr "Bestellung"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "{0} × {substitute} für diesen Fertigungsauftrag bestellen"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "{0} für diesen Auftrag bestellen"
@@ -12130,6 +12171,9 @@ msgstr "Teile"
msgid "Part"
msgstr "Teil"
+msgid "Part Being Replaced"
+msgstr "Zu ersetzender Teil"
+
msgid "Part Details"
msgstr "Teildetails"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Verfolgtes Element auswählen"
+msgid "Picked"
+msgstr "Kommissioniert"
+
msgid "Picked and consumed as separate components"
msgstr "Als separate Komponenten entnommen und verbraucht"
msgid "Picked quantity"
msgstr "Gepickte Menge"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "Kommissionierung anstelle von {substitutedFrom}, dem Artikel auf dem Fertigungsauftrag"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "Kommissionierung anstelle von {substitutedFrom}, dem Artikel auf dem Fertigungsauftrag, für {assemblies} Baugruppen"
+
msgid "Picking Lines"
msgstr "Kommissionierungszeilen"
@@ -16066,6 +16119,12 @@ msgstr "Empfang beenden"
msgid "Stop Shipping"
msgstr "Versand stoppen"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Beendet neue Kaufvorschläge nach diesem Datum."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Beendet neue Kaufvorschläge für den alten Teil nach diesem Datum."
+
msgid "Storage client not available"
msgstr "Speicherclient nicht verfügbar"
@@ -17511,6 +17570,9 @@ msgstr "Diese Fertigungsaufträge haben diesem Arbeitsplatz zugewiesene Arbeitsg
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Diese Buchungssätze sind noch Entwurf, sodass ihre Sollposten und Habenposten nicht im Sachkonto für diesen Zeitraum enthalten sind. Buchen Sie jeden einzelnen oder ändern Sie das Datum zu einem späteren offenen Zeitraum."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Diese Teile werden durch dieses Teil ersetzt. Jede Regel ist auf dem alten Teil konfiguriert; öffnen Sie es, um die Regel zu ändern."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Diese Zeilen verlinken auf Daten außerhalb dieses Unternehmens. Daher kann keine Sicherheitskopie Ihrer aktuellen Daten erstellt werden. Das Löschen kann nicht rückgängig gemacht werden. Sollten diese sich als gemeinsam mit anderen Unternehmen in dieser Gruppe herausstellen, wird nichts gelöscht und die Wiederherstellung wird nicht gestartet."
@@ -18790,6 +18852,9 @@ msgstr "Version:"
msgid "Versions"
msgstr "Versionen"
+msgid "via"
+msgstr "über"
+
msgid "via Digital Quote"
msgstr "über digitales Angebot"
@@ -19205,6 +19270,9 @@ msgstr "Was den Bestand nach oben oder unten getrieben hat, nach beliebiger Dime
msgid "What happens when a journal is dated in a locked period."
msgstr "Was passiert, wenn ein Buchungssatz in einem gesperrten Zeitraum datiert ist."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Was tatsächlich je Teil für diesen Werkstoff zum Linienlager kommissioniert wurde. Eine Kommissionierung kann ein anderes Teil bringen, als der Materialname angibt (eine Aufteilung durch „Zuerst verbrauchen“, ein Ausweichplan durch „Neue bevorzugen“) — hier sehen Sie, welche Teile sich an der Maschine befinden."
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} ist was?"
@@ -19283,6 +19351,9 @@ msgstr "Wann Carbon sich verpflichtet hatte, die Waren ankommen zu lassen; kombi
msgid "When expired stock is used"
msgstr "Wenn abgelaufene Bestände verwendet werden"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Wenn MRP dieses Teil für die Nachfrage des alten Teils nutzt"
+
msgid "When MRP uses the successor for new demand"
msgstr "Wenn MRP den Nachfolger für neuen Bedarf verwendet"
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 4dc43462a3..36d01ac11c 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Verfolgtes Element auswählen"
msgid "Picked"
msgstr "Gepickt"
+msgid "Picked as"
+msgstr "Kommissioniert als"
+
msgid "Picked quantity"
msgstr "Gepickte Menge"
@@ -1044,6 +1047,12 @@ msgstr "Spalte {0} aufgenommen an Position: {1} von {2}"
msgid "Picking"
msgstr "Kommissionierung"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "Kommissionierung anstelle von {substitutedFrom}, dem Artikel im Fertigungsauftrag"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "Kommissionierung anstelle von {substitutedFrom}, dem Artikel im Fertigungsauftrag, für {substitutedAssemblies} Baugruppen"
+
msgid "Pin Out"
msgstr "Abmelden"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 8352db0af9..3411e2f6ec 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} deleted successfully"
msgid "{0} draft journal entries"
msgstr "{0} draft journal entries"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} in stock; the remaining {1} will be picked as {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} jobs created"
@@ -1419,6 +1432,9 @@ msgstr "Add path"
msgid "Add Permissions"
msgstr "Add Permissions"
+msgid "Add Predecessor"
+msgstr "Add Predecessor"
+
msgid "Add Printer"
msgstr "Add Printer"
@@ -3489,6 +3505,9 @@ msgstr "Choose a batchable process to see the operations that can run together."
msgid "Choose a company"
msgstr "Choose a company"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Choose a row on the left to see where its stock can come from."
@@ -7761,6 +7780,9 @@ msgstr "Frequency"
msgid "Friday"
msgstr "Friday"
+msgid "from"
+msgstr "from"
+
msgid "From"
msgstr "From"
@@ -8298,6 +8320,9 @@ msgstr "How many of the successor replace one old part"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
+msgid "How many of this part replace one old part"
+msgstr "How many of this part replace one old part"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
@@ -8485,6 +8510,9 @@ msgstr "In order to convert this RFQ to a quote, it must have a customer."
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
+msgid "in place of this item"
+msgstr "in place of this item"
+
msgid "In Process Only"
msgstr "In Process Only"
@@ -8509,6 +8537,9 @@ msgstr "In stock"
msgid "In stock only"
msgstr "In stock only"
+msgid "In stock, the remainder as {substitute}"
+msgstr "In stock, the remainder as {substitute}"
+
msgid "In the loop together"
msgstr "In the loop together"
@@ -11891,6 +11922,12 @@ msgstr "Optional fixed rate used when translating equity balances per IAS 21 (in
msgid "Optional pages & sections"
msgstr "Optional pages & sections"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Optional. Stops new purchase suggestions after this date."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Optional. Stops new purchase suggestions for the old part after this date."
+
msgid "Options"
msgstr "Options"
@@ -11906,6 +11943,10 @@ msgstr "Or enter this secret manually:"
msgid "Order"
msgstr "Order"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Order {0} × {substitute} for this job"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Order {0} for this job"
@@ -12130,6 +12171,9 @@ msgstr "part"
msgid "Part"
msgstr "Part"
+msgid "Part Being Replaced"
+msgstr "Part Being Replaced"
+
msgid "Part Details"
msgstr "Part Details"
@@ -12409,12 +12453,21 @@ msgstr "Pick the serial numbers on hand that were received from this supplier."
msgid "Pick tracked item"
msgstr "Pick tracked item"
+msgid "Picked"
+msgstr "Picked"
+
msgid "Picked and consumed as separate components"
msgstr "Picked and consumed as separate components"
msgid "Picked quantity"
msgstr "Picked quantity"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "picking in place of {substitutedFrom}, the item on the job"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+
msgid "Picking Lines"
msgstr "Picking Lines"
@@ -16066,6 +16119,12 @@ msgstr "Stop Receiving"
msgid "Stop Shipping"
msgstr "Stop Shipping"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Stops new purchase suggestions after this date."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Stops new purchase suggestions for the old part after this date."
+
msgid "Storage client not available"
msgstr "Storage client not available"
@@ -17511,6 +17570,9 @@ msgstr "These jobs have operations assigned to this work center:"
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
@@ -18790,6 +18852,9 @@ msgstr "Version:"
msgid "Versions"
msgstr "Versions"
+msgid "via"
+msgstr "via"
+
msgid "via Digital Quote"
msgstr "via Digital Quote"
@@ -19205,6 +19270,9 @@ msgstr "What drove inventory up or down, by any dimension"
msgid "What happens when a journal is dated in a locked period."
msgstr "What happens when a journal is dated in a locked period."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+
msgid "What is {translatedTerm}?"
msgstr "What is {translatedTerm}?"
@@ -19283,6 +19351,9 @@ msgstr "When Carbon committed to having the goods arrive; combined with the ship
msgid "When expired stock is used"
msgstr "When expired stock is used"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "When MRP starts using this part for the old part's demand"
+
msgid "When MRP uses the successor for new demand"
msgstr "When MRP uses the successor for new demand"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index 7ddf50fdff..ab0f8d2cfd 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Pick tracked item"
msgid "Picked"
msgstr "Picked"
+msgid "Picked as"
+msgstr "Picked as"
+
msgid "Picked quantity"
msgstr "Picked quantity"
@@ -1044,6 +1047,12 @@ msgstr "Picked up Column {0} at position: {1} of {2}"
msgid "Picking"
msgstr "Picking"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "picking in place of {substitutedFrom}, the item on the job"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+
msgid "Pin Out"
msgstr "Pin Out"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index da8dd15b4c..a01028996f 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} eliminado correctamente"
msgid "{0} draft journal entries"
msgstr "{0} asientos de diario en borrador"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} en existencias, para {1} conjuntos; el restante {2} será preparado como {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} en existencias; el restante {1} será preparado como {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} órdenes de trabajo creadas"
@@ -1419,6 +1432,9 @@ msgstr "Agregar ruta"
msgid "Add Permissions"
msgstr "Agregar Permisos"
+msgid "Add Predecessor"
+msgstr "Agregar predecesor"
+
msgid "Add Printer"
msgstr "Agregar impresora"
@@ -3489,6 +3505,9 @@ msgstr "Elija un proceso agrupable para ver las operaciones que pueden ejecutars
msgid "Choose a company"
msgstr "Elige una empresa"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Selecciona una pieza que {itemReadableId} reemplaza. La regla se guarda en esa pieza con {itemReadableId} como su sucesor."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Elija una fila a la izquierda para ver de dónde puede provenir su stock."
@@ -7761,6 +7780,9 @@ msgstr "Frecuencia"
msgid "Friday"
msgstr "Viernes"
+msgid "from"
+msgstr "desde"
+
msgid "From"
msgstr "Desde"
@@ -8298,6 +8320,9 @@ msgstr "Cuántos del sucesor reemplazan una pieza antigua"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Cuánto de este material se necesita para construir uno del artículo padre del trabajo; se multiplica por cantidad de trabajo para cambiar el tamaño del consumo."
+msgid "How many of this part replace one old part"
+msgstr "Cuántas de esta pieza reemplazan una pieza anterior"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Cuántas unidades construye cada trabajo individual en el lote; la cantidad del último trabajo puede ser más pequeña si la cantidad total no se divide uniformemente."
@@ -8485,6 +8510,9 @@ msgstr "Para convertir esta RFQ a una cotización, debe tener un cliente."
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Para enviar esta RFQ a los proveedores, primero debe agregar proveedores a la RFQ."
+msgid "in place of this item"
+msgstr "en lugar de este artículo"
+
msgid "In Process Only"
msgstr "Solo en proceso"
@@ -8509,6 +8537,9 @@ msgstr "En stock"
msgid "In stock only"
msgstr "Solo en stock"
+msgid "In stock, the remainder as {substitute}"
+msgstr "En existencias, el restante como {substitute}"
+
msgid "In the loop together"
msgstr "En el ciclo juntos"
@@ -11891,6 +11922,12 @@ msgstr "Tasa fija opcional utilizada al traducir saldos de patrimonio según IAS
msgid "Optional pages & sections"
msgstr "Páginas y secciones opcionales"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Opcional. Detiene las sugerencias de compra después de esta fecha."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Opcional. Detiene las sugerencias de compra para la pieza anterior después de esta fecha."
+
msgid "Options"
msgstr "Opciones"
@@ -11906,6 +11943,10 @@ msgstr "O ingrese este código secreto manualmente:"
msgid "Order"
msgstr "Pedido"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Ordenar {0} × {substitute} para esta orden de trabajo"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Pedir {0} para este trabajo"
@@ -12130,6 +12171,9 @@ msgstr "piezas"
msgid "Part"
msgstr "Parte"
+msgid "Part Being Replaced"
+msgstr "Pieza siendo reemplazada"
+
msgid "Part Details"
msgstr "Detalles de la Pieza"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Seleccionar artículo rastreado"
+msgid "Picked"
+msgstr "Preparado"
+
msgid "Picked and consumed as separate components"
msgstr "Seleccionado y consumido como componentes separados"
msgid "Picked quantity"
msgstr "Cantidad recogida"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "picking en lugar de {substitutedFrom}, el artículo en la orden de trabajo"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "picking en lugar de {substitutedFrom}, el artículo en la orden de trabajo, para {assemblies} conjuntos"
+
msgid "Picking Lines"
msgstr "Líneas de Picking"
@@ -16066,6 +16119,12 @@ msgstr "Detener recepción"
msgid "Stop Shipping"
msgstr "Detener envío"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Detiene las sugerencias de compra después de esta fecha."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Detiene las sugerencias de compra para la pieza anterior después de esta fecha."
+
msgid "Storage client not available"
msgstr "Cliente de almacenamiento no disponible"
@@ -17511,6 +17570,9 @@ msgstr "Estas órdenes de trabajo tienen operaciones asignadas a este centro de
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Estos asientos aún están en Borrador, por lo que sus debe y haber no están en el libro mayor para este período. Contabiliza cada uno, o cambia su fecha a un período abierto posterior."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Estas piezas están siendo reemplazadas por ésta. Cada regla se establece en la pieza anterior; ábrela para cambiar la regla."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Estas filas contienen referencias a datos fuera de esta empresa, por lo que no se puede crear una copia de seguridad de los datos actuales. La eliminación de estas filas no se puede deshacer. Si se encuentran compartidas con otras empresas del grupo, nada se eliminará y la restauración no se iniciará."
@@ -18790,6 +18852,9 @@ msgstr "Versión:"
msgid "Versions"
msgstr "Versiones"
+msgid "via"
+msgstr "vía"
+
msgid "via Digital Quote"
msgstr "a través de Cotización Digital"
@@ -19205,6 +19270,9 @@ msgstr "Qué impulsó el inventario hacia arriba o hacia abajo, por cualquier di
msgid "What happens when a journal is dated in a locked period."
msgstr "Qué sucede cuando un asiento se registra en un período bloqueado."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Qué ha sido preparado realmente en pie de línea para este artículo, por pieza. Un picking puede traer una pieza diferente a la que el artículo nombra (una división Consumir primero, una alternativa Preferir nuevo) — aquí es donde ves qué piezas están en la máquina."
+
msgid "What is {translatedTerm}?"
msgstr "¿Qué es {translatedTerm}?"
@@ -19283,6 +19351,9 @@ msgstr "Cuándo Carbon se comprometió a que llegaran los bienes; combinado con
msgid "When expired stock is used"
msgstr "Cuando se utiliza stock vencido"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Cuándo MRP comienza a usar esta pieza para la demanda de la pieza anterior"
+
msgid "When MRP uses the successor for new demand"
msgstr "Cuando MRP utiliza el sucesor para nueva demanda"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index 13b17b3042..5cab7d1afd 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Seleccionar artículo rastreado"
msgid "Picked"
msgstr "Recogido"
+msgid "Picked as"
+msgstr "Preparado como"
+
msgid "Picked quantity"
msgstr "Cantidad recogida"
@@ -1044,6 +1047,12 @@ msgstr "Se tomó la columna {0} en la posición: {1} de {2}"
msgid "Picking"
msgstr "Picking"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "picking en lugar de {substitutedFrom}, el artículo de la orden de trabajo"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "picking en lugar de {substitutedFrom}, el artículo de la orden de trabajo, para {substitutedAssemblies} ensamblajes"
+
msgid "Pin Out"
msgstr "Cerrar sesión con PIN"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 0f87f16134..c07f56fb50 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} supprimé avec succès"
msgid "{0} draft journal entries"
msgstr "{0} écritures de journal brouillon"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} en stock, pour {1} assemblages ; les {2} restants seront prélevés comme {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} en stock ; les {1} restants seront prélevés comme {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} ordres de fabrication créés"
@@ -1419,6 +1432,9 @@ msgstr "Ajouter un chemin"
msgid "Add Permissions"
msgstr "Ajouter des autorisations"
+msgid "Add Predecessor"
+msgstr "Ajouter un prédécesseur"
+
msgid "Add Printer"
msgstr "Ajouter une imprimante"
@@ -3489,6 +3505,9 @@ msgstr "Choisissez un processus regroupable pour voir les opérations qui peuven
msgid "Choose a company"
msgstr "Choisir une société"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Choisissez une pièce que {itemReadableId} remplace. La règle est enregistrée sur cette pièce avec {itemReadableId} comme successeur."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Choisissez une ligne à gauche pour voir d'où son stock peut provenir."
@@ -7761,6 +7780,9 @@ msgstr "Fréquence"
msgid "Friday"
msgstr "Vendredi"
+msgid "from"
+msgstr "de"
+
msgid "From"
msgstr "De"
@@ -8298,6 +8320,9 @@ msgstr "Combien de successeurs remplacent une ancienne pièce"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Combien de ce matériel il faut pour en construire un du pièce parent du travail; multiplié par la quantité de travail pour dimensionner la consommation."
+msgid "How many of this part replace one old part"
+msgstr "Combien de cette pièce remplacent une ancienne pièce"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Combien d'unités chaque travail individuel dans le lot construit; la quantité du dernier travail peut être plus petite si la quantité totale ne se divise pas uniformément."
@@ -8485,6 +8510,9 @@ msgstr "Pour convertir cette demande de devis en devis, elle doit être associé
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Pour envoyer cet appel d'offres aux fournisseurs, vous devez d'abord ajouter des fournisseurs à l'appel d'offres."
+msgid "in place of this item"
+msgstr "à la place de cet article"
+
msgid "In Process Only"
msgstr "En cours uniquement"
@@ -8509,6 +8537,9 @@ msgstr "En stock"
msgid "In stock only"
msgstr "En stock uniquement"
+msgid "In stock, the remainder as {substitute}"
+msgstr "En stock, le reste comme {substitute}"
+
msgid "In the loop together"
msgstr "Dans la boucle ensemble"
@@ -11891,6 +11922,12 @@ msgstr "Taux fixe optionnel utilisé lors de la traduction des soldes des capita
msgid "Optional pages & sections"
msgstr "Pages et sections optionnelles"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Facultatif. Arrête les nouvelles suggestions d'achat après cette date."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Facultatif. Arrête les nouvelles suggestions d'achat pour l'ancienne pièce après cette date."
+
msgid "Options"
msgstr "Options"
@@ -11906,6 +11943,10 @@ msgstr "Ou entrez ce secret manuellement :"
msgid "Order"
msgstr "Commande"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Commander {0} × {substitute} pour cet ordre de fabrication"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Commander {0} pour cette tâche"
@@ -12130,6 +12171,9 @@ msgstr "pièces"
msgid "Part"
msgstr "Pièce"
+msgid "Part Being Replaced"
+msgstr "Pièce remplacée"
+
msgid "Part Details"
msgstr "Détails de la pièce"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Sélectionner un article suivi"
+msgid "Picked"
+msgstr "Prélevé"
+
msgid "Picked and consumed as separate components"
msgstr "Prélevé et consommé comme composants séparés"
msgid "Picked quantity"
msgstr "Quantité prélevée"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "prélèvement à la place de {substitutedFrom}, l'article de l'ordre"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "prélèvement à la place de {substitutedFrom}, l'article de l'ordre, pour {assemblies} assemblages"
+
msgid "Picking Lines"
msgstr "Lignes de prélèvement"
@@ -16066,6 +16119,12 @@ msgstr "Arrêter la réception"
msgid "Stop Shipping"
msgstr "Arrêter l'expédition"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Arrête les nouvelles suggestions d'achat après cette date."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Arrête les nouvelles suggestions d'achat pour l'ancienne pièce après cette date."
+
msgid "Storage client not available"
msgstr "Client de stockage non disponible"
@@ -17511,6 +17570,9 @@ msgstr "Ces ordres de fabrication ont des opérations assignées à ce poste de
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Ces écritures de journal sont encore Brouillon, de sorte que leurs débits et crédits ne se trouvent pas dans le grand livre pour cette période. Comptabilisez chacune ou redatez-la à une période ouverte ultérieure."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Ces pièces sont remplacées par celle-ci. Chaque règle est définie sur l'ancienne pièce ; ouvrez-la pour modifier la règle."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Ces lignes sont liées à des données en dehors de cette Société, c'est pourquoi une copie de sécurité de vos données actuelles ne peut pas être créée. La suppression de ces lignes ne peut pas être annulée. S'il s'avère qu'elles sont partagées avec d'autres Sociétés de ce groupe, rien n'est supprimé et la restauration ne démarre pas."
@@ -18790,6 +18852,9 @@ msgstr "Version :"
msgid "Versions"
msgstr "Versions"
+msgid "via"
+msgstr "via"
+
msgid "via Digital Quote"
msgstr "via Devis Numérique"
@@ -19205,6 +19270,9 @@ msgstr "Ce qui a fait monter ou descendre les stocks, selon un quelconque axe an
msgid "What happens when a journal is dated in a locked period."
msgstr "Ce qui se passe quand une écriture est datée dans une période verrouillée."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Ce qui a été réellement prélevé au bord de ligne pour cette matière, par pièce. Un prélèvement peut apporter une pièce différente de celle nommée par la matière (un fractionnement Consommer d'abord, une substitution Préférer le nouveau) — c'est où vous voyez quelles pièces sont à la machine."
+
msgid "What is {translatedTerm}?"
msgstr "Qu'est-ce que {translatedTerm} ?"
@@ -19283,6 +19351,9 @@ msgstr "Quand Carbon s'est engagé à ce que les marchandises arrivent ; combin
msgid "When expired stock is used"
msgstr "Lorsque du stock expiré est utilisé"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Quand MRP commence à utiliser cette pièce pour la demande de l'ancienne pièce"
+
msgid "When MRP uses the successor for new demand"
msgstr "Quand le MRP utilise le successeur pour les nouveaux besoins"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index c0413ba354..5419d23edb 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Sélectionner un article suivi"
msgid "Picked"
msgstr "Prélevé"
+msgid "Picked as"
+msgstr "Prélevé comme"
+
msgid "Picked quantity"
msgstr "Quantité prélevée"
@@ -1044,6 +1047,12 @@ msgstr "Colonne {0} saisie à la position : {1} sur {2}"
msgid "Picking"
msgstr "Prélèvement"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "Prélèvement à la place de {substitutedFrom}, l'article de l'ordre de fabrication"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "Prélèvement à la place de {substitutedFrom}, l'article de l'ordre de fabrication, pour {substitutedAssemblies} assemblages"
+
msgid "Pin Out"
msgstr "Déconnecter"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 6d8b7bb595..241b7429c2 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} सफलतापूर्वक हटाया गया"
msgid "{0} draft journal entries"
msgstr "{0} ड्राफ्ट जर्नल प्रविष्टियाँ"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} स्टॉक में है, {1} असेंबलीज़ के लिए; शेष {2} को {3} के रूप में पिका जाएगा"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} स्टॉक में है; शेष {1} को {2} के रूप में पिका जाएगा"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} जॉब बनाए गए"
@@ -1419,6 +1432,9 @@ msgstr "पथ जोड़ें"
msgid "Add Permissions"
msgstr "अनुमतियां जोड़ें"
+msgid "Add Predecessor"
+msgstr "पूर्ववर्ती जोड़ें"
+
msgid "Add Printer"
msgstr "प्रिंटर जोड़ें"
@@ -3489,6 +3505,9 @@ msgstr "एक साथ चल सकने वाले ऑपरेशन द
msgid "Choose a company"
msgstr "कंपनी चुनें"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "एक पार्ट चुनें जिसे {itemReadableId} प्रतिस्थापित करता है। नियम उस पार्ट पर सहेजा जाता है जिसमें {itemReadableId} उत्तराधिकारी है।"
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "यह देखने के लिए बाईं ओर की पंक्ति को चुनें कि इसका स्टॉक कहां से आ सकता है।"
@@ -7761,6 +7780,9 @@ msgstr "आवृत्ति"
msgid "Friday"
msgstr "शुक्रवार"
+msgid "from"
+msgstr "से"
+
msgid "From"
msgstr "से"
@@ -8298,6 +8320,9 @@ msgstr "उत्तराधिकारी के कितने एक प
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "इस कार्य की एक मात्रा बनाने के लिए इस सामग्री की कितनी जरूरत है; खपत को आकार देने के लिए कार्य मात्रा से गुणा किया गया।"
+msgid "How many of this part replace one old part"
+msgstr "एक पुराने पार्ट की जगह इस पार्ट की कितनी मात्रा आती है"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "बल्क बैच में प्रत्येक व्यक्तिगत नौकरी कितनी इकाइयों को बनाती है; यदि कुल मात्रा समान रूप से विभाजित नहीं होती है तो अंतिम नौकरी की मात्रा छोटी हो सकती है।"
@@ -8485,6 +8510,9 @@ msgstr "इस RFQ को कोटेशन में परिवर्ति
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "इस RFQ को आपूर्तिकर्ताओं को भेजने के लिए, आपको पहले RFQ में आपूर्तिकर्ता जोड़ने चाहिए।"
+msgid "in place of this item"
+msgstr "इस आइटम की जगह"
+
msgid "In Process Only"
msgstr "केवल प्रक्रिया में"
@@ -8509,6 +8537,9 @@ msgstr "स्टॉक में"
msgid "In stock only"
msgstr "केवल स्टॉक में"
+msgid "In stock, the remainder as {substitute}"
+msgstr "स्टॉक में, शेष {substitute} के रूप में"
+
msgid "In the loop together"
msgstr "एक साथ लूप में"
@@ -11891,6 +11922,12 @@ msgstr "IAS 21 के अनुसार इक्विटी शेष को
msgid "Optional pages & sections"
msgstr "वैकल्पिक पृष्ठ और अनुभाग"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "वैकल्पिक। इस तारीख के बाद नई खरीद सुझाव बंद करता है।"
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "वैकल्पिक। इस तारीख के बाद पुराने पार्ट के लिए नई खरीद सुझाव बंद करता है।"
+
msgid "Options"
msgstr "विकल्प"
@@ -11906,6 +11943,10 @@ msgstr "या इस गुप्त को मैन्युअल रूप
msgid "Order"
msgstr "आदेश"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "इस जॉब के लिए {0} × {substitute} ऑर्डर करें"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "इस कार्य के लिए {0} ऑर्डर करें"
@@ -12130,6 +12171,9 @@ msgstr "भाग"
msgid "Part"
msgstr "पार्ट"
+msgid "Part Being Replaced"
+msgstr "प्रतिस्थापित किया जा रहा पार्ट"
+
msgid "Part Details"
msgstr "भाग विवरण"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "ट्रैक किए गए आइटम को चुनें"
+msgid "Picked"
+msgstr "पिक किया गया"
+
msgid "Picked and consumed as separate components"
msgstr "अलग घटकों के रूप में चुना और उपभोग किया गया"
msgid "Picked quantity"
msgstr "चुना गया मात्रा"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "जॉब पर आइटम {substitutedFrom} की जगह में पिकिंग"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "जॉब पर आइटम {substitutedFrom} की जगह में {assemblies} असेंबलीज़ के लिए पिकिंग"
+
msgid "Picking Lines"
msgstr "पिकिंग लाइनें"
@@ -16066,6 +16119,12 @@ msgstr "प्राप्ति को रोकें"
msgid "Stop Shipping"
msgstr "शिपिंग बंद करें"
+msgid "Stops new purchase suggestions after this date."
+msgstr "इस तारीख के बाद नई खरीद सुझाव बंद करता है।"
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "इस तारीख के बाद पुराने पार्ट के लिए नई खरीद सुझाव बंद करता है।"
+
msgid "Storage client not available"
msgstr "स्टोरेज क्लाइंट उपलब्ध नहीं है"
@@ -17511,6 +17570,9 @@ msgstr "ये जॉब इस वर्क सेंटर को असाइ
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "ये जर्नल प्रविष्टियां अभी भी ड्राफ्ट हैं, इसलिए उनके नामे और जमा इस अवधि के लिए खाता बही में नहीं हैं। प्रत्येक को पोस्ट करें, या इसे बाद की खुली अवधि में फिर से दिनांकित करें।"
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "ये पार्ट्स इसके द्वारा प्रतिस्थापित किए जा रहे हैं। प्रत्येक नियम पुराने पार्ट पर सेट है; नियम बदलने के लिए इसे खोलें।"
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "ये पंक्तियां इस कंपनी के बाहर के डेटा से जुड़ी हुई हैं, इसलिए आपके वर्तमान डेटा की सुरक्षा प्रति नहीं बनाई जा सकती। उन्हें हटाना पूर्ववत नहीं किया जा सकता। यदि वे इस समूह की अन्य कंपनियों के साथ साझा की जाती हैं, तो कुछ भी हटाया नहीं जाता है और पुनर्स्थापन शुरू नहीं होता है।"
@@ -18790,6 +18852,9 @@ msgstr "संस्करण:"
msgid "Versions"
msgstr "संस्करण"
+msgid "via"
+msgstr "के माध्यम से"
+
msgid "via Digital Quote"
msgstr "डिजिटल उद्धरण के माध्यम से"
@@ -19205,6 +19270,9 @@ msgstr "किस चीज़ ने इन्वेंटरी को कि
msgid "What happens when a journal is dated in a locked period."
msgstr "जब कोई जर्नल लॉक की गई अवधि में तारीख दी जाती है तो क्या होता है।"
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "इस सामग्री के लिए प्रति पार्ट लाइनसाइड पर जो वास्तव में पिका गया है। एक पिक सामग्री में नामित पार्ट से अलग पार्ट ला सकता है (एक पहले उपयोग करें विभाजन, एक नए को प्राथमिकता दें फॉलबैक) — यह वह जगह है जहां आप देखते हैं कि कौन से पार्ट्स मशीन पर हैं।"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} क्या है?"
@@ -19283,6 +19351,9 @@ msgstr "जब कार्बन ने माल के आने का व
msgid "When expired stock is used"
msgstr "जब समाप्त हो चुका स्टॉक उपयोग किया जाता है"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "जब MRP इस पार्ट का उपयोग पुराने पार्ट की मांग को पूरा करने के लिए शुरू करता है"
+
msgid "When MRP uses the successor for new demand"
msgstr "जब MRP नई मांग के लिए उत्तराधिकारी का उपयोग करता है"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 69cc8364be..7a7f45757d 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -1032,6 +1032,9 @@ msgstr "ट्रैक किए गए आइटम को चुनें"
msgid "Picked"
msgstr "उठाया गया"
+msgid "Picked as"
+msgstr "के रूप में पिक किया गया"
+
msgid "Picked quantity"
msgstr "चुना गया मात्रा"
@@ -1044,6 +1047,12 @@ msgstr "कॉलम {0} को स्थिति {1} पर उठाया
msgid "Picking"
msgstr "पिकिंग"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "पिकिंग {substitutedFrom} की जगह, जॉब पर आइटम"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "पिकिंग {substitutedFrom} की जगह, जॉब पर आइटम, {substitutedAssemblies} असेंबलीज के लिए"
+
msgid "Pin Out"
msgstr "पिन आउट"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index c6b10bcd52..173beec5a0 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} eliminato con successo"
msgid "{0} draft journal entries"
msgstr "{0} righe di registrazione in bozza"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} in giacenza, per {1} assiemi; il rimanente {2} sarà prelevato come {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} in giacenza; il rimanente {1} sarà prelevato come {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} ordini di produzione creati"
@@ -1419,6 +1432,9 @@ msgstr "Aggiungi percorso"
msgid "Add Permissions"
msgstr "Aggiungi Autorizzazioni"
+msgid "Add Predecessor"
+msgstr "Aggiungi Predecessore"
+
msgid "Add Printer"
msgstr "Aggiungi stampante"
@@ -3489,6 +3505,9 @@ msgstr "Scegli un processo raggruppabile per vedere le operazioni che possono es
msgid "Choose a company"
msgstr "Scegli un'azienda"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Scegli un componente che {itemReadableId} sostituisce. La regola è salvata su quel componente con {itemReadableId} come suo successore."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Scegli una riga a sinistra per vedere da dove può provenire il suo stock."
@@ -7761,6 +7780,9 @@ msgstr "Frequenza"
msgid "Friday"
msgstr "Venerdì"
+msgid "from"
+msgstr "da"
+
msgid "From"
msgstr "Da"
@@ -8298,6 +8320,9 @@ msgstr "Quanti del successore sostituiscono una parte vecchia"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Quanto di questo materiale ci vuole per costruire uno dell'articolo padre del lavoro; moltiplicato per la quantità di lavoro per dimensionare il consumo."
+msgid "How many of this part replace one old part"
+msgstr "Quanti di questo componente sostituiscono un vecchio componente"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Quante unità costruisce ogni singolo lavoro nel lotto; la quantità dell'ultimo lavoro può essere più piccola se la quantità totale non si divide uniformemente."
@@ -8485,6 +8510,9 @@ msgstr "Per convertire questo RFQ in un preventivo, deve avere un cliente."
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Per inviare questa RFQ ai fornitori, devi prima aggiungere fornitori alla RFQ."
+msgid "in place of this item"
+msgstr "al posto di questo articolo"
+
msgid "In Process Only"
msgstr "Solo in corso"
@@ -8509,6 +8537,9 @@ msgstr "Disponibile"
msgid "In stock only"
msgstr "Solo in giacenza"
+msgid "In stock, the remainder as {substitute}"
+msgstr "In giacenza, il rimanente come {substitute}"
+
msgid "In the loop together"
msgstr "Nel giro insieme"
@@ -11891,6 +11922,12 @@ msgstr "Tasso fisso opzionale utilizzato quando si traducono i saldi del patrimo
msgid "Optional pages & sections"
msgstr "Pagine e sezioni opzionali"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Facoltativo. Interrompe le nuove proposte di acquisto dopo questa data."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Facoltativo. Interrompe le nuove proposte di acquisto per il vecchio componente dopo questa data."
+
msgid "Options"
msgstr "Opzioni"
@@ -11906,6 +11943,10 @@ msgstr "Oppure inserisci questo segreto manualmente:"
msgid "Order"
msgstr "Ordine"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Ordina {0} × {substitute} per questo ordine di produzione"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Ordina {0} per questo lavoro"
@@ -12130,6 +12171,9 @@ msgstr "pezzi"
msgid "Part"
msgstr "Parte"
+msgid "Part Being Replaced"
+msgstr "Componente Sostituito"
+
msgid "Part Details"
msgstr "Dettagli Parte"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Seleziona articolo tracciato"
+msgid "Picked"
+msgstr "Prelevato"
+
msgid "Picked and consumed as separate components"
msgstr "Prelevato e consumato come componenti separati"
msgid "Picked quantity"
msgstr "Quantità prelevata"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "prelievo al posto di {substitutedFrom}, l'articolo sull'ordine di produzione"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "prelievo al posto di {substitutedFrom}, l'articolo sull'ordine di produzione, per {assemblies} assiemi"
+
msgid "Picking Lines"
msgstr "Righe di prelievo"
@@ -16066,6 +16119,12 @@ msgstr "Interrompi ricezione"
msgid "Stop Shipping"
msgstr "Arresta spedizione"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Interrompe le nuove proposte di acquisto dopo questa data."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Interrompe le nuove proposte di acquisto per il vecchio componente dopo questa data."
+
msgid "Storage client not available"
msgstr "Client di archiviazione non disponibile"
@@ -17511,6 +17570,9 @@ msgstr "Questi ordini di produzione hanno operazioni assegnate a questo centro d
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Queste voci di prima nota sono ancora Bozza, quindi i loro dare e avere non sono nel registro per questo periodo. Registra ognuno, o ri-datalo in un periodo aperto successivo."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Questi componenti sono sostituiti da questo. Ogni regola è impostata sul vecchio componente; aprilo per modificare la regola."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Queste righe sono collegate a dati esterni a questa azienda, pertanto non è possibile effettuare una copia di sicurezza dei dati attuali. La loro eliminazione non può essere annullata. Se risultano condivise con altre aziende del gruppo, nulla viene eliminato e il ripristino non si avvierà."
@@ -18790,6 +18852,9 @@ msgstr "Versione:"
msgid "Versions"
msgstr "Versioni"
+msgid "via"
+msgstr "tramite"
+
msgid "via Digital Quote"
msgstr "tramite Preventivo Digitale"
@@ -19205,6 +19270,9 @@ msgstr "Cosa ha fatto aumentare o diminuire l'inventario, per qualsiasi dimensio
msgid "What happens when a journal is dated in a locked period."
msgstr "Cosa succede quando una registrazione è datata in un periodo bloccato."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Ciò che è stato effettivamente prelevato al bordo linea per questo materiale, per componente. Un prelievo può portare un componente diverso da quello indicato nel materiale (una suddivisione Consumare prima, una riserva Preferisci Nuovo) — qui puoi vedere quali componenti sono alla macchina."
+
msgid "What is {translatedTerm}?"
msgstr "Cos'è {translatedTerm}?"
@@ -19283,6 +19351,9 @@ msgstr "Quando Carbon si è impegnato ad avere le merci arrivare; combinato con
msgid "When expired stock is used"
msgstr "Quando viene utilizzato stock scaduto"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Quando MRP inizia a utilizzare questo componente per il fabbisogno del vecchio componente"
+
msgid "When MRP uses the successor for new demand"
msgstr "Quando MRP utilizza il successore per nuovo fabbisogno"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 74beebe01c..f3c5710e45 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Seleziona articolo tracciato"
msgid "Picked"
msgstr "Prelevato"
+msgid "Picked as"
+msgstr "Prelevato come"
+
msgid "Picked quantity"
msgstr "Quantità prelevata"
@@ -1044,6 +1047,12 @@ msgstr "Colonna {0} presa dalla posizione: {1} di {2}"
msgid "Picking"
msgstr "Prelievo"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "Prelievo in luogo di {substitutedFrom}, l'articolo dell'ordine di produzione"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "Prelievo in luogo di {substitutedFrom}, l'articolo dell'ordine di produzione, per {substitutedAssemblies} assiemi"
+
msgid "Pin Out"
msgstr "Disconnetti"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index e98a75c70b..4a7d6ddad4 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -111,6 +111,19 @@ msgstr "{0}が正常に削除されました"
msgid "{0} draft journal entries"
msgstr "{0}件の下書き仕訳"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0}在庫あり、{1}組用;残り{2}は{3}としてピッキング"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0}在庫あり;残り{1}は{2}としてピッキング"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} 件の製造指図が作成されました"
@@ -1419,6 +1432,9 @@ msgstr "パスを追加"
msgid "Add Permissions"
msgstr "権限を追加"
+msgid "Add Predecessor"
+msgstr "前任品目を追加"
+
msgid "Add Printer"
msgstr "プリンターを追加"
@@ -3489,6 +3505,9 @@ msgstr "バッチ可能なプロセスを選択して、一緒に実行できる
msgid "Choose a company"
msgstr "会社を選択"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "{itemReadableId}が置き換える部品を選択してください。そのルールはその部品に{itemReadableId}を後継品目として保存されます。"
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "左側の行を選択して、在庫がどこから来るかを確認します。"
@@ -7761,6 +7780,9 @@ msgstr "頻度"
msgid "Friday"
msgstr "金曜日"
+msgid "from"
+msgstr "から"
+
msgid "From"
msgstr "開始"
@@ -8298,6 +8320,9 @@ msgstr "1つの旧部品を何個の後継品目で置き換えるか"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "ジョブの親アイテムの1つを構築するために必要なこの材料の量; ジョブ数量を乗じて消費をサイズ化します。"
+msgid "How many of this part replace one old part"
+msgstr "旧部品1個を置き換えるのに、この部品は何個必要か"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "バルク一括処理の各個別ジョブが構築するユニット数; 総数量が均等に分割されない場合、最後のジョブの数量は小さくなります。"
@@ -8485,6 +8510,9 @@ msgstr "この見積依頼を見積に変換するには、得意先を持つ必
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "この見積依頼を仕入先に送信するには、まず見積依頼に仕入先を追加する必要があります。"
+msgid "in place of this item"
+msgstr "この品目の代わりに"
+
msgid "In Process Only"
msgstr "処理中のみ"
@@ -8509,6 +8537,9 @@ msgstr "在庫あり"
msgid "In stock only"
msgstr "在庫のみ"
+msgid "In stock, the remainder as {substitute}"
+msgstr "在庫あり、残りは{substitute}として"
+
msgid "In the loop together"
msgstr "一緒にループの中にいる"
@@ -11891,6 +11922,12 @@ msgstr "IAS 21 に従って純資産残高を換算する際に使用するオ
msgid "Optional pages & sections"
msgstr "オプションページとセクション"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "オプション。この日付以降、新規の購買提案が行われなくなります。"
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "オプション。この日付以降、旧部品の新規購買提案が行われなくなります。"
+
msgid "Options"
msgstr "オプション"
@@ -11906,6 +11943,10 @@ msgstr "または、このシークレットを手動で入力します:"
msgid "Order"
msgstr "注文"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "この製造指図に{0} × {substitute}を発注"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "このジョブ用に{0}を発注"
@@ -12130,6 +12171,9 @@ msgstr "部品"
msgid "Part"
msgstr "部品"
+msgid "Part Being Replaced"
+msgstr "置き換わる部品"
+
msgid "Part Details"
msgstr "部品詳細"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "追跡品目をピック"
+msgid "Picked"
+msgstr "ピッキング済"
+
msgid "Picked and consumed as separate components"
msgstr "別個のコンポーネントとしてピッキングおよび消費"
msgid "Picked quantity"
msgstr "ピック数量"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "製造指図の{substitutedFrom}の代わりにピッキング"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "製造指図の{substitutedFrom}の代わりに{assemblies}組用にピッキング"
+
msgid "Picking Lines"
msgstr "ピッキングラインス"
@@ -16066,6 +16119,12 @@ msgstr "受信を停止"
msgid "Stop Shipping"
msgstr "配送を停止"
+msgid "Stops new purchase suggestions after this date."
+msgstr "この日付以降、新規の購買提案が行われなくなります。"
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "この日付以降、旧部品の新規購買提案が行われなくなります。"
+
msgid "Storage client not available"
msgstr "ストレージクライアントは利用できません"
@@ -17511,6 +17570,9 @@ msgstr "これらの製造指図には、この作業区に割り当てられた
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "これらの仕訳はまだ下書きであるため、それらの借方と貸方は当期の元帳に含まれていません。各仕訳を転記するか、後の開いている期間に再度日付を付け直してください。"
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "これらの部品はこの部品で置き換わっています。各ルールは旧部品に設定されています;ルールを変更するには旧部品を開いてください。"
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "これらの行はこの会社外のデータにリンクしているため、現在のデータのバックアップを作成できません。削除を元に戻すことはできません。このグループ内の他の会社と共有されていることが判明した場合、何も削除されず、復元は開始されません。"
@@ -18790,6 +18852,9 @@ msgstr "バージョン:"
msgid "Versions"
msgstr "バージョン"
+msgid "via"
+msgstr "経由で"
+
msgid "via Digital Quote"
msgstr "デジタル見積経由"
@@ -19205,6 +19270,9 @@ msgstr "在庫の増減を駆動した要因(ディメンション別)"
msgid "What happens when a journal is dated in a locked period."
msgstr "仕訳をロック中の期間に付けたときの処理"
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "この材料用にラインサイドに実際にピッキングされたもの(部品別)。ピッキングは材料の名前と異なる部品をもたらすことができます(先に消費による分割、新しい方を優先するフォールバック)— ここはマシンにある部品を確認できる場所です。"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}とは何ですか?"
@@ -19283,6 +19351,9 @@ msgstr "Carbonが商品の到着を約束した日付。出荷方法の輸送日
msgid "When expired stock is used"
msgstr "期限切れの在庫が使用される場合"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "MRPがこの部品を旧部品の所要量に使用し始めるとき"
+
msgid "When MRP uses the successor for new demand"
msgstr "MRPが新しい所要量に対して後継品目を使用する場合"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index c3f0bdf803..ecca8c2a7e 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -1032,6 +1032,9 @@ msgstr "追跡品目をピック"
msgid "Picked"
msgstr "ピック済み"
+msgid "Picked as"
+msgstr "ピッキング済み として"
+
msgid "Picked quantity"
msgstr "ピック数量"
@@ -1044,6 +1047,12 @@ msgstr "カラム {0} を位置 {1}/{2} で選択しました"
msgid "Picking"
msgstr "ピッキング"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "{substitutedFrom}の代わりにピッキング、当ジョブ上の品目"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "{substitutedAssemblies}個のアセンブリ分、{substitutedFrom}の代わりにピッキング、当ジョブ上の品目"
+
msgid "Pin Out"
msgstr "ピンアウト"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index bba69e98ee..717f975f80 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -111,6 +111,19 @@ msgstr "{0}이(가) 삭제되었습니다"
msgid "{0} draft journal entries"
msgstr "{0}개의 초안 분개"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0}개 재고 있음, {1}개 조립품용; 나머지 {2}개는 {3}로 피킹할 예정"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0}개 재고 있음; 나머지 {1}개는 {2}로 피킹할 예정"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0}개의 작업 지시 생성됨"
@@ -1419,6 +1432,9 @@ msgstr "경로 추가"
msgid "Add Permissions"
msgstr "권한 추가"
+msgid "Add Predecessor"
+msgstr "선행 품목 추가"
+
msgid "Add Printer"
msgstr "프린터 추가"
@@ -3489,6 +3505,9 @@ msgstr "함께 실행할 수 있는 작업을 보려면 배치 가능한 공정
msgid "Choose a company"
msgstr "회사를 선택하세요"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "{itemReadableId}가 대체하는 부품을 선택하세요. 규칙은 해당 부품에 저장되며 {itemReadableId}가 후속 품목으로 지정됩니다."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "왼쪽의 행을 선택하여 해당 재고가 어디서 올 수 있는지 확인하세요."
@@ -7761,6 +7780,9 @@ msgstr "빈도"
msgid "Friday"
msgstr "금요일"
+msgid "from"
+msgstr "에서"
+
msgid "From"
msgstr "출발지"
@@ -8298,6 +8320,9 @@ msgstr "이전 품목 하나를 대체하는 후속 품목의 수량"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "작업 지시의 부모 품목 1개를 만드는 데 필요한 이 자재의 개수입니다. 작업 수량에 곱해서 소모량을 결정합니다."
+msgid "How many of this part replace one old part"
+msgstr "이 부품 몇 개가 기존 부품 1개를 대체합니까"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "대량 배치 내 개별 작업 각각이 생산하는 수량으로, 총수량이 균등하게 나누어지지 않으면 마지막 작업의 수량이 더 적을 수 있습니다."
@@ -8485,6 +8510,9 @@ msgstr "이 RFQ를 견적으로 전환하려면 고객이 지정되어 있어야
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "이 RFQ를 공급업체에 보내려면 먼저 RFQ에 공급업체를 추가해야 합니다."
+msgid "in place of this item"
+msgstr "이 품목 대신"
+
msgid "In Process Only"
msgstr "진행 중만"
@@ -8509,6 +8537,9 @@ msgstr "재고 있음"
msgid "In stock only"
msgstr "재고만"
+msgid "In stock, the remainder as {substitute}"
+msgstr "재고 있음, 나머지는 {substitute}로"
+
msgid "In the loop together"
msgstr "함께 정보 공유하기"
@@ -11891,6 +11922,12 @@ msgstr "IAS 21에 따라 자본 잔액을 환산할 때 사용하는 선택적
msgid "Optional pages & sections"
msgstr "선택적 페이지 및 섹션"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "선택사항. 이 날짜 이후로 새로운 구매 제안을 중단합니다."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "선택사항. 이 날짜 이후로 기존 부품에 대한 새로운 구매 제안을 중단합니다."
+
msgid "Options"
msgstr "옵션"
@@ -11906,6 +11943,10 @@ msgstr "또는 이 시크릿을 수동으로 입력하세요:"
msgid "Order"
msgstr "주문"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "이 작업 지시를 위해 {0} × {substitute} 발주"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "이 작업의 주문 {0}"
@@ -12130,6 +12171,9 @@ msgstr "품목"
msgid "Part"
msgstr "품목"
+msgid "Part Being Replaced"
+msgstr "대체될 부품"
+
msgid "Part Details"
msgstr "품목 세부정보"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "추적 품목 선택"
+msgid "Picked"
+msgstr "피킹 완료"
+
msgid "Picked and consumed as separate components"
msgstr "별도의 구성품으로 피킹 및 소비됨"
msgid "Picked quantity"
msgstr "피킹 수량"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "{substitutedFrom}(작업 지시의 품목) 대신 피킹"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "{substitutedFrom}(작업 지시의 품목) 대신 피킹, {assemblies}개 조립품용"
+
msgid "Picking Lines"
msgstr "피킹 라인"
@@ -16066,6 +16119,12 @@ msgstr "수령 중지"
msgid "Stop Shipping"
msgstr "배송 중지"
+msgid "Stops new purchase suggestions after this date."
+msgstr "이 날짜 이후로 새로운 구매 제안을 중단합니다."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "이 날짜 이후로 기존 부품에 대한 새로운 구매 제안을 중단합니다."
+
msgid "Storage client not available"
msgstr "저장소 클라이언트를 사용할 수 없습니다"
@@ -17511,6 +17570,9 @@ msgstr "이 작업장에 할당된 공정이 있는 작업 지시:"
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "이 전표들은 아직 초안 상태이므로 이 기간에 차변 및 대변이 원장에 없습니다. 각 전표를 전기하거나 이후 미결 기간으로 다시 날짜를 지정하십시오."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "이 부품들이 이 부품으로 대체됩니다. 각 규칙은 기존 부품에 설정되어 있으니 규칙을 변경하려면 해당 부품을 열어주세요."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "이 행들은 이 회사 외부의 데이터와 연결되어 있으므로 현재 데이터의 안전한 사본을 만들 수 없습니다. 이들을 삭제하면 되돌릴 수 없습니다. 이들이 이 그룹의 다른 회사와 공유되는 경우, 아무것도 삭제되지 않고 복원이 시작되지 않습니다."
@@ -18790,6 +18852,9 @@ msgstr "버전:"
msgid "Versions"
msgstr "버전"
+msgid "via"
+msgstr "경유"
+
msgid "via Digital Quote"
msgstr "디지털 견적을 통해"
@@ -19205,6 +19270,9 @@ msgstr "모든 차원별 재고를 높이거나 낮춘 요인"
msgid "What happens when a journal is dated in a locked period."
msgstr "전표의 일자가 잠김 기간에 있을 때 무슨 일이 발생하는가."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "이 자재에 대해 라인사이드로 실제로 피킹된 부품입니다(부품당). 피킹은 자재가 지정한 부품과 다를 수 있습니다(우선 소진 분할, 신규 선호 폴백). 이는 기계에 있는 부품을 확인할 수 있는 곳입니다."
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}란 무엇인가요?"
@@ -19283,6 +19351,9 @@ msgstr "Carbon이 재화 도착을 약속한 시점으로, 배송 방법의 운
msgid "When expired stock is used"
msgstr "만료된 재고가 사용될 때"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "MRP가 기존 부품의 소요량을 충족하기 위해 이 부품을 사용하기 시작할 때"
+
msgid "When MRP uses the successor for new demand"
msgstr "MRP가 새로운 소요량에 대해 후속 품목을 사용할 때"
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index d9e7d30b1a..4b18927957 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -1032,6 +1032,9 @@ msgstr "추적 품목 선택"
msgid "Picked"
msgstr "피킹됨"
+msgid "Picked as"
+msgstr "피킹 항목"
+
msgid "Picked quantity"
msgstr "피킹 수량"
@@ -1044,6 +1047,12 @@ msgstr "열 {0}을(를) 집었습니다 — 위치: {2}개 중 {1}번째"
msgid "Picking"
msgstr "피킹"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "{substitutedFrom} 대신 피킹, 작업의 품목"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "{substitutedFrom} 대신 피킹, 작업의 품목, {substitutedAssemblies}개 조립"
+
msgid "Pin Out"
msgstr "PIN 로그아웃"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 6f2a29baed..d540592ace 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} usunięty pomyślnie"
msgid "{0} draft journal entries"
msgstr "{0} roboczych zapisów księgowych"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} w zapasach, dla {1} zespołów; pozostała {2} będzie pobrana jako {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} w zapasach; pozostała {1} będzie pobrana jako {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} zleceń produkcyjnych utworzonych"
@@ -1419,6 +1432,9 @@ msgstr "Dodaj ścieżkę"
msgid "Add Permissions"
msgstr "Dodaj uprawnienia"
+msgid "Add Predecessor"
+msgstr "Dodaj poprzednika"
+
msgid "Add Printer"
msgstr "Dodaj drukarkę"
@@ -3489,6 +3505,9 @@ msgstr "Wybierz proces wsadowy, aby zobaczyć operacje, które mogą działać r
msgid "Choose a company"
msgstr "Wybierz firmę"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Wybierz część, którą zastępuje {itemReadableId}. Reguła jest zapisana na tej części z {itemReadableId} jako jej następnik."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Wybierz wiersz po lewej, aby zobaczyć, skąd może pochodzić jego zapas."
@@ -7761,6 +7780,9 @@ msgstr "Częstotliwość"
msgid "Friday"
msgstr "Piątek"
+msgid "from"
+msgstr "z"
+
msgid "From"
msgstr "Od"
@@ -8298,6 +8320,9 @@ msgstr "Ile następników zastępuje jedną starą część"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Ile tego materiału potrzeba do zbudowania jednego artykułu nadrzędnego pracy; pomnożyć przez ilość pracy, aby zmienić rozmiar zużycia."
+msgid "How many of this part replace one old part"
+msgstr "Ile tej części zastępuje jedną starą część"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Ile jednostek buduje każde indywidualne zadanie w partii; ilość ostatniego zadania może być mniejsza, jeśli całkowita ilość nie dzieli się równomiernie."
@@ -8485,6 +8510,9 @@ msgstr "Aby przekształcić to RFQ w ofertę, musi mieć klienta."
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Aby wysłać to zapytanie ofertowe do dostawców, musisz najpierw dodać dostawców do zapytania ofertowego."
+msgid "in place of this item"
+msgstr "w miejsce tego artykułu"
+
msgid "In Process Only"
msgstr "Tylko w trakcie"
@@ -8509,6 +8537,9 @@ msgstr "W magazynie"
msgid "In stock only"
msgstr "Tylko w magazynie"
+msgid "In stock, the remainder as {substitute}"
+msgstr "W zapasach, reszta jako {substitute}"
+
msgid "In the loop together"
msgstr "W pętli razem"
@@ -11891,6 +11922,12 @@ msgstr "Opcjonalna stała stawka używana przy tłumaczeniu sald kapitału włas
msgid "Optional pages & sections"
msgstr "Opcjonalne strony i sekcje"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Opcjonalnie. Wstrzymuje nowe propozycje zakupów po tej dacie."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Opcjonalnie. Wstrzymuje nowe propozycje zakupów dla starej części po tej dacie."
+
msgid "Options"
msgstr "Opcje"
@@ -11906,6 +11943,10 @@ msgstr "Lub wpisz tę sekretną wartość ręcznie:"
msgid "Order"
msgstr "Zamówienie"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Zamów {0} × {substitute} dla tego zlecenia produkcyjnego"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Zamów {0} dla tego zadania"
@@ -12130,6 +12171,9 @@ msgstr "części"
msgid "Part"
msgstr "Część"
+msgid "Part Being Replaced"
+msgstr "Część wymieniana"
+
msgid "Part Details"
msgstr "Szczegóły części"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Wybierz śledzony element"
+msgid "Picked"
+msgstr "Pobrano"
+
msgid "Picked and consumed as separate components"
msgstr "Pobrane i zużyte jako oddzielne komponenty"
msgid "Picked quantity"
msgstr "Pobrana ilość"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "kompletacja w miejsce {substitutedFrom}, artykułu na zleceniu"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "kompletacja w miejsce {substitutedFrom}, artykułu na zleceniu, dla {assemblies} zespołów"
+
msgid "Picking Lines"
msgstr "Pozycje kompletacji"
@@ -16066,6 +16119,12 @@ msgstr "Zatrzymaj Odbieranie"
msgid "Stop Shipping"
msgstr "Zatrzymaj wysyłkę"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Wstrzymuje nowe propozycje zakupów po tej dacie."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Wstrzymuje nowe propozycje zakupów dla starej części po tej dacie."
+
msgid "Storage client not available"
msgstr "Klient magazynu niedostępny"
@@ -17511,6 +17570,9 @@ msgstr "Te zlecenia produkcyjne mają operacje przypisane do tego stanowiska rob
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Te dowody księgowe są wciąż w wersji roboczej, dlatego ich wpisy Winien i Ma nie znajdują się w księdze dla tego okresu. Zaksięguj każdy z nich lub przesyć go do późniejszego otwartego okresu."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Te części są zastępowane przez ten artykuł. Każda reguła jest ustawiona na starej części; otwórz ją, aby zmienić regułę."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Te wiersze łączą się z danymi spoza tej firmy, dlatego nie można wykonać bezpiecznej kopii bieżących danych. Usunięcie ich nie może być cofnięte. Jeśli okaże się, że są współdzielone z innymi firmami w tej grupie, nic nie zostanie usunięte i przywracanie nie zostanie uruchomione."
@@ -18790,6 +18852,9 @@ msgstr "Wersja:"
msgid "Versions"
msgstr "Wersje"
+msgid "via"
+msgstr "poprzez"
+
msgid "via Digital Quote"
msgstr "poprzez Cyfrową Ofertę"
@@ -19205,6 +19270,9 @@ msgstr "Co spowodowało wzrost lub spadek zapasów, wg dowolnego wymiaru"
msgid "What happens when a journal is dated in a locked period."
msgstr "Co się dzieje, gdy dowód księgowy jest datowany w zablokowanym okresie."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Co faktycznie zostało pobrane do magazynu przyliniowego dla tego materiału, na każdą część. Pobranie może przynieść inną część niż wymieniona na materiale (podział Najpierw zużyj, rezerwowy Preferuj nowy) — tutaj widzisz, które części są przy maszynie."
+
msgid "What is {translatedTerm}?"
msgstr "Co to jest {translatedTerm}?"
@@ -19283,6 +19351,9 @@ msgstr "Kiedy Carbon zobowiązał się na dostarczenie towaru; połączone z dni
msgid "When expired stock is used"
msgstr "Gdy używany jest wygasły zapas"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Kiedy MRP zaczyna używać tę część do zapotrzebowania starej części"
+
msgid "When MRP uses the successor for new demand"
msgstr "Kiedy MRP używa następcy dla nowego zapotrzebowania"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index a3b5d95672..c1e21c8255 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Wybierz śledzony element"
msgid "Picked"
msgstr "Pobrane"
+msgid "Picked as"
+msgstr "Pobrano jako"
+
msgid "Picked quantity"
msgstr "Pobrana ilość"
@@ -1044,6 +1047,12 @@ msgstr "Podniesiono kolumnę {0} na pozycji: {1} z {2}"
msgid "Picking"
msgstr "Kompletowanie"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "kompletacja zamiast {substitutedFrom}, artykułu w zleceniu produkcyjnym"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "kompletacja zamiast {substitutedFrom}, artykułu w zleceniu produkcyjnym, dla {substitutedAssemblies} montaży"
+
msgid "Pin Out"
msgstr "Wyloguj PIN"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 4369760074..08b89ae733 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} eliminado com sucesso"
msgid "{0} draft journal entries"
msgstr "{0} lançamentos de diário em rascunho"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} em estoque, para {1} montagens; o restante {2} será separado como {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} em estoque; o restante {1} será separado como {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} ordens de produção criadas"
@@ -1419,6 +1432,9 @@ msgstr "Adicionar caminho"
msgid "Add Permissions"
msgstr "Adicionar Permissões"
+msgid "Add Predecessor"
+msgstr "Adicionar Antecessor"
+
msgid "Add Printer"
msgstr "Adicionar Impressora"
@@ -3489,6 +3505,9 @@ msgstr "Escolha um processo em lote para ver as operações que podem ser execut
msgid "Choose a company"
msgstr "Escolha uma empresa"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Escolha uma peça que {itemReadableId} substitui. A regra é salva nessa peça com {itemReadableId} como seu sucessor."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Escolha uma linha à esquerda para ver de onde seu estoque pode vir."
@@ -7761,6 +7780,9 @@ msgstr "Frequência"
msgid "Friday"
msgstr "Sexta-feira"
+msgid "from"
+msgstr "de"
+
msgid "From"
msgstr "De"
@@ -8298,6 +8320,9 @@ msgstr "Quantos do sucessor substituem uma peça antiga"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Quanto deste material é necessário para construir um do item pai do trabalho; multiplicado pela quantidade de trabalho para dimensionar o consumo."
+msgid "How many of this part replace one old part"
+msgstr "Quantas desta peça substituem uma peça antiga"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Quantas unidades cada trabalho individual no lote constrói; a quantidade do último trabalho pode ser menor se a quantidade total não se divide uniformemente."
@@ -8485,6 +8510,9 @@ msgstr "Para converter este RFQ em uma cotação, ele deve ter um cliente."
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Para enviar este RFQ aos fornecedores, você deve primeiro adicionar fornecedores ao RFQ."
+msgid "in place of this item"
+msgstr "no lugar deste item"
+
msgid "In Process Only"
msgstr "Apenas em Processamento"
@@ -8509,6 +8537,9 @@ msgstr "Em estoque"
msgid "In stock only"
msgstr "Apenas em estoque"
+msgid "In stock, the remainder as {substitute}"
+msgstr "Em estoque, o restante como {substitute}"
+
msgid "In the loop together"
msgstr "No circuito juntos"
@@ -11891,6 +11922,12 @@ msgstr "Taxa fixa opcional usada ao traduzir saldos de patrimônio líquido de a
msgid "Optional pages & sections"
msgstr "Páginas e seções opcionais"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Opcional. Interrompe novas sugestões de compra após esta data."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Opcional. Interrompe novas sugestões de compra da peça antiga após esta data."
+
msgid "Options"
msgstr "Opções"
@@ -11906,6 +11943,10 @@ msgstr "Ou introduza este segredo manualmente:"
msgid "Order"
msgstr "Pedido"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Solicitar {0} × {substitute} para esta ordem de produção"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Pedir {0} para este trabalho"
@@ -12130,6 +12171,9 @@ msgstr "peças"
msgid "Part"
msgstr "Peça"
+msgid "Part Being Replaced"
+msgstr "Peça sendo substituída"
+
msgid "Part Details"
msgstr "Detalhes da Peça"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Selecionar item rastreado"
+msgid "Picked"
+msgstr "Separado"
+
msgid "Picked and consumed as separate components"
msgstr "Selecionado e consumido como componentes separados"
msgid "Picked quantity"
msgstr "Quantidade colhida"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "separação no lugar de {substitutedFrom}, o item na ordem de produção"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "separação no lugar de {substitutedFrom}, o item na ordem de produção, para {assemblies} montagens"
+
msgid "Picking Lines"
msgstr "Linhas de separação"
@@ -16066,6 +16119,12 @@ msgstr "Parar Recebimento"
msgid "Stop Shipping"
msgstr "Parar Envio"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Interrompe novas sugestões de compra após esta data."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Interrompe novas sugestões de compra da peça antiga após esta data."
+
msgid "Storage client not available"
msgstr "Cliente de armazenamento não disponível"
@@ -17511,6 +17570,9 @@ msgstr "Estas ordens de produção têm operações atribuídas a este centro de
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Estes lançamentos de diário ainda estão em Rascunho, portanto seus débitos e créditos não estão no livro-razão para este período. Lance cada um, ou redatē-o para um período aberto posterior."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Essas peças estão sendo substituídas por esta. Cada regra é definida na peça antiga; abra-a para alterar a regra."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Essas linhas estão vinculadas a dados fora desta empresa, portanto não é possível criar uma cópia de segurança dos seus dados atuais. A exclusão dessas linhas não pode ser desfeita. Se forem compartilhadas com outras empresas neste grupo, nada será excluído e a restauração não será iniciada."
@@ -18790,6 +18852,9 @@ msgstr "Versão:"
msgid "Versions"
msgstr "Versões"
+msgid "via"
+msgstr "via"
+
msgid "via Digital Quote"
msgstr "via Cotação Digital"
@@ -19205,6 +19270,9 @@ msgstr "O que impulsionou o inventário para cima ou para baixo, por qualquer di
msgid "What happens when a journal is dated in a locked period."
msgstr "O que acontece quando um diário é datado em um período bloqueado."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "O que foi realmente separado para a borda de linha para este material, por peça. Uma separação pode trazer uma peça diferente da que o material nomeia (uma divisão de Consumir Primeiro, uma alternativa de Preferir Novo) — aqui é onde você vê quais peças estão na máquina."
+
msgid "What is {translatedTerm}?"
msgstr "O que é {translatedTerm}?"
@@ -19283,6 +19351,9 @@ msgstr "Quando a Carbon se comprometeu com a chegada das mercadorias; combinado
msgid "When expired stock is used"
msgstr "Quando o estoque vencido é usado"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Quando MRP começa a usar esta peça para a demanda da peça antiga"
+
msgid "When MRP uses the successor for new demand"
msgstr "Quando o MRP usa o sucessor para nova demanda"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 3271597ff5..cc7a29293d 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Selecionar item rastreado"
msgid "Picked"
msgstr "Apanhado"
+msgid "Picked as"
+msgstr "Separado como"
+
msgid "Picked quantity"
msgstr "Quantidade colhida"
@@ -1044,6 +1047,12 @@ msgstr "Coluna {0} selecionada na posição: {1} de {2}"
msgid "Picking"
msgstr "Separação"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "separação em lugar de {substitutedFrom}, o item da ordem de produção"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "separação em lugar de {substitutedFrom}, o item da ordem de produção, para {substitutedAssemblies} conjuntos"
+
msgid "Pin Out"
msgstr "Desconectar"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 6b08f9f845..06fc7b454f 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} успешно удален"
msgid "{0} draft journal entries"
msgstr "{0} черновых операций"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} в наличии, для {1} сборок; остаток {2} будет отобран как {3}"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} в наличии; остаток {1} будет отобран как {2}"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} производственных заказов создано"
@@ -1419,6 +1432,9 @@ msgstr "Добавить путь"
msgid "Add Permissions"
msgstr "Добавить права доступа"
+msgid "Add Predecessor"
+msgstr "Добавить предшественника"
+
msgid "Add Printer"
msgstr "Добавить принтер"
@@ -3489,6 +3505,9 @@ msgstr "Выберите пакетируемый процесс, чтобы у
msgid "Choose a company"
msgstr "Выберите организацию"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "Выберите деталь, которую заменяет {itemReadableId}. Правило сохраняется на этой детали с {itemReadableId} в качестве преемника."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Выберите строку слева, чтобы увидеть, откуда может поступить её запас."
@@ -7761,6 +7780,9 @@ msgstr "Частота"
msgid "Friday"
msgstr "Пятница"
+msgid "from"
+msgstr "из"
+
msgid "From"
msgstr "От"
@@ -8298,6 +8320,9 @@ msgstr "Сколько единиц преемника заменяют одну
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "Сколько этого материала нужно, чтобы построить один из родительского товара работы; умножается на количество работы для определения размера потребления."
+msgid "How many of this part replace one old part"
+msgstr "Сколько этой детали заменяют одну старую деталь"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Сколько единиц строит каждая отдельная работа в пакетной партии; количество последней работы может быть меньше, если общее количество не делится равномерно."
@@ -8485,6 +8510,9 @@ msgstr "Чтобы преобразовать этот запрос цен в к
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Чтобы отправить этот запрос коммерческих предложений поставщикам, необходимо сначала добавить поставщиков в запрос."
+msgid "in place of this item"
+msgstr "вместо этой номенклатуры"
+
msgid "In Process Only"
msgstr "Только в процессе"
@@ -8509,6 +8537,9 @@ msgstr "В наличии"
msgid "In stock only"
msgstr "Только в наличии"
+msgid "In stock, the remainder as {substitute}"
+msgstr "В наличии, остаток как {substitute}"
+
msgid "In the loop together"
msgstr "В курсе дела вместе"
@@ -11891,6 +11922,12 @@ msgstr "Дополнительный фиксированный курс, исп
msgid "Optional pages & sections"
msgstr "Дополнительные страницы и разделы"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "Опционально. Останавливает новые предложения по закупкам после этой даты."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "Опционально. Останавливает новые предложения по закупкам старой детали после этой даты."
+
msgid "Options"
msgstr "Параметры"
@@ -11906,6 +11943,10 @@ msgstr "Или введите этот секрет вручную:"
msgid "Order"
msgstr "Заказ"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Заказать {0} × {substitute} для этого производственного заказа"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Заказать {0} для этого задания"
@@ -12130,6 +12171,9 @@ msgstr "детали"
msgid "Part"
msgstr "Деталь"
+msgid "Part Being Replaced"
+msgstr "Заменяемая деталь"
+
msgid "Part Details"
msgstr "Детали детали"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Выбрать отслеживаемый товар"
+msgid "Picked"
+msgstr "Отобрано"
+
msgid "Picked and consumed as separate components"
msgstr "Подобрано и потреблено как отдельные компоненты"
msgid "Picked quantity"
msgstr "Выбранное количество"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "отбор вместо {substitutedFrom}, номенклатуры в производственном заказе"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "отбор вместо {substitutedFrom}, номенклатуры в производственном заказе, для {assemblies} сборок"
+
msgid "Picking Lines"
msgstr "Строки отбора"
@@ -16066,6 +16119,12 @@ msgstr "Остановить получение"
msgid "Stop Shipping"
msgstr "Остановить отправку"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Останавливает новые предложения по закупкам после этой даты."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Останавливает новые предложения по закупкам старой детали после этой даты."
+
msgid "Storage client not available"
msgstr "Клиент хранилища недоступен"
@@ -17511,6 +17570,9 @@ msgstr "Эти производственные заказы имеют опер
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Эти операции по-прежнему находятся в режиме Черновик, поэтому их дебеты и кредиты не включены в главную книгу для этого периода. Проведите каждый из них или переведите его в более поздний открытый период."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Эти детали заменяются на эту. Каждое правило установлено на старой детали; откройте ее, чтобы изменить правило."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Эти строки связаны с данными вне этой организации, поэтому не удаётся создать резервную копию текущих данных. Удаление их не может быть отменено. Если окажется, что они используются другими организациями в этой группе, ничего не удаляется и восстановление не начинается."
@@ -18790,6 +18852,9 @@ msgstr "Версия:"
msgid "Versions"
msgstr "Версии"
+msgid "via"
+msgstr "через"
+
msgid "via Digital Quote"
msgstr "через цифровое предложение"
@@ -19205,6 +19270,9 @@ msgstr "Что повлияло на инвентаризацию вверх и
msgid "What happens when a journal is dated in a locked period."
msgstr "Что происходит, когда операция датирована в заблокированный период."
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Что было фактически отобрано в прилинейный запас для данной номенклатуры по деталям. Отбор может привести деталь, отличную от указанной в материале (разделение при \"Сначала израсходовать\", альтернатива при \"Предпочесть новое\") — здесь вы видите, какие детали находятся на станке."
+
msgid "What is {translatedTerm}?"
msgstr "Что такое {translatedTerm}?"
@@ -19283,6 +19351,9 @@ msgstr "Когда Carbon обязалась доставить товары; в
msgid "When expired stock is used"
msgstr "Когда используется Запас с истекшим сроком"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "Когда MRP начинает использовать эту деталь для удовлетворения потребностей в старой детали"
+
msgid "When MRP uses the successor for new demand"
msgstr "Когда MRP использует преемника для новых потребностей"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index c83970bb2e..2f0876536b 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Выбрать отслеживаемый товар"
msgid "Picked"
msgstr "Подобрано"
+msgid "Picked as"
+msgstr "Отобрано как"
+
msgid "Picked quantity"
msgstr "Выбранное количество"
@@ -1044,6 +1047,12 @@ msgstr "Столбец {0} взят с позиции: {1} из {2}"
msgid "Picking"
msgstr "Отбор"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "Отбор вместо {substitutedFrom}, номенклатура в производственном заказе"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "Отбор вместо {substitutedFrom}, номенклатура в производственном заказе, для {substitutedAssemblies} сборок"
+
msgid "Pin Out"
msgstr "Выход по PIN"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index a302d623ab..7784693bfd 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} başarıyla silindi"
msgid "{0} draft journal entries"
msgstr "{0} taslak muhasebe fişi"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0} stokta, {1} montaj için; kalan {2} {3} olarak toplanacak"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0} stokta; kalan {1} {2} olarak toplanacak"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "{0} iş emri oluşturuldu"
@@ -1419,6 +1432,9 @@ msgstr "Yol ekle"
msgid "Add Permissions"
msgstr "İzin Ekle"
+msgid "Add Predecessor"
+msgstr "Öncülü Ekle"
+
msgid "Add Printer"
msgstr "Yazıcı Ekle"
@@ -3489,6 +3505,9 @@ msgstr "Birlikte çalışabilecek operasyonları görmek için toplu işlenebili
msgid "Choose a company"
msgstr "Bir şirket seçin"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "{itemReadableId}'nin yerine geçen bir parça seçin. Kural seçilen parçaya {itemReadableId} ardıl olarak kaydedilir."
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "Stokun nereden gelebileceğini görmek için sol taraftaki bir satırı seçin."
@@ -7761,6 +7780,9 @@ msgstr "Sıklık"
msgid "Friday"
msgstr "Cuma"
+msgid "from"
+msgstr "gelen"
+
msgid "From"
msgstr "Başlangıç"
@@ -8298,6 +8320,9 @@ msgstr "Bir eski parçanın yerini kaç ardıl alır"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "İşin ana öğesinin birini oluşturmak için bu malzemeden ne kadar gerekir; tüketimi boyutlandırmak için iş miktarı ile çarpılır."
+msgid "How many of this part replace one old part"
+msgstr "Bu parçadan kaçı bir eski parçayı değiştirir"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "Toplu batch'teki her bireysel iş kaç birim oluşturur; toplam miktar eşit olarak bölünmezse, son işin miktarı daha küçük olabilir."
@@ -8485,6 +8510,9 @@ msgstr "Bu Fiyat Teklifi'ni (RFQ) bir teklife dönüştürmek için bir müşter
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "Bu RFQ'yu tedarikçilere gönderebilmek için öncelikle RFQ'ya tedarikçi eklemeniz gerekir."
+msgid "in place of this item"
+msgstr "bu stok kartı yerine"
+
msgid "In Process Only"
msgstr "Sadece Devam Edenler"
@@ -8509,6 +8537,9 @@ msgstr "Stokta"
msgid "In stock only"
msgstr "Yalnızca stokta"
+msgid "In stock, the remainder as {substitute}"
+msgstr "Stokta, geri kalanı {substitute} olarak"
+
msgid "In the loop together"
msgstr "Birlikte döngüde"
@@ -11891,6 +11922,12 @@ msgstr "Özkaynak bakiyelerini IAS 21'e göre çevirirken kullanılan isteğe ba
msgid "Optional pages & sections"
msgstr "İsteğe bağlı sayfalar ve bölümler"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "İsteğe bağlı. Bu tarihten sonra yeni satın alma önerilerini durdurur."
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "İsteğe bağlı. Bu tarihten sonra eski parça için yeni satın alma önerilerini durdurur."
+
msgid "Options"
msgstr "Seçenekler"
@@ -11906,6 +11943,10 @@ msgstr "Veya bu sırrı manuel olarak girin:"
msgid "Order"
msgstr "Sipariş"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "Bu iş emri için {0} × {substitute} sipariş et"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "Bu iş için {0} sipariş et"
@@ -12130,6 +12171,9 @@ msgstr "parçalar"
msgid "Part"
msgstr "Parça"
+msgid "Part Being Replaced"
+msgstr "Yerine Geçilen Parça"
+
msgid "Part Details"
msgstr "Parça Detayları"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "Takip edilen öğeyi seç"
+msgid "Picked"
+msgstr "Toplandı"
+
msgid "Picked and consumed as separate components"
msgstr "Ayrı bileşenler olarak toplanmış ve tüketilmiş"
msgid "Picked quantity"
msgstr "Alınan miktar"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "{substitutedFrom} yerine toplama, iş emrindeki stok kartı"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "{substitutedFrom} yerine toplama, iş emrindeki stok kartı, {assemblies} montaj için"
+
msgid "Picking Lines"
msgstr "Toplama Satırları"
@@ -16066,6 +16119,12 @@ msgstr "Alımı Durdur"
msgid "Stop Shipping"
msgstr "Gönderimi Durdur"
+msgid "Stops new purchase suggestions after this date."
+msgstr "Bu tarihten sonra yeni satın alma önerilerini durdurur."
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "Bu tarihten sonra eski parça için yeni satın alma önerilerini durdurur."
+
msgid "Storage client not available"
msgstr "Depolama istemcisi kullanılamıyor"
@@ -17511,6 +17570,9 @@ msgstr "Bu iş emirlerinin bu iş merkezine atanmış operasyonları vardır:"
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "Bu muhasebe fişleri hala Taslak halinde olduğundan borç ve alacakları bu dönemin defterine girmedi. Her birini muhasebeleştir veya daha sonraki açık bir döneme yeniden tarihle."
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "Bu parçalar bu birim tarafından değiştiriliyor. Her kural eski parçaya ayarlanmış; kuralı değiştirmek için açın."
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "Bu satırlar bu Şirket dışındaki verilere bağlı olduğundan, mevcut verilerinizin bir güvenlik kopyası oluşturulamaz. Bu satırları silmek geri alınamaz. Bunların bu gruptaki diğer Şirketlerle paylaşıldığı anlaşılırsa, hiçbir şey silinmez ve geri yükleme başlamaz."
@@ -18790,6 +18852,9 @@ msgstr "Sürüm:"
msgid "Versions"
msgstr "Sürümler"
+msgid "via"
+msgstr "aracılığıyla"
+
msgid "via Digital Quote"
msgstr "Dijital Teklif ile"
@@ -19205,6 +19270,9 @@ msgstr "Envanterin yükselmesine veya düşmesine neyin sebep olduğu, herhangi
msgid "What happens when a journal is dated in a locked period."
msgstr "Muhasebe fişi kilitli bir dönemde tarihlendirildiğinde ne olur?"
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "Bu malzeme için Hat yanı'na gerçekten toplanmış olan toplama, parça başına. Bir toplama malzemenin adından farklı bir parça getirebilir (Önce tüket bölmesi, Yeni'yi Tercih Et yedek) — makinada hangi parçaların bulunduğunu görmek için burası."
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm} nedir?"
@@ -19283,6 +19351,9 @@ msgstr "Carbon'un malların teslim edilmesine taahhüt ettiği zaman; sevkiyat y
msgid "When expired stock is used"
msgstr "Süresi dolmuş stok kullanıldığında"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "MRP bu parçayı eski parçanın talebinde kullanmaya başladığında"
+
msgid "When MRP uses the successor for new demand"
msgstr "MRP'nin ardılı yeni talebe kullandığında"
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 18c9d331f3..824476dc73 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -1032,6 +1032,9 @@ msgstr "Takip edilen öğeyi seç"
msgid "Picked"
msgstr "Alındı"
+msgid "Picked as"
+msgstr "Toplandı olarak"
+
msgid "Picked quantity"
msgstr "Alınan miktar"
@@ -1044,6 +1047,12 @@ msgstr "Sütun {0} alındı, konumu: {1} / {2}"
msgid "Picking"
msgstr "Toplama"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "{substitutedFrom} yerine toplama, iş emrindeki stok kartı"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "{substitutedFrom} yerine toplama, iş emrindeki stok kartı, {substitutedAssemblies} montaj için"
+
msgid "Pin Out"
msgstr "Çıkış Yap"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 9be518b500..044bd30840 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -111,6 +111,19 @@ msgstr "{0} 已成功删除"
msgid "{0} draft journal entries"
msgstr "{0}个草稿凭证"
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format(assembliesInStock)
+#. placeholder {2}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {3}: consumeFirst.successorReadableId
+msgid "{0} in stock, for {1} assemblies; the remaining {2} will be picked as {3}"
+msgstr "{0}库存,用于{1}个组件;剩余的{2}将按{3}拣货"
+
+#. placeholder {0}: formatter.format(onHand)
+#. placeholder {1}: formatter.format( shortfall * consumeFirst.conversionFactor )
+#. placeholder {2}: consumeFirst.successorReadableId
+msgid "{0} in stock; the remaining {1} will be picked as {2}"
+msgstr "{0}库存;剩余的{1}将按{2}拣货"
+
#. placeholder {0}: jobs.length
msgid "{0} jobs created"
msgstr "已创建{0}个工单"
@@ -1419,6 +1432,9 @@ msgstr "添加路径"
msgid "Add Permissions"
msgstr "添加权限"
+msgid "Add Predecessor"
+msgstr "添加前驱物料"
+
msgid "Add Printer"
msgstr "添加打印机"
@@ -3489,6 +3505,9 @@ msgstr "选择可批处理的工序以查看可以一起运行的操作。"
msgid "Choose a company"
msgstr "选择公司"
+msgid "Choose a part that {itemReadableId} replaces. The rule is saved on that part with {itemReadableId} as its successor."
+msgstr "选择{itemReadableId}所替代的零件。该规则将保存在该零件上,将{itemReadableId}作为其后继物料。"
+
msgid "Choose a row on the left to see where its stock can come from."
msgstr "选择左侧的行以查看其库存可能来自何处。"
@@ -7761,6 +7780,9 @@ msgstr "频率"
msgid "Friday"
msgstr "星期五"
+msgid "from"
+msgstr "来自"
+
msgid "From"
msgstr "从"
@@ -8298,6 +8320,9 @@ msgstr "后继物料中的多少个替代一个旧零件"
msgid "How many of this material it takes to build one of the job's parent item; multiplied by job quantity to size the consumption."
msgstr "构建一个工单的父物料需要多少这种原材料;乘以工单数量来确定消耗量"
+msgid "How many of this part replace one old part"
+msgstr "此零件中有多少个替代一个旧零件"
+
msgid "How many units each individual job in the bulk batch builds; the last job's quantity may be smaller if Total Quantity doesn't divide evenly."
msgstr "批量生产批次中每个单独工单生产的件数;如果总数量不能均匀整除,最后一个工单的数量可能较小。"
@@ -8485,6 +8510,9 @@ msgstr "为了将此RFQ转换为报价,它必须有一个客户。"
msgid "In order to send this RFQ to suppliers, you must first add suppliers to the RFQ."
msgstr "为了将此RFQ发送给供应商,您必须先向RFQ添加供应商。"
+msgid "in place of this item"
+msgstr "代替此物料"
+
msgid "In Process Only"
msgstr "仅处理中"
@@ -8509,6 +8537,9 @@ msgstr "有库存"
msgid "In stock only"
msgstr "仅库存"
+msgid "In stock, the remainder as {substitute}"
+msgstr "库存,剩余部分为{substitute}"
+
msgid "In the loop together"
msgstr "一起保持沟通"
@@ -11891,6 +11922,12 @@ msgstr "在根据IAS 21转换所有者权益余额时使用的可选固定汇率
msgid "Optional pages & sections"
msgstr "可选页面和部分"
+msgid "Optional. Stops new purchase suggestions after this date."
+msgstr "可选。在此日期之后停止新采购建议。"
+
+msgid "Optional. Stops new purchase suggestions for the old part after this date."
+msgstr "可选。在此日期之后停止旧零件的新采购建议。"
+
msgid "Options"
msgstr "选项"
@@ -11906,6 +11943,10 @@ msgstr "或手动输入此密码:"
msgid "Order"
msgstr "订单"
+#. placeholder {0}: status?.shortfall
+msgid "Order {0} × {substitute} for this job"
+msgstr "为此工单订购{0} × {substitute}"
+
#. placeholder {0}: status?.shortfall
msgid "Order {0} for this job"
msgstr "为此作业订购 {0}"
@@ -12130,6 +12171,9 @@ msgstr "零件"
msgid "Part"
msgstr "零件"
+msgid "Part Being Replaced"
+msgstr "被替代的零件"
+
msgid "Part Details"
msgstr "零件详情"
@@ -12409,12 +12453,21 @@ msgstr ""
msgid "Pick tracked item"
msgstr "拣货追踪物料"
+msgid "Picked"
+msgstr "已拣货"
+
msgid "Picked and consumed as separate components"
msgstr "已拣货且作为单独组件已消耗"
msgid "Picked quantity"
msgstr "已拣货数量"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "拣货替代{substitutedFrom}(工单上的物料)"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {assemblies} assemblies"
+msgstr "拣货替代{substitutedFrom}(工单上的物料),用于{assemblies}个组件"
+
msgid "Picking Lines"
msgstr "拣货行"
@@ -16066,6 +16119,12 @@ msgstr "停止接收"
msgid "Stop Shipping"
msgstr "停止发货"
+msgid "Stops new purchase suggestions after this date."
+msgstr "在此日期之后停止新采购建议。"
+
+msgid "Stops new purchase suggestions for the old part after this date."
+msgstr "在此日期之后停止旧零件的新采购建议。"
+
msgid "Storage client not available"
msgstr "存储客户端不可用"
@@ -17511,6 +17570,9 @@ msgstr "这些工单在此工作中心分配了工序:"
msgid "These journal entries are still Draft, so their debits and credits aren't in the ledger for this period. Post each one, or re-date it into a later open period."
msgstr "这些凭证仍是草稿,所以其借方和贷方不在此期间的账簿中。过账每一个,或将其重新标注日期到更后的未结期间。"
+msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."
+msgstr "这些零件被此零件替代。每个规则都在旧零件上设置;打开它来更改规则。"
+
msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."
msgstr "这些行链接到此公司外的数据,因此无法创建当前数据的安全备份。删除它们无法撤销。如果这些行实际上与此集团中的其他公司共享,则不删除任何行,且不启动还原。"
@@ -18790,6 +18852,9 @@ msgstr "版本:"
msgid "Versions"
msgstr "版本"
+msgid "via"
+msgstr "经由"
+
msgid "via Digital Quote"
msgstr "通过数字报价"
@@ -19205,6 +19270,9 @@ msgstr "什么驱动库存管理增加或减少,按任何维度"
msgid "What happens when a journal is dated in a locked period."
msgstr "当凭证的日期在已锁定的期间时会发生什么。"
+msgid "What has actually been picked to lineside for this material, per part. A pick can bring a different part than the material names (a Consume First split, a Prefer New fallback) — this is where you see which parts are at the machine."
+msgstr "此物料实际拣货到线边的零件。拣货可能会使用与物料名称不同的零件(先消耗拆分、优选新物料回退)——这是您查看机器上有哪些零件的位置。"
+
msgid "What is {translatedTerm}?"
msgstr "{translatedTerm}是什么?"
@@ -19283,6 +19351,9 @@ msgstr "货物的承诺到达日期;结合发货方式的运输天数,这驱
msgid "When expired stock is used"
msgstr "当使用已过期库存时"
+msgid "When MRP starts using this part for the old part's demand"
+msgstr "当MRP开始将此零件用于旧零件的需求时"
+
msgid "When MRP uses the successor for new demand"
msgstr "当 MRP 将后继物料用于新需求时"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index 9c298460df..5eb58b7632 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -1032,6 +1032,9 @@ msgstr "拣货追踪物料"
msgid "Picked"
msgstr "已拣货"
+msgid "Picked as"
+msgstr "拣货为"
+
msgid "Picked quantity"
msgstr "已拣货数量"
@@ -1044,6 +1047,12 @@ msgstr "在位置{1}(共{2})处选取了列{0}"
msgid "Picking"
msgstr "拣货"
+msgid "picking in place of {substitutedFrom}, the item on the job"
+msgstr "拣货替代{substitutedFrom}(工单上的物料)"
+
+msgid "picking in place of {substitutedFrom}, the item on the job, for {substitutedAssemblies} assemblies"
+msgstr "拣货替代{substitutedFrom}(工单上的物料),{substitutedAssemblies}个装配"
+
msgid "Pin Out"
msgstr "退出登录"