Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
MRP planning actions, forecast consumption, planning horizon and scheduled run time (#1601)
Brad Barbinc1b539854cab
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex df9ff50372..679e258563 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2731,6 +2731,32 @@ drawer (`foo.tsx` + `foo.new.tsx`). A list loader reads the whole query string,`search: "all"`. A loader that reads the pathname, a cookie or a header must not use thehelper.+## A `@container` block has no intrinsic width — it vanishes in a shrink-to-fit parent++**Context:** The planning grid's expanded row (`PlanningActionLines`) was reused inside the+order drawer, under a `VStack`, to list an item's suggested changes. The heading rendered and+the rows did not.++**Problem:** The block's root is `@container` (`container-type: inline-size`), which is+inline-size containment: the element contributes NO intrinsic width to its parent. In the+grid the Table hands it a width. `VStack` is `flex flex-col items-start`, so its children+shrink-to-fit — and a contained element's fit width is zero plus padding. The table inside+was `w-full` of nothing. Typecheck, lint and unit tests all pass on this; only a render+shows it.++**Rule:** Anything marked `@container` must be stretched by its parent (`w-full`, a block+parent, or a flex column with default `items-stretch`) — never placed in `VStack`/`HStack`+or any `items-start`/`inline-*`/`w-fit` parent without an explicit width. When moving a+component to a new host, check what the OLD host was giving it for free: width, padding+offsets (`pl-[52px]` lined the block up under a grid row and means nothing in a drawer) and+column widths sized for a different pane. A layout built for one host usually wants its own+variant in the next (the drawer now has its own `OpenOrdersGrid`), sharing only the+behaviour.++**Applies to:** `apps/erp/app/modules/production/ui/Planning/PlanningActionLines.tsx`+(`PlanningActionLines` vs `PlanningOrderGrids.tsx`), and any `@container` component rendered+through `VStack`/`HStack` (`packages/react/src/VStack.tsx` is `items-start`).+## A write that changes nothing still costs a queue message, an Inngest event and a function run**Context:** `/api/inngest` was the largest consumer on the ERP deployment (2026-10-01@@ -2804,6 +2830,102 @@ tag until proven otherwise.**Applies to:** `apps/erp/app/modules/*/*.service.ts`, `pnpm run generate:mcp`.+## A supply figure that includes scrap cannot be written back as the order quantity++**Context:** Planning actions measure each open job against demand and suggest Decrease /+Increase. The job's supply came from `openProductionOrders.quantityToReceive`, which is+`productionQuantity − received`, and `productionQuantity` is the generated `quantity + scrapQuantity`.++**Problem:** Apply writes the suggested figure to `job.quantity`, the good units. A job of 80+with scrap 4 counted as 84 against a demand of 80: "Only 80 of 84 is required", every run, for+every job on an item with a scrap rate — and applying it changed nothing, so it came back.+An Increase was 4 too high the same way. No test covered a job with scrap.++**Rule:** Measure a document in the unit the action will WRITE. If the engine reads a derived+total (with scrap, with a conversion factor), either convert at the boundary or read the base+column. And when a write changes a base quantity, restate what rides on it (the scrap+allowance), as the insert path does — a patch that sets one column of a pair is the bug class+`.claude/rules/supersession-system.md` describes for `itemScrapPercentage`.++**Applies to:** `generatePlanningActions` (`packages/planning/src/mrp/planning-actions.ts`),+`updatePlanningJob` (`production.service.ts`), any engine that reads `openProductionOrders`+or `openPurchaseOrderLines` and writes a document quantity back.++## An `.in()` list built from a result set has no upper bound++**Context:** The planning grids load the actions for the 100 parts on a page, then looked up+each action's purchase order line with `.in("id", lineIds)`.++**Problem:** `.in()` writes every id into the URL. The list was one id per ACTION, so it grew+with the data, not the page size: 2,357 ids was a 54 kB request line and the gateway rejected+it (HTTP 431). The loader did `planningActions.data ?? []`, so the page rendered every part+with no actions — indistinguishable from "nothing to do". Demo data and hand-made test parts+(a few actions each) never came near the limit; it took load data to see it.++**Rule:** An id list for `.in()` must be bounded by something you control (the page size), and+chunked when that bound is large — about 100 ids per request. When the related rows hang off+a foreign key, embed them in the first read instead of looking them up afterwards. And a+loader never swaps a failed read for an empty list: log it and throw.++A list the USER builds (the ids of a bulk selection: Apply, Dismiss, Assign) has no bound at+all, and chunking a WRITE breaks its atomicity — a claim that lands in chunk 1 and fails in+chunk 2 leaves rows claimed with nothing applied. Send such a list through Kysely instead:+`where("id", "in", ids)` binds the ids as parameters, one statement, no URL, no `max_rows`.+The same bulk Apply did this over PostgREST in five functions and would have failed whole on a+page of busy parts.++**Applies to:** `getPlanningActions` and the planning action worklist writes in+`apps/erp/app/modules/production/production.service.ts`, the planning loaders and+`planning.update` routes (`x+/purchasing+/planning*.tsx`, `x+/production+/planning*.tsx`), and+any "read rows, then `.in()` their ids" enrichment.++## `useNumberFormatter()` with no argument is a new formatter on every render++**Context:** Opening or closing the order drawer on the planning pages stuttered. The drawer+itself was cheap; the table behind it was the cost.++**Problem:** react-aria memoizes the formatter on the options OBJECT+(`useMemo(() => new NumberFormatter(locale, options), [locale, options])`), and the default+`options = {}` is a new object on each call. So `useNumberFormatter()` returns a new formatter+every render. It was a dependency of the table's `columns` memo, so every render rebuilt the+columns; TanStack then sees new `cell` functions and React REMOUNTS every cell, and the+shared `Table` re-measures its column widths. Opening the drawer re-rendered the table six+times through fetcher state — 1,824 DOM nodes replaced, six main-thread blocks of 90–220 ms.+With a stable formatter: zero nodes replaced, and the drawer shows in ~100 ms instead of ~220.++**Rule:** A value that feeds a `useMemo`/`useCallback` dependency list must be stable. Pass+`useNumberFormatter` a module-level options constant (or use the `@carbon/utils` formatter+hooks), never the bare call. When a table feels slow, count DOM nodes replaced in its+`tbody` during the interaction before optimizing anything else — a non-zero count on an+interaction that changes no data means the columns are being rebuilt.++**Applies to:** `PurchasingPlanningTable.tsx`, `ProductionPlanningTable.tsx` (fixed), and the+other ERP files that still call `useNumberFormatter()` bare — it only costs where the+formatter reaches a memo dependency list (`InventoryTable`, `TrackedEntitiesTable`,+`JobMaterialsTable`, `DemandProjectionTable`, `JobOperationStepRecordsTable` are the+candidates to check).++## A drawer rendered as `{item && <Drawer />}` cannot animate closed++**Context:** The planning order drawer slid in but vanished on close.++**Problem:** Three things each removed it before a closing animation could run. The tables+rendered it as `{selectedItem && <Drawer />}` and closed it by clearing `selectedItem`, so+it left the DOM in the same render. The shared `Drawer` panel only had a slide-IN. And Radix+keeps a closing dialog mounted only while the element its portal wraps is animating — that+element is `DrawerPortal`'s positioning div, which had no animation, so even a mounted+drawer with an exit animation on its panel was removed at once. Adding the exit classes to+the panel alone changed nothing; the frame-by-frame trace still showed zero closing frames.++**Rule:** A drawer that should animate closed stays mounted and is driven by `open`; keep the+record it shows until the next open (`useDrawerItem`), and key it per open so each open+still starts fresh. When a Radix exit animation does not play, check every element between+the portal and the animated node — each `Presence` looks only at its own child. Verify with+a trace of `data-state` and `getBoundingClientRect()` per frame, not by eye.++**Applies to:** `packages/react/src/Drawer.tsx` (`portalVariants` + `sheetVariants` closing+durations must match), `useDrawerItem` (`apps/erp/app/hooks`), both planning tables, and the+other state-driven drawers that still unmount on close.## A cast that silences excess-property errors hides failed writesdiff --git a/.ai/plans/2026-09-08-mrp-planning-actions.md b/.ai/plans/2026-09-08-mrp-planning-actions.mdnew file mode 100644index 0000000000..ead3f6df9d--- /dev/null+++ b/.ai/plans/2026-09-08-mrp-planning-actions.md@@ -0,0 +1,512 @@+# MRP Planning Actions (Phase 1) — implementation plan++**Spec:** .ai/specs/2026-08-22-mrp-v2-planned-order-generation.md (§P1 — Phase 1)+**Research:** .ai/research/mrp-planning-actions.md+**Run record:** .ai/runs/2026-09-08-mrp-planning-actions.md+**Branch:** mrp-action-suggestions++Scope = **Phase 1 only**: emit and persist assignable, dismissible planning actions+(`Order | Make | Expedite | Defer | Cancel | Increase | Decrease`) on a focused+`planningAction` table, routed to a responsible buyer/planner via an inheritance ladder,+worked from the two existing planning pages. **Everything in Phases 2+ of the spec+(plannedOrder cascade + Planned→Firm→Released lifecycle, pegging, continuous regen,+rough-cut capacity, what-if/CTP, programmable release, §9 calm-by-default) is OUT OF+SCOPE.** If a task seems to require any of those, STOP and report — do not build them.++## Progress+- [x] Task 1: Migration — `planningAction` table, enums, ladder columns, tolerance, RLS (96d53c0177; applied via crbn migrate, verified in DB)+- [x] Task 2: `pnpm run generate:types` (regenerated by crbn migrate; planningAction ×30 in types.ts; same commit)+- [x] Task 3: Shared pure reorder-sizing module — computePlanningOrders in @carbon/utils, 239 utils tests green, erp+utils typecheck clean+- [x] Task 4: Zod models — tuples + dismiss/assign validators (derived type lands with Task 7)+- [x] Task 5: ladder resolver + bulk loader in @carbon/ee, precedence tests green+- [x] Task 6: generatePlanningActions — derive+diff pure fns tested (833 ee tests), wired into runMrp post-Phase-7, errors propagate+- [x] Task 7: getPlanningActions (flat queries + JS merge, parent PO id join) + dismiss/assign/mark-actioned services + PlanningAction type+- [x] Task 8: planning.update extended (both routes) — IDOR bind by id+companyId+Open, commitment gates, updateJob+notify for jobs, shortClose for cancel, wire map lowercase+- [x] Task 9: responsibleEmployee on itemPlanningValidator + ItemPlanningForm (Employee picker, all 4 item types via shared form)+- [x] Task 10: /x/settings/planning — ResponsibleEmployeeCard tree (company→location→item-group, inherited placeholders) + RescheduleToleranceCard (0–365), writers in settings.service, nav + path registered+- [x] Task 11: worklist on both planning pages — dismiss/assign route cases added. (Originally a `PlanningActionsTable` card above the grid; reworked 2026-09-29 into the grid's Actions column + expandable rows — `ui/Planning/PlanningActionLines.tsx`, plan `2026-09-29-planning-actions-grid-rows.md`.)+- [x] Task 12: browser-verified on satellite dataset — 72 actions (41 Order/27 Make/2 Expedite/2 Defer) from scheduled+manual MRP; ladder assignment→My actions 45; Review-on-PO nav to parent PO; dismissal survives regen; settings+item-tab render. Screenshots in .ai/scratch/e2e/++## Dependencies+- Task 2 needs Task 1. Tasks 3, 4, 5 need Task 2 (types). Task 6 needs 3+4+5.+ Task 7 needs 4. Task 8 needs 4+7. Tasks 9 and 10 need 1+2 (independent of each other).+ Task 11 needs 6+7+8. Task 12 needs everything.+- Tasks 3, 4, 5 are independent of each other and may run in parallel after Task 2.+- Tasks 9 and 10 are independent and may run in parallel after Task 2.++---++## Task 1: Migration — `planningAction` table, enums, ladder columns, tolerance, RLS++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/{generated}_mrp-planning-actions.sql`+- Copy from (precedent): `packages/database/supabase/migrations/20260820215433_sso-connection.sql` (idempotent `CREATE TYPE` guard + composite-PK table + full four-policy RLS); `packages/database/supabase/migrations/20260120171236_process-active-column.sql` (ALTER ADD COLUMN pattern)++**Steps:**+1. Create the file: `pnpm db:migrate:new mrp-planning-actions` (never hand-pick the timestamp; never `000000` HHMMSS).+2. Create the two enums idempotently (per the sso precedent's `DO $$ ... EXCEPTION WHEN duplicate_object THEN NULL; END $$;` guard):+ ```sql+ DO $$ BEGIN+ CREATE TYPE "planningActionType" AS ENUM+ ('Order', 'Make', 'Expedite', 'Defer', 'Cancel', 'Increase', 'Decrease');+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;+ DO $$ BEGIN+ CREATE TYPE "planningActionStatus" AS ENUM ('Open', 'Dismissed', 'Actioned');+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;+ ```+3. Create the table exactly as spec §P1.2 specifies (bare `NUMERIC`, no precision spec; audit columns; composite PK). Use `CREATE TABLE IF NOT EXISTS`:+ ```sql+ CREATE TABLE IF NOT EXISTS "planningAction" (+ "id" TEXT NOT NULL DEFAULT id('pla'),+ "companyId" TEXT NOT NULL,+ "itemId" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "periodId" TEXT NOT NULL,+ "type" "planningActionType" NOT NULL,+ "status" "planningActionStatus" NOT NULL DEFAULT 'Open',+ "suggestedQuantity" NUMERIC NOT NULL,+ "suggestedDate" DATE NOT NULL,+ "isASAP" BOOLEAN NOT NULL DEFAULT false,+ "purchaseOrderLineId" TEXT,+ "jobId" TEXT,+ "requiresManualAction" BOOLEAN NOT NULL DEFAULT false,+ "supplierId" TEXT,+ "policyName" TEXT,+ "reason" TEXT,+ "triggerValues" JSONB,+ "assignee" TEXT REFERENCES "user"("id"),+ "assigneeOverridden" BOOLEAN NOT NULL DEFAULT false,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "planningAction_change_target_chk" CHECK (+ ("type" IN ('Order','Make') AND "purchaseOrderLineId" IS NULL AND "jobId" IS NULL)+ OR ("type" NOT IN ('Order','Make') AND (("purchaseOrderLineId" IS NOT NULL)::int + ("jobId" IS NOT NULL)::int) = 1)+ )+ );+ ```+4. Indexes (companyId, assignee, item+loc, status) and the partial-unique natural key, exactly as spec §P1.2:+ ```sql+ CREATE INDEX IF NOT EXISTS "planningAction_companyId_idx" ON "planningAction" ("companyId");+ CREATE INDEX IF NOT EXISTS "planningAction_assignee_idx" ON "planningAction" ("companyId", "assignee");+ CREATE INDEX IF NOT EXISTS "planningAction_item_loc_idx" ON "planningAction" ("companyId", "itemId", "locationId");+ CREATE INDEX IF NOT EXISTS "planningAction_status_idx" ON "planningAction" ("companyId", "status");+ CREATE INDEX IF NOT EXISTS "planningAction_createdBy_idx" ON "planningAction" ("createdBy");+ CREATE UNIQUE INDEX IF NOT EXISTS "planningAction_natural_key_idx" ON "planningAction"+ ("companyId", "itemId", "locationId", "type", "periodId",+ COALESCE("purchaseOrderLineId", "jobId", ''))+ WHERE "status" <> 'Actioned';+ ```+5. RLS: enable + four policies. SELECT = any employee; writes = purchasing OR production update (a buyer or planner may dismiss/assign/apply). The engine writes as service-role and bypasses RLS.+ ```sql+ ALTER TABLE "public"."planningAction" ENABLE ROW LEVEL SECURITY;+ CREATE POLICY "SELECT" ON "public"."planningAction" FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+ );+ CREATE POLICY "INSERT" ON "public"."planningAction" FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[])+ OR "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])+ );+ CREATE POLICY "UPDATE" ON "public"."planningAction" FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[])+ OR "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])+ );+ CREATE POLICY "DELETE" ON "public"."planningAction" FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[])+ OR "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])+ );+ ```+6. Ladder columns + tolerance (idempotent `ADD COLUMN IF NOT EXISTS`). **No view recreation is required** — verified: no `SELECT *` view selects from `location`/`itemPlanning` (they appear only in RPC functions selecting explicit columns). Note the item-group tier is a TABLE (step 6b), not a column on `itemPostingGroup`.+ ```sql+ ALTER TABLE "itemPlanning" ADD COLUMN IF NOT EXISTS "responsibleEmployee" TEXT REFERENCES "user"("id");+ ALTER TABLE "location" ADD COLUMN IF NOT EXISTS "responsibleEmployee" TEXT REFERENCES "user"("id");+ ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "defaultResponsibleEmployee" TEXT REFERENCES "user"("id");+ ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "rescheduleToleranceDays" INTEGER NOT NULL DEFAULT 7+ CHECK ("rescheduleToleranceDays" >= 0);+ ```+ The tolerance comparison is **strictly greater than** everywhere (`gap > rescheduleToleranceDays` fires; `≤` is suppressed) — engine, tests, and acceptance all use the same `>`.+6b. **Location-specific item-group ownership table** (the "location → item group" tier — the same group can have a different owner per location, so it is NOT a column on `itemPostingGroup`). **Composite-FK prerequisites (verified 2026-09-11):** `location` already has `UNIQUE ("id","companyId")` (`location_id_companyId_key`, added by `20260905132037_job-operation-batching.sql:159`), but **`itemPostingGroup`'s PK is `("id")` alone** (`20230330024716_parts.sql:69`) with no `("id","companyId")` unique — the composite FK below FAILS without one. Add it first, idempotently:+ ```sql+ DO $$ BEGIN+ ALTER TABLE "itemPostingGroup"+ ADD CONSTRAINT "itemPostingGroup_id_companyId_key" UNIQUE ("id", "companyId");+ EXCEPTION WHEN duplicate_table THEN NULL; WHEN duplicate_object THEN NULL; END $$;+ ```+ Then:+ ```sql+ CREATE TABLE IF NOT EXISTS "itemPostingGroupResponsibility" (+ "id" TEXT NOT NULL DEFAULT id('pgr'),+ "companyId" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "itemPostingGroupId" TEXT NOT NULL,+ "responsibleEmployee" TEXT REFERENCES "user"("id"),+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_location_fkey"+ FOREIGN KEY ("locationId", "companyId") REFERENCES "location"("id", "companyId") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_group_fkey"+ FOREIGN KEY ("itemPostingGroupId", "companyId") REFERENCES "itemPostingGroup"("id", "companyId") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_unique" UNIQUE ("companyId", "locationId", "itemPostingGroupId")+ );+ CREATE INDEX IF NOT EXISTS "itemPostingGroupResponsibility_companyId_idx" ON "itemPostingGroupResponsibility" ("companyId");+ CREATE INDEX IF NOT EXISTS "itemPostingGroupResponsibility_createdBy_idx" ON "itemPostingGroupResponsibility" ("createdBy");+ ```+ Then **explicitly enable RLS** — policies are inert without it — and add the four policies (SELECT via `get_companies_with_employee_role()`; INSERT/UPDATE/DELETE via `get_companies_with_employee_permission('settings_update')`), same form as the `planningAction` block above:+ ```sql+ ALTER TABLE "public"."itemPostingGroupResponsibility" ENABLE ROW LEVEL SECURITY;+ ```+ Include a cross-company access test in the browser-verification pass (a user of company A must not read/write company B's responsibility rows).+7. Apply locally: `pnpm db:migrate`.++**Verify:**+```bash+pnpm db:migrate+# Expected: migration applies cleanly, no errors; regenerates types + swagger.+```+If `pnpm db:migrate` fails because the local stack/DB is not up, STOP and report — do not hand-edit the DB or skip the migration.++**Out of scope:** the Phase-2 `plannedOrder`/`plannedOrderPeg`/`planningRun`/`planningState` tables, the `planningTimeFenceDays` columns, and any `companySettings` automation columns — do NOT create them.++---++## Task 2: Regenerate DB types++**Depends on:** Task 1+**Files:**+- Modify: `packages/database/src/types.ts` (generated — never hand-edit)++**Steps:**+1. Run `pnpm run generate:types`.+2. Commit the regenerated `types.ts` (types regen is normal — do not use casts to avoid it).++**Verify:**+```bash+pnpm run generate:types && grep -c "planningAction" packages/database/src/types.ts+# Expected: generate:types exits 0; grep count > 0 (the table + enums are present).+```++**Out of scope:** editing generated types by hand.++---++## Task 3: Shared pure reorder-sizing module + parity test++**Depends on:** Task 2+**Files:**+- Create: `packages/utils/src/planning-sizing.ts` — pure `computePlanningOrders(input): PlanningOrder[]`+- Create: `packages/utils/src/planning-sizing.test.ts`+- Modify: `packages/utils/src/index.ts` — export the new module+- Modify: `apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx` — refactor `calculateOrders` to delegate to the shared fn+- Copy from (precedent): the branch logic in `apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx:108-490` (`calculateOrders`) and the SQL `calculate_quantity_to_order` in `packages/database/supabase/migrations/20260324120000_planning-quantity-to-order.sql`++**Steps:**+1. Port `calculateOrders` (the four policy branches — `Manual Reorder`→[], `Demand-Based Reorder`, `Fixed Reorder Quantity`, `Maximum Quantity` — plus min/max OQ, `orderMultiple`, `lotSize`, lot-size splitting, ASAP detection) into a **pure, dependency-free** function in `@carbon/utils`. It must NOT import React or any app code. Signature:+ ```ts+ export function computePlanningOrders(input: {+ reorderingPolicy: string;+ periods: { id: string; startDate: string }[];+ projections: number[]; // per-period projected on-hand (week1..weekN), same order as periods+ params: {+ reorderPoint: number; reorderQuantity: number;+ minimumOrderQuantity: number; maximumOrderQuantity: number;+ orderMultiple: number; lotSize: number;+ maximumInventoryQuantity: number;+ demandAccumulationPeriod: number; demandAccumulationSafetyStock: number;+ leadTime: number;+ };+ }): {+ periodId: string; startDate: string; dueDate: string; quantity: number;+ isASAP: boolean; policyName: string;+ triggerValues: { projectedStock?: number; safetyStock?: number; reorderPoint?: number; reorderQuantity?: number; lotSize?: number; leadTime?: number };+ }[]+ ```+ Use `@internationalized/date` + `@carbon/utils` `formatDate` helpers for all date math — never JS `Date`. Use the numeric-precision helpers (`round(x, 0, Up)` for whole-unit ceils) — no raw `Math.ceil`/`toFixed` on value-bearing numbers (the `no-raw-rounding` check).+2. Refactor the client `calculateOrders` in `ItemReorderPolicy.tsx` to call `computePlanningOrders` (keep the supersession "Stock Only" branch and the client-side `ordersCache` where they are; only the four-policy math moves). The client output shape (which includes `dueDate`/`startDate`) must be preserved.+3. Write `planning-sizing.test.ts` with: (a) one fixture per policy asserting the exact orders, and (b) a **parity block** — for a fixture matrix of inputs, assert `computePlanningOrders(...)` total per item equals the SQL `calculate_quantity_to_order` result computed by hand from the same inputs (encode the expected SQL scalar as literals in the test; do not call the DB).++**Verify:**+```bash+pnpm --filter @carbon/utils test+pnpm exec turbo run typecheck --filter=@carbon/utils --filter=erp+# Expected: sizing tests pass (per-policy + parity); both packages typecheck clean.+```+If the ported math diverges from `calculateOrders` in any policy branch (parity fails), STOP and report — do not "adjust" the numbers to make the test pass.++**Out of scope:** Period-of-Supply (POQ) — a Phase-2 fifth policy; do NOT add it. Changing the SQL `calculate_quantity_to_order`.++---++## Task 4: Zod models + derived types for `planningAction`++**Depends on:** Task 2+**Files:**+- Modify: `apps/erp/app/modules/production/production.models.ts` — add `planningActionType`/`planningActionStatus` string-tuple constants + `planningActionDismissValidator` / `planningActionAssignValidator` (for mutations) and any filter enums+- Modify: `apps/erp/app/modules/production/types.ts` — derived `PlanningAction` type+- Copy from (precedent): `apps/erp/app/modules/purchasing/purchasing.models.ts` (validator style, `zfd` usage) and the enum-tuple pattern used for `purchaseOrderStatusType`++**Steps:**+1. Add exported string tuples mirroring the DB enums:+ ```ts+ export const planningActionType = ["Order","Make","Expedite","Defer","Cancel","Increase","Decrease"] as const;+ export const planningActionStatus = ["Open","Dismissed","Actioned"] as const;+ ```+2. Add `planningActionDismissValidator` / `planningActionAssignValidator` (fields: `id`, and for assign `assignee`) using `zfd`. (Apply-action reuses the existing planning.update payload — see Task 8 — so no new validator for apply.)+3. Add the derived read type `PlanningAction` in `production/types.ts` as `NonNullable<Awaited<ReturnType<typeof getPlanningActions>>["data"]>[number]` (wire once Task 7 exists).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: clean typecheck.+```++**Out of scope:** models for any Phase-2 entity.++---++## Task 5: `responsibleEmployee` ladder resolver++**Depends on:** Task 2+**Files:**+- Create: `packages/planning/src/mrp/responsible-employee.ts` — pure resolver + a bulk-load query helper+- Create: `packages/planning/src/mrp/responsible-employee.test.ts`+- Modify: `packages/planning/src/index.ts` — export the resolver if needed by callers++**Steps:**+1. Pure resolver:+ ```ts+ export function resolveResponsibleEmployee(rungs: {+ item: string | null; // itemPlanning.responsibleEmployee for (itemId, locationId)+ itemGroup: string | null; // itemPostingGroupResponsibility.responsibleEmployee for (locationId, group) — location-specific+ location: string | null; // location.responsibleEmployee+ company: string | null; // companySettings.defaultResponsibleEmployee+ }): string | null {+ return rungs.item ?? rungs.itemGroup ?? rungs.location ?? rungs.company ?? null;+ }+ ```+2. Bulk-load helper (Kysely) that, for a company, returns per-(itemId, locationId) the four rung values: `itemPlanning.responsibleEmployee` (by itemId+locationId); the **location-specific item-group** value from `itemPostingGroupResponsibility` joined by `(locationId, itemPostingGroupId)` where `itemPostingGroupId` comes from `item → itemCost.itemPostingGroupId`; `location.responsibleEmployee`; and the single `companySettings.defaultResponsibleEmployee`. Return a `Map<string, string|null>` keyed `itemId·locationId` of the resolved employee. One query per run — never per-item (no N+1). The item-group lookup is keyed by BOTH locationId and group, so the same group resolves to different owners at different locations.+3. Unit test the resolver: item wins over group wins over location wins over company; all null → null.++**Verify:**+```bash+pnpm --filter @carbon/ee test+# Expected: resolver precedence tests pass.+```++**Out of scope:** any (location × item-group) matrix — it is a single-value ladder per rung.++---++## Task 6: `generatePlanningActions` engine step + wire into `runMrp`++**Depends on:** Tasks 3, 4, 5+**Files:**+- Create: `packages/planning/src/mrp/planning-actions.ts` — `generatePlanningActions(client, db, { companyId, userId })`+- Create: `packages/planning/src/mrp/planning-actions.test.ts`+- Modify: `packages/planning/src/mrp/mrp.ts` — call `generatePlanningActions` after the Phase-7 transaction commits (`mrp.ts:937` block)+- Copy from (precedent): the batched-write + Kysely-transaction style already in `mrp.ts` (Phase 7, `BATCH_SIZE = 500`); the RPC read style in `apps/erp/app/modules/purchasing/purchasing.service.ts:460` (`getPurchasingPlanning`)++**Steps:**+1. `generatePlanningActions` runs **after** `runMrp`'s forecast/actual transaction commits (so the planning RPCs read fresh data). For each location:+ - Get/create periods (reuse the same period helper the planning routes use).+ - Call the RPCs `get_purchasing_planning` and `get_production_planning` (via `client.rpc(...)`) → per-item rows with `reorderingPolicy`, reorder params, `week1..weekN` projections, `quantityToOrder`, `preferredSupplierId`, `suppliers`.+ - **Order/Make actions:** run `computePlanningOrders` (Task 3) per item from its projections+params → dated suggestions. Buy items (`replenishmentSystem != 'Make'`) → `Order` (+ `supplierId` = preferred); Make items → `Make`. Carry `policyName`/`triggerValues`/`isASAP`.+ - **Change actions:** query the `openPurchaseOrderLines` and `openProductionOrders` views for the company/location. Per (itemId, locationId), match open orders to net requirements greedily by date:+ - an open order whose matched requirement date is earlier than its own date by **strictly more than** `rescheduleToleranceDays` → **Expedite** (`suggestedDate` = requirement date, target = the PO line / job);+ - later by strictly more than the tolerance → **Defer** (a gap ≤ tolerance never fires — the `>` comparison is canonical everywhere including tests);+ - open order quantity < requirement (after order-multiple rounding) → **Increase**; > requirement → **Decrease**;+ - open order with no remaining requirement → **Cancel**.+ - **Exactly ONE action per target document.** Date and qty rules can both match the same PO line/job; emit only the single highest-priority action per target: **Cancel** (mutually exclusive — no requirement) → **Expedite/Defer** (date) → **Increase/Decrease** (qty). Suppress the lower-priority action *before* the diff-write; a target needing both gets the date action now and the qty action on a later run.+ - Set `requiresManualAction`: for a PO line, true **only** when `isPurchaseOrderLocked(status)` (`purchasing.models.ts` `PURCHASE_ORDER_LOCKED_STATUSES`). Do **NOT** gate on `orderDate` — `insertPurchaseOrder` defaults `orderDate` to today, so it is non-null even on freshly planned POs and would flag every one. For a job, true when `status = 'Ready'` or later (treat `Ready`/`In Progress`/`Paused` as committed; `Draft`/`Planned` are not).+ - Resolve `assignee` via the Task 5 bulk resolver.+2. **Diff-write** in a Kysely transaction on the natural key `(companyId, itemId, locationId, type, periodId, COALESCE(poLineId, jobId, ''))`:+ - matched `Open` row → UPDATE in place (suggested qty/date/reason/isASAP/requiresManualAction refreshed; `assignee` re-resolved ONLY when `assigneeOverridden = false`; bump `updatedAt`/`updatedBy` only on real change);+ - matched `Dismissed` row → leave dismissed UNLESS suggestion changed materially (qty beyond order-multiple rounding, or date beyond `rescheduleToleranceDays`) → set back to `Open`;+ - `Open` **or `Dismissed`** row with no matching computed action → **delete** (retire). A lingering Dismissed row whose need vanished would otherwise occupy the natural key and block a fresh Open row if the same need returns — a returning need is a new situation and must re-surface;+ - `Actioned` rows → ignore (excluded by the partial-unique predicate).+ - Batch 500/statement.+3. Wire into `runMrp` (`mrp.ts`): after the existing `db.transaction().execute(...)` at line 937 returns, call `await generatePlanningActions(client, db, { companyId, userId })` and let any error **propagate** — do NOT catch-and-swallow. A generation failure must fail the run so callers report it (the scheduled Inngest job already try/catches per company and logs; the manual `api/mrp` route surfaces the error to the user) instead of reporting success with stale actions; the already-committed forecasts are fine and actions self-heal on the next successful run. `userId` is the payload's `userId`. **Audit actor:** the scheduled path passes `userId: "system"`, which is a real seeded `user` row (`20230123004317_companies-rls.sql:76` inserts `('system', '[email protected]', …)`), so the `createdBy` FK is satisfied on every deployment — assert this in the test below rather than assuming it.+4. Test `planning-actions.test.ts`: (a) an item short of coverage with no open order → one `Order`/`Make`; (b) an open PO due > tolerance late → `Expedite` referencing the PO line; (c) a date gap of **exactly** the tolerance → no message; tolerance+1 day → message (boundary pins the strict `>`); (d) two consecutive runs on identical inputs → identical rows (diff-write idempotency); (e) a `Dismissed` row survives an unchanged run; a `Dismissed` row whose need vanished is **deleted**, and the returning need creates a fresh `Open` row; (f) `requiresManualAction`: false for `Draft` and `Planned` PO statuses, true for each `PURCHASE_ORDER_LOCKED_STATUSES` value; (g) an open PO wrong on BOTH date and qty → exactly ONE action (the date action) for that target; (h) a run with `userId: "system"` writes actions whose `createdBy = 'system'` satisfies the FK (scheduled-path proof). Use injected fixtures / a test DB per the package's existing test setup.++**Verify:**+```bash+pnpm --filter @carbon/ee test+pnpm exec turbo run typecheck --filter=@carbon/ee+# Expected: generation + diff-write + idempotency tests pass; clean typecheck.+```+If the open-order-to-requirement matching cannot be made deterministic from the available data (no pegging exists in Phase 1), use the documented greedy date-match heuristic above and note its limits in a code comment — do NOT introduce a `plannedOrderPeg` table (Phase 2).++**Out of scope:** removing the `supplyForecast` delete (Phase 2); any planned-order cascade; capacity/what-if.++---++## Task 7: `planningAction` read + mutation services++**Depends on:** Task 4+**Files:**+- Modify: `apps/erp/app/modules/production/production.service.ts` — `getPlanningActions`, `dismissPlanningActions`, `markPlanningActionsActioned`+- Modify: `apps/erp/app/modules/production/production.models.ts` — (validators from Task 4)+- Copy from (precedent): `getPurchasingPlanning` (`purchasing.service.ts:460`) for the `GenericQueryFilters` + `client.from(...)`/`client.rpc(...)` shape; `assign()` in `apps/erp/app/modules/shared/shared.server.ts` for assignment++**Steps:**+1. `getPlanningActions(client, { companyId, locationId, replenishmentSystem: "Buy" | "Make", filters })` — selects `planningAction` joined to item (readable id, name) for the location, filtered to `status <> 'Actioned'` by default, honoring `GenericQueryFilters` (assignee, type, status, search, sorts, pagination). **Also join through `purchaseOrderLine` to select the parent `purchaseOrderId` (+ its readable id)** — `planningAction` stores the LINE id, and `path.to.purchaseOrder(...)` needs the PO id, so "Review on PO" navigation would otherwise be a broken link. Include the job's readable id for the job case. Buy page passes the Buy set (`type IN ('Order','Expedite','Defer','Cancel','Increase','Decrease')` for items whose `replenishmentSystem != 'Make'`); Make page the Make set. Returns raw `{ data, error }`.+2. `dismissPlanningActions(db, { ids, companyId, userId })` — set `status = 'Dismissed'`, `updatedBy`, `updatedAt` for the ids (bulk).+3. `markPlanningActionsActioned(db, { ids, companyId, userId })` — set `status = 'Actioned'` (called by the apply route after a successful apply — Task 8).+4. Assignment reuses the shared **`assign()`** service against `table: "planningAction"` (the column is named `assignee`), and additionally sets `assigneeOverridden = true`. Add a small `assignPlanningAction(client, { id, assignee, userId })` that does both in one update (do NOT route through `api/assign`, because that path also fires table→NotificationEvent mapping we don't want here; a dedicated fn keeps it quiet). Confirm no `NotificationEvent` is wired for `planningAction` in `api+/assign.ts`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: clean typecheck; services return {data,error} and scope by companyId.+```++**Out of scope:** notifications/digests (Phase 2 `PlanningExceptions`).++---++## Task 8: Apply-action route handling + commitment gate++**Depends on:** Tasks 4, 7+**Files:**+- Modify: `apps/erp/app/routes/x+/purchasing+/planning.update.tsx` — accept the new action types + a `planningActionId`+- Modify: `apps/erp/app/routes/x+/production+/planning.update.tsx` — same+- Modify: `apps/erp/app/modules/purchasing/purchasing.service.ts` — add `updatePurchaseOrderLineSchedule(client, { lineId, requiredDate?, purchaseQuantity?, userId })` (thin wrapper over the inline `client.from("purchaseOrderLine").update(...)` pattern already at `planning.update.tsx:244`)+- Copy from (precedent): the existing `action === "order"` branch in each `planning.update.tsx`; `shortClosePurchaseOrderLine` / `updateJobStatus` / `updateJobOperationDueDate` / `notifyScheduleInputsChanged` for change execution++**Steps:**+1. Extend each `planning.update` action switch beyond `"order"`. Keep `"order"` (Order/Make create) exactly as-is. Add branches for `"expedite" | "defer" | "increase" | "decrease" | "cancel"`. **Wire representation:** route discriminators are lowercase; the client maps the stored enum through ONE explicit map before submit (`{ Order: "order", Make: "order", Expedite: "expedite", Defer: "defer", Increase: "increase", Decrease: "decrease", Cancel: "cancel" }` — a raw `Order` must never reach `action === "order"` unmapped or it falls into the unknown-action branch).+2. **Bind to the persisted action first (IDOR guard — CWE-639).** Each change-action branch receives ONLY a `planningActionId`. Before any mutation the route loads the `planningAction` by **id AND companyId**, requires `status = 'Open'`, and takes the action **type, target reference (`purchaseOrderLineId`/`jobId`), `suggestedDate`, and `suggestedQuantity` from the stored row** — never from the request body. Reject id-not-found, cross-company, non-Open, or type-mismatch requests. Every subsequent target lookup and update is `companyId`-scoped.+3. **Commitment gate in the route** (defense-in-depth; the engine already flagged it): re-read the target document's status. If the PO is locked (**`isPurchaseOrderLocked(status)` only — do NOT check `orderDate`, which `insertPurchaseOrder` defaults to today even for planned POs**), or the job status is `Ready`+, **refuse the auto-apply** and return `{ requiresManualAction: true }` (the UI navigates instead — Task 11). Otherwise:+ - Expedite/Defer on a PO line → `updatePurchaseOrderLineSchedule({ lineId, requiredDate: suggestedDate })`.+ - Increase/Decrease on a PO line → `updatePurchaseOrderLineSchedule({ lineId, purchaseQuantity: suggestedQuantity })`.+ - Cancel on a PO line → `shortClosePurchaseOrderLine(db, { lineId, purchaseOrderId, companyId, userId, intent: "close" })`.+ - Expedite/Defer on a job → **exactly one path**: `updateJob({ dueDate: suggestedDate })` (the job's demand target; it recomputes priority), then `notifyScheduleInputsChanged(companyId, "reorder", reason, jobId)` (there is no `"job"` kind — use `"reorder"`). Do NOT call `updateJobOperationDueDate` — that pins an *operation* need-by and sets `manuallyScheduled`, a different input — and never write `jobOperation` dates directly.+ - Increase/Decrease on a job → `updateJob({ quantity })` then `recalculateJobRequirements`.+ - Cancel on a job → `updateJobStatus({ id, companyId, status: "Cancelled", updatedBy })`.+4. On success, call `markPlanningActionsActioned(db, { ids: [planningActionId], companyId, userId })`.+5. Preserve the JSON-body + `action`-discriminator contract and the plain-object return shape (no redirect) both routes use today.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: clean typecheck; unknown-action default branch still errors.+```+If a job-side reschedule cannot be expressed as `updateJob({ dueDate })` + `notifyScheduleInputsChanged` without touching scheduler internals, STOP and report — do not write `jobOperation` dates directly, and do not repurpose `updateJobOperationDueDate` (it pins an operation need-by, a different input).++**Out of scope:** the automated reopen + supplier-notification / change-order flow for committed POs (deferred — the gate just navigates).++---++## Task 9: `responsibleEmployee` field on the item Planning tab++**Depends on:** Tasks 1, 2+**Files:**+- Modify: `apps/erp/app/modules/items/items.models.ts` — add `responsibleEmployee` to `itemPlanningValidator` (`:612`)+- Modify: `apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx` — render an `Employee` field+- Modify: `apps/erp/app/modules/items/items.service.ts` — `upsertItemPlanning` (`:3719`) passes the field through (it spreads validated data, so likely no change beyond the validator)+- Copy from (precedent): any existing `Employee` field usage in a `ValidatedForm` (`apps/erp/app/components/Form/Employee.tsx`)++**Steps:**+1. Add `responsibleEmployee: zfd.text(z.string().optional())` to `itemPlanningValidator`.+2. In `ItemPlanningForm`, import `Employee` from `~/components/Form` and render `<Employee name="responsibleEmployee" label={t\`Responsible\`} />`. This single form serves Part/Material/Tool/Consumable, so all four item Planning tabs get the field at once.+3. Confirm `upsertItemPlanning` persists it (it spreads `validation.data`; the new column exists after Task 1).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: clean typecheck.+```++**Out of scope:** the item-group/location/company rungs (Task 10).++---++## Task 10: Ownership settings screen (clone printer `AssignmentsCard`)++**Depends on:** Tasks 1, 2+**Files:**+- Create: `apps/erp/app/modules/settings/ui/Planning/ResponsibleEmployeeCard.tsx`+- Create/modify route: `apps/erp/app/routes/x+/settings+/planning.tsx` (new settings route) — loader + `intent`-switched action+- Modify: `apps/erp/app/utils/path.ts` — add `settingsPlanning: \`${x}/settings/planning\``+- Modify: settings navigation config to add the new settings link (find where `printing` settings link is registered and mirror it)+- Modify: `apps/erp/app/modules/settings/settings.service.ts` (or the appropriate settings service) — `setDefaultResponsibleEmployee` / `setLocationResponsibleEmployee` / `upsertItemPostingGroupResponsibility` writers for company default / per-location / per-item-group+- Copy from (precedent): `apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx` + `apps/erp/app/routes/x+/settings+/printing.tsx` (fetcher + `intent` action returning `{success,message}`, Combobox-per-row, no ValidatedForm)++**Steps:**+1. Clone the `AssignmentsCard` + `LocationSection` **tree** structure into `ResponsibleEmployeeCard` — this maps 1:1 onto printers (location default → per-work-center override), here **company default → per-location → per-item-group**:+ - a top **company default** row (writes `companySettings.defaultResponsibleEmployee`);+ - one **section per location**, each with a **location default** row (writes `location.responsibleEmployee`) and, nested/indented beneath it, **one row per item group** (writes `itemPostingGroupResponsibility` for that `(locationId, itemPostingGroupId)`), exactly like `LocationSection` renders per-work-center rows under a location.+ - Each row = an `Employee`/`Combobox` picker; an unset item-group row shows an **inherited-placeholder** ("inherits {location default}" — or the company default when the location is itself unset), the way `AssignmentRow` computes `displayState` (`assigned` / `inherited` / `missing`).+2. Loader: `requirePermissions(request, { view: "settings" })`; load `companySettings`, `getLocationsList`, all `itemPostingGroup` rows, all `itemPostingGroupResponsibility` rows for the company (to seed the nested rows), + the people list (`usePeople` source).+3. Action: `requirePermissions(request, { update: "settings" })`; `intent`-switch:+ - `setCompanyDefault` → update `companySettings.defaultResponsibleEmployee`;+ - `setLocation` (locationId, employee) → update `location.responsibleEmployee`;+ - `setItemGroup` (locationId, itemPostingGroupId, employee) → **upsert** `itemPostingGroupResponsibility` on `(companyId, locationId, itemPostingGroupId)` (delete the row when employee is cleared, matching the printer "unset → inherit" behavior).+ Each returns `{ success, message }` (no redirect; fetcher + toast).+4. Register the settings link + `path.to.settingsPlanning`.+5. Settings writers go in the appropriate settings service (`setDefaultResponsibleEmployee`, `setLocationResponsibleEmployee`, `upsertItemPostingGroupResponsibility`).+6. Expose **`rescheduleToleranceDays`** on the same screen as a plain number field (its own small card above the ownership card), zod-validated `z.number().int().min(0).max(365)` in the mutation (the DB `CHECK (>= 0)` is the backstop; a negative value would make every gap actionable).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: clean typecheck. (Browser check happens in Task 12.)+```++**Out of scope:** treating this as a free (customer-type × item-group)-style classification matrix — it is a printer-style **inheritance tree** (company → location → item-group) where only configured cells persist and each falls back up the tree.++---++## Task 11: Worklist columns + "my actions" filter + bulk actions on both planning pages++**Depends on:** Tasks 6, 7, 8+**Files:**+- Modify: `apps/erp/app/routes/x+/purchasing+/planning.tsx` + `apps/erp/app/routes/x+/production+/planning.tsx` — loaders also call `getPlanningActions`+- Modify: `apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx` + `apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx` — new columns, filters, bulk actions+- Copy from (precedent): the existing `columns` `useMemo`, `withSelectableRows`, `renderActions`, and `onBulkUpdate` in `PurchasingPlanningTable.tsx`; the `Assignee` inline control (`apps/erp/app/components/Assignee.tsx`)++**Steps:**+1. Loader: alongside the existing `getPurchasingPlanning`/`getProductionPlanning` projection query, call `getPlanningActions(...)` for the location + replenishment set and pass the rows to the table.+2. Columns: add **action type**, **suggested date**, **suggested qty**, **reason** (rendered from `triggerValues`/`policyName`), **assignee** (render the `Assignee` inline control with `table="planningAction"` — but wire its onChange to the quiet `assignPlanningAction` route, not the notification-firing `api/assign`; simplest: a dedicated fetcher POST), **status**, and an urgency flag from `isASAP`. Give the type and status columns `meta.filter` static options; give assignee a static filter of people so **"my actions"** is a filter value (default the page to the current user via the initial filter/search params).+3. Row primary control: **Apply** — submits to the extended `planning.update` route with the row's **`planningActionId` and the mapped lowercase `action`** (via the Task 8 enum→wire map; e.g. `Expedite` → `"expedite"`) and NOTHING else: the server derives type, target, and proposal values from the persisted row (Task 8 IDOR bind). EXCEPT when `requiresManualAction`, where the control is **"Review on PO/Job"** and links to `path.to.purchaseOrder(purchaseOrderId)` using the **parent PO id from Task 7's join** (never the stored `purchaseOrderLineId` — that link would 404) / `path.to.job(jobId)`.+4. Bulk (reuse `withSelectableRows` + `renderActions`): **Apply selected**, **Assign selected**, **Dismiss selected** (the latter two POST to the new services). Keep the existing "Recalculate" MRP button.+5. Keep the live 48-week projection columns exactly as they are.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp && pnpm run lint+# Expected: clean typecheck + lint.+```++**Out of scope:** a unified cross-module cockpit; the diff/live banners and capacity strip (Phase 2).++---++## Task 12: Browser verification (/test) on the satellite dataset++**Depends on:** Tasks 1–11+**Files:** none (verification only)++**Steps:**+1. Boot the stack (`crbn up`) and run `/test` for the planning-actions feature:+ - Trigger an MRP run (the planning page "Recalculate"), then confirm the worklist shows `Order`/`Make` rows with suggested qty/date/reason and a resolved assignee.+ - Set an item group's `responsibleEmployee` in the new settings screen; recalc; confirm that group's actions route to that person; set a per-item override on the Planning tab and confirm it wins.+ - Filter to "my actions"; apply an Order on an uncommitted plan → PO created, row goes Actioned; apply Expedite on a Draft/Planned PO line → date changes.+ - Confirm a sent/locked PO's change action shows "Review on PO" and navigates instead of editing.+ - Dismiss an action; recalc; confirm it stays dismissed.+2. Capture screenshots of the worklist + settings screen for the PR (net-new UI).++**Verify:**+```bash+# /test playbook passes for each flow above; screenshots saved for the PR.+```+If the stack cannot boot, the feature is BLOCKED (not done) — report it.++**Out of scope:** everything in Phases 2+.diff --git a/.ai/plans/2026-09-11-demand-forecast-consumption.md b/.ai/plans/2026-09-11-demand-forecast-consumption.mdnew file mode 100644index 0000000000..1c82168fa4--- /dev/null+++ b/.ai/plans/2026-09-11-demand-forecast-consumption.md@@ -0,0 +1,521 @@+# Demand Forecast Consumption — implementation plan++**Spec:** .ai/specs/implemented/2026-09-11-demand-forecast-consumption.md+**Research:** .ai/research/demand-forecast-consumption.md+**Audit:** .ai/runs/2026-09-11-demand-forecast-consumption-audit.md+**Branch:** mrp-action-suggestions (worktree kelowna)++Core idea (read the spec first): actual demand consumes the authored forecast+(`demandProjection`) per weekly bucket — own bucket, then backward+`forecastConsumptionBackwardPeriods` weeks, then forward+`forecastConsumptionForwardPeriods` weeks. Computed regeneratively in `runMrp`,+persisted as `demandProjection.consumedQuantity`, subtracted with+`GREATEST(forecastQuantity - consumedQuantity, 0)` at every read site.++## Progress+- [x] Task 1: Pure `consumeForecast` function + unit tests (e24cc547b6)+- [x] Task 2: Migration — columns, view column, three function forks (322288b5be)+- [x] Task 3: Apply migration + regenerate types (322288b5be; dataset/backup hook checks skipped — no DB connection at commit time, rerun in Task 10)+- [x] Task 4: Wire consumption into `runMrp` (Phase 1/4/7) (42c3a86f5c)+- [x] Task 5: Net projections in `generatePlanningActions` (201a87040b)+- [x] Task 6: Net projections in `getItemDemand` + item planning chart (a592b29b80 — merged in the forecast loader, not the chart, so Outgoing card + Supply & Demand list fix too)+- [x] Task 7: Settings service fn + planning settings card (committed; + ui/Planning barrel export)+- [x] Task 8: Consumed annotation in the forecast edit grid (committed; useQuantityFormatter is a callable, not Intl — used directly)+- [x] Task 9: Docs/rules/spec sync (committed with design artifacts; KB regenerated from docs source per agent-knowledge-base rule)+- [x] Task 10: Validation gates + browser verification — @carbon/ee tests (1012 pass), erp+ee typecheck, biome lint, db:check:datasets (4 green), db:check:backups (restorable, via IPv4 URL — localhost→IPv6 quirk), /translate (0 missing, linguito clean). Browser+DB e2e on satellite: settings card renders (4/1); cases A/B/C/D proven through real runMrp + get_production_planning (consumedQuantity persisted, RPC nets, gap heals via backward window, 0/0 setting live); Demand Forecasts grid renders. Test data cleaned up.++## Dependencies+- Task 1 is independent (pure TS, no generated types) — may run in parallel with Task 2.+- Task 3 needs Task 2. Tasks 4–8 need Task 3 (generated types); Task 4 also needs Task 1.+- Tasks 5, 6, 7, 8 are mutually independent (parallelizable).+- Task 9 independent of code tasks (doc text), but write it after Task 4 so it describes reality.+- Task 10 last.++---++## Task 1: Pure `consumeForecast` function + unit tests++**Depends on:** none+**Files:**+- Create: `packages/planning/src/mrp/forecast-consumption.ts`+- Create: `packages/planning/src/mrp/forecast-consumption.test.ts`+- Copy from (precedent): `packages/planning/src/mrp/planning-actions.test.ts` (pure-unit vitest style, named imports from sibling)++**Steps:**+1. Create `forecast-consumption.ts` with exactly this exported API (JSDoc welcome, no classes):++```ts+export type ConsumptionWindow = {+ /** How many periods BEFORE the actual's period may be consumed (0 = own period only). */+ backwardPeriods: number;+ /** How many periods AFTER the actual's period may be consumed. */+ forwardPeriods: number;+};++export type ConsumptionResult = {+ /** periodIndex -> quantity consumed from that period's forecast (0 ≤ consumed ≤ forecast). */+ consumedByPeriod: Map<number, number>;+ /** periodIndex -> forecast − consumed, floored at 0. Every input forecast period has an entry. */+ remainderByPeriod: Map<number, number>;+};++export function consumeForecast(args: {+ /** periodIndex -> authored forecast quantity (entries may be 0; negative treated as 0). */+ forecast: Map<number, number>;+ /** periodIndex -> total consuming actual quantity (SO quantityToConsume + job-material quantityToIssue). */+ actuals: Map<number, number>;+ window: ConsumptionWindow;+}): ConsumptionResult;+```++Algorithm (implement exactly):+- Initialize `remaining = new Map(forecast)` clamping negatives to 0; `consumedByPeriod` starts with 0 for every forecast key.+- Sort actual period indices ascending. For each actual index `p` with quantity `q > 0`:+ - Visit candidate periods in this order: `p`, then `p−1, p−2, … p−backwardPeriods`, then `p+1, … p+forwardPeriods` (skip negative indices; indices need not exist in `forecast` — just skip missing ones).+ - At each candidate `c`: `take = Math.min(q, remaining.get(c) ?? 0)`; if `take > 0`, decrement `remaining[c]`, increment `consumedByPeriod[c]`, decrement `q`. Stop early when `q === 0`.+ - Leftover `q` consumes nothing else (it stands as real demand — caller's concern).+- `remainderByPeriod` = clamped forecast − consumed per key.+- Pure function: do NOT mutate the input maps.++2. Create `forecast-consumption.test.ts` (vitest, `describe`/`it`/`expect` like the precedent) with at minimum these cases (window `{backwardPeriods: 4, forwardPeriods: 1}` unless stated):+ - Same-bucket: F={2:10}, A={2:10} → remainder {2:0}; A+remainder totals 10.+ - Under: F={2:10}, A={2:5} → remainder {2:5} (total demand 5+5=10).+ - Over: F={2:10}, A={2:12} → remainder {2:0} (total 12).+ - The user's gap: F={2:10, 4:10}, A={3:10}, backward 1 → consumed {2:10}, remainder {2:0, 4:10}.+ - Backward preference: F={1:10, 3:10}, A={2:6}, backward≥1/forward≥1 → consumes period 1 (backward) not 3.+ - Forward reach: F={2:10}, A={1:10}, backward 4/forward 1 → consumed {2:10}.+ - Window exhaustion: F={0:5}, A={6:10}, backward 4 → nothing consumed (period 0 is out of reach), remainder {0:5}.+ - Backward spill across multiple periods: F={1:4, 2:4}, A={3:10}, backward 2 → consumes 4+4, remainder both 0.+ - `{0,0}` window ≡ per-bucket max: F={2:10}, A={1:10, 2:3} → remainder {2:7}; nothing consumed by period 1's actual.+ - Earlier actual wins: F={2:10}, A={1:8, 3:8}, backward 1/forward 1 → period-1 actual (forward) takes 8 first, period-3 actual (backward) gets remaining 2.+ - Inputs not mutated; negative forecast clamped to 0.++**Verify:**+```bash+pnpm --filter @carbon/ee test -- forecast-consumption+# Expected: all tests pass, including "gap" and "earlier actual wins" cases; 0 failures+```++**Out of scope:** any import from `mrp.ts` or generated DB types (keep it dependency-free); rounding (caller rounds at persist).++---++## Task 2: Migration — columns, view column, three function forks++**Depends on:** none+**Files:**+- Create: via `pnpm db:migrate:new demand-forecast-consumption` → `packages/database/supabase/migrations/<timestamp>_demand-forecast-consumption.sql`+- Copy from (sources to fork — copy the NEWEST definition, change only what is listed):+ - `packages/database/supabase/migrations/20260811123619_widen-sales-production-scale.sql` lines ~290-324 (`openSalesOrderLines`)+ - `packages/database/supabase/migrations/20260715195226_planning-reads-demand-projections.sql` (`get_production_planning`)+ - `packages/database/supabase/migrations/20260831190142_purchasing-planning-reads-demand-projections.sql` (`get_purchasing_planning`)+ - `packages/database/supabase/migrations/20260716142907_restore-inventory-quantities-tags.sql` (`get_inventory_quantities` — the NEWEST def; NOT `20260316000000`)++**Steps:**+1. `pnpm db:migrate:new demand-forecast-consumption` (never hand-pick the timestamp; HHMMSS must not be `000000`).+2. Section 1 — columns (idempotent):++```sql+-- Forecast consumption: MRP-computed, derived state. Never user-authored.+ALTER TABLE "demandProjection"+ ADD COLUMN IF NOT EXISTS "consumedQuantity" NUMERIC NOT NULL DEFAULT 0;++-- Company-level consumption window, in weekly periods (0/0 = same-week netting only)+ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "forecastConsumptionBackwardPeriods" INTEGER NOT NULL DEFAULT 4+ CHECK ("forecastConsumptionBackwardPeriods" >= 0),+ ADD COLUMN IF NOT EXISTS "forecastConsumptionForwardPeriods" INTEGER NOT NULL DEFAULT 1+ CHECK ("forecastConsumptionForwardPeriods" >= 0);+```++(Precedent for the CHECK-on-ALTER shape: `rescheduleToleranceDays` in `20261006130000_mrp-planning-actions.sql:109-110`. `NUMERIC` bare — no precision spec. `ADD COLUMN ... DEFAULT` is metadata-only, no table rewrite.)++3. Section 2 — `openSalesOrderLines`: `DROP VIEW IF EXISTS "openSalesOrderLines";` then recreate by copying the 20260811123619 definition **verbatim**, adding ONE column directly after the existing `END AS "quantityToSend",` line:++```sql+ -- Pre-job-dedup open quantity: what this line CONSUMES from the demand+ -- forecast. An MTO line fully covered by its linked job still consumed+ -- the forecast that predicted it; only its residual drives new supply.+ sol."quantityToSend" AS "quantityToConsume",+```++Keep `WITH (security_invoker=true)` and every other column/join/filter identical. Add a `-- Forked from 20260811123619_widen-sales-production-scale.sql` comment.++4. Section 3 — `get_production_planning`: `DROP FUNCTION IF EXISTS get_production_planning(TEXT, TEXT, TEXT[]);` then copy the ENTIRE function from `20260715195226` verbatim (same signature, same RETURNS TABLE), changing ONLY the third UNION arm of `demand_data` (lines ~152-158 of the source) to:++```sql+ UNION ALL+ -- Top-level manual projections, net of forecast consumption: actual+ -- demand consumed them during the MRP run (demandProjection.consumedQuantity),+ -- so only the unconsumed remainder still drives demand here.+ SELECT "itemId", "periodId", NULL as "actualQuantity",+ GREATEST("forecastQuantity" - "consumedQuantity", 0) AS "forecastQuantity"+ FROM "demandProjection"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+```++5. Section 4 — `get_purchasing_planning`: same treatment, source `20260831190142`. Add `DROP FUNCTION IF EXISTS get_purchasing_planning(TEXT, TEXT, TEXT[]);` before the `CREATE OR REPLACE` (the source file omits it; signature is unchanged so this is belt-and-braces idempotency). Change ONLY the third UNION arm of its `demand_data` CTE (source lines ~133-141) to the same `GREATEST` form. Note this function's RETURNS list differs from production's (`"purchasingBlocked"` vs `"manufacturingBlocked"`) — copy ITS OWN list, do not cross-pollinate.+6. Section 5 — `get_inventory_quantities`: `DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT, TEXT);` then copy the ENTIRE function from `20260716142907` verbatim (signature `(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)`), changing ONLY the `demand_forecast` CTE (source lines ~279-292) by appending a third UNION arm inside its `combined` subquery, matching that CTE's own column aliasing:++```sql+ UNION ALL+ SELECT "itemId", GREATEST("forecastQuantity" - "consumedQuantity", 0) AS qty+ FROM "demandProjection"+ WHERE "companyId" = company_id AND "locationId" = location_id+```++(If the source CTE uses table aliases like `da`/`df`, alias this arm `dp` consistently. This arm ADDS projections to inventory demand — they were previously omitted entirely; the spec calls this fix out explicitly.)+7. Re-read the finished file top to bottom checking idempotency: every ALTER guarded with IF NOT EXISTS, every DROP guarded with IF EXISTS, no `NUMERIC(x,y)`, no `CURRENT_DATE`.++If any of the four source definitions has drifted (a newer migration now defines it — check with `grep -rl "get_production_planning\|get_purchasing_planning\|get_inventory_quantities\|openSalesOrderLines" packages/database/supabase/migrations/ | sort | tail`), STOP and report — do not fork a stale definition.++**Verify:**+```bash+ls packages/database/supabase/migrations/ | tail -3+# Expected: the new <timestamp>_demand-forecast-consumption.sql is the newest file+grep -c "GREATEST(\"forecastQuantity\" - \"consumedQuantity\", 0)" packages/database/supabase/migrations/*demand-forecast-consumption.sql+# Expected: 3 (two planning fns + inventory fn)+grep -c "quantityToConsume" packages/database/supabase/migrations/*demand-forecast-consumption.sql+# Expected: >= 1+```++**Out of scope:** RLS changes (existing policies cover new columns); `TABLE_RENAMES` (nothing renamed/dropped); touching `demandForecast`/`demandActual` DDL; the older `get_inventory_quantities` definitions.++---++## Task 3: Apply migration + regenerate types++**Depends on:** Task 2+**Files:**+- Modify (generated): `packages/database/src/types.ts` (via script — never hand-edit)++**Steps:**+1. `pnpm db:migrate` (applies pending migrations to the local DB and regenerates types + swagger). If the local DB is unreachable, STOP and report — do not attempt a DB rebuild.++**Verify:**+```bash+grep -n "consumedQuantity" packages/database/src/types.ts | head -3+# Expected: consumedQuantity appears in the demandProjection Row/Insert/Update types+grep -n "quantityToConsume" packages/database/src/types.ts | head -3+# Expected: quantityToConsume appears in the openSalesOrderLines view Row type+grep -n "forecastConsumptionBackwardPeriods" packages/database/src/types.ts | head -2+# Expected: present on companySettings+```++**Out of scope:** committing (that happens per-task via check-and-commit at execute time).++---++## Task 4: Wire consumption into `runMrp` (Phase 1/4/7)++**Depends on:** Tasks 1, 3+**Files:**+- Modify: `packages/planning/src/mrp/mrp.ts` — Phase 1 settings load; Phase 4 loop reorder + consumption; Phase 7 persist++**Steps:**+1. Import `consumeForecast` from `./forecast-consumption` and `round` from `@carbon/utils`.+2. **Phase 1** (near the existing 5-way `Promise.all` at ~lines 125-183): also load the window settings — a single-row read, alongside (not inside) the fetchAll batch:++```ts+const consumptionSettings = await client+ .from("companySettings")+ .select("forecastConsumptionBackwardPeriods, forecastConsumptionForwardPeriods")+ .eq("id", companyId)+ .maybeSingle();+const consumptionWindow = {+ backwardPeriods: consumptionSettings.data?.forecastConsumptionBackwardPeriods ?? 4,+ forwardPeriods: consumptionSettings.data?.forecastConsumptionForwardPeriods ?? 1+};+```++3. **Phase 4 restructure** (current code: projections loop `:442-477`, SO loop `:480-515`, JM loop `:518-552`). New order: SO loop, JM loop, THEN projections+consumption. Build a period index first:++```ts+const periodIndexById = new Map<string, number>();+periods.forEach((p, i) => { if (p.id) periodIndexById.set(p.id, i); });+// locationId␟itemId (makeLocationItemKey) -> periodIndex -> consuming quantity+const consumptionActuals = new Map<string, Map<number, number>>();+```++4. **SO loop changes**: the loop currently skips on `!line.quantityToSend`. Change the guard so a line with `quantityToConsume > 0` still consumes even when its demand residual is 0 (the MTO-covered case):+ - Skip only when `!line.itemId || !line.locationId`, or when BOTH `(line.quantityToSend ?? 0) <= 0` AND `(line.quantityToConsume ?? 0) <= 0`.+ - Keep every existing demand-side write (`grossDemand`, `salesDemandByKey`, `topLevelContributors`) gated on `line.quantityToSend > 0` exactly as today.+ - Additionally, when `(line.quantityToConsume ?? 0) > 0` and the period resolved, accumulate into `consumptionActuals` under `makeLocationItemKey(line.locationId, line.itemId)` at `periodIndexById.get(period.id)`.+5. **JM loop changes**: same accumulation using `line.quantityToIssue` (its existing demand quantity — job materials have no dedup split), same key/period shape. No change to its demand-side writes.+6. **Projections loop replacement**: group loaded projections per `makeLocationItemKey(projection.locationId, projection.itemId)`. Per group:++```ts+const forecast = new Map<number, number>(); // periodIndex -> forecastQuantity+// (skip rows whose periodId is not in periodIndexById — defensive; Phase 1 already filters to horizon)+const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast,+ actuals: consumptionActuals.get(locationItemKey) ?? new Map(),+ window: consumptionWindow+});+```++ For each projection row: its remainder (`remainderByPeriod.get(periodIndex) ?? clampedForecast`) replaces `projection.forecastQuantity` in the existing body — `grossDemand` add and the `Demand Projection` contributor both use the remainder, and a remainder of 0 adds neither. Keep the existing null-guards (`!projection.itemId || !projection.locationId`) and the `> 0` gate. Rename the vestigial `netDemand` local to `remainder` and update the stale comment block at `:438-441` (it still describes the old no-netting design) plus the wrong migration filename in the comment at `:464` (`20260527115843_demand-projection-source.sql` → `20260527110002_demand-forecast-source.sql`).+ Also collect persist rows for EVERY loaded projection (consumed 0 included):++```ts+// itemId, locationId, periodId, consumedQuantity (round() at persist — internal scale)+consumptionUpserts.push({ itemId, locationId, periodId, consumedQuantity: round(consumedByPeriod.get(periodIndex) ?? 0) });+```++7. **Phase 4.5 untouched**: consumption runs entirely BEFORE the supersession redirect (spec decision — authored identity). Do not move or modify Phase 4.5.+8. **Phase 7 persist** (inside the existing `db.transaction().execute` at `:938`, after the existing upsert loops, same `BATCH_SIZE = 500`): batched `UPDATE ... FROM (VALUES ...)` — an UPDATE, not an upsert, so a projection deleted mid-run can never be resurrected:++```ts+import { sql } from "kysely"; // top of file if not present+for (let i = 0; i < consumptionUpserts.length; i += BATCH_SIZE) {+ const batch = consumptionUpserts.slice(i, i + BATCH_SIZE);+ await sql`+ UPDATE "demandProjection" AS dp+ SET "consumedQuantity" = v."consumedQuantity"::numeric,+ "updatedAt" = ${datetime.timestamp()},+ "updatedBy" = ${userId}+ FROM (VALUES ${sql.join(+ batch.map((r) => sql`(${r.itemId}, ${r.locationId}, ${r.periodId}, ${r.consumedQuantity})`)+ )}) AS v("itemId", "locationId", "periodId", "consumedQuantity")+ WHERE dp."itemId" = v."itemId"+ AND dp."locationId" = v."locationId"+ AND dp."periodId" = v."periodId"+ AND dp."companyId" = ${companyId}+ `.execute(trx);+}+```++(Precedent for the VALUES-batch shape: `packages/jobs/src/workflows/retention.ts` pass 3. `datetime.timestamp()` matches the existing Phase-7 upserts' `updatedAt`.)+9. If `makeLocationItemKey` or the Phase-7 structure differs from what this task describes, STOP and report — do not improvise around a drifted `mrp.ts`.++**Verify:**+```bash+pnpm --filter @carbon/ee test+# Expected: all suites pass (forecast-consumption, planning-actions, responsible-employee, scheduling)+pnpm exec turbo run typecheck --filter=@carbon/ee+# Expected: exit 0, no type errors+```++**Out of scope:** Phase 4.5 supersession logic; `explodeBom` / `mrp-engine.ts`; `demandActual` write semantics (still the deduped demand quantities); `generatePlanningActions` (Task 5).++---++## Task 5: Net projections in `generatePlanningActions`++**Depends on:** Task 3+**Files:**+- Modify: `packages/planning/src/mrp/planning-actions.ts` — the demand union (~lines 527-575)++**Steps:**+1. In the three-way `Promise.all` (~line 529), add `"consumedQuantity"` to the `demandProjection` select:++```ts+db.selectFrom("demandProjection")+ .select(["itemId", "locationId", "periodId", "forecastQuantity", "consumedQuantity"])+ .where("companyId", "=", companyId)+ .execute()+```++2. In the projections loop of the union (~lines 566-574), change the added quantity to the net remainder:++```ts+addDemand(+ row.itemId,+ row.locationId,+ row.periodId,+ Math.max((Number(row.forecastQuantity) || 0) - (Number(row.consumedQuantity) || 0), 0)+);+```++3. Update the union's header comment (`── demand per (item, location, period): actual + forecast + projection…`) to say the projection arm is net of consumption, matching the RPCs.++**Verify:**+```bash+pnpm --filter @carbon/ee test -- planning-actions+# Expected: existing planning-actions tests still pass+pnpm exec turbo run typecheck --filter=@carbon/ee+# Expected: exit 0+```++**Out of scope:** `deriveChangeActions` internals; the supply queries; `rescheduleToleranceDays` handling.++---++## Task 6: Net projections in `getItemDemand` + item planning chart++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/modules/items/items.service.ts` — `getItemDemand` (~lines 647-683)+- Modify: `apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts` and/or the `ItemPlanningChart` component (find via `grep -rn "getItemDemand" apps/erp/app`) — merge projections into the demand series++**Steps:**+1. Add a third query to `getItemDemand`'s `Promise.all`, same filter shape as the existing two:++```ts+client.from("demandProjection").select("*")+ .eq("itemId", itemId).eq("locationId", locationId)+ .eq("companyId", companyId).in("periodId", periods)+```++Return `{ actuals, forecasts, projections }` (projections raw rows — netting happens at the merge point so the caller can also show gross if it wants).+2. In the consumer that assembles per-period demand for the chart (follow `getItemDemand`'s callers), add the net projection quantity per period to the demand value: `Math.max((forecastQuantity ?? 0) - (consumedQuantity ?? 0), 0)`, summed into the same period bucket as `demandForecast` rows. The resulting series must equal what the planning RPC's `demand_data` computes for the same item.+3. If the chart's data shape makes the merge ambiguous (e.g. it renders actual and forecast as separate series), merge the net projection into the FORECAST series (it is forecast demand) and STOP AND REPORT only if neither series fits.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+grep -n "projections" apps/erp/app/modules/items/items.service.ts | head -3+# Expected: getItemDemand now returns projections+```++**Out of scope:** chart visual redesign; other `items.service.ts` functions.++---++## Task 7: Settings service fn + planning settings card++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/modules/settings/settings.service.ts` — new fn next to `setRescheduleToleranceDays` (~line 1678)+- Modify: `apps/erp/app/routes/x+/settings+/planning.tsx` — loader fields, validator, action intent, render+- Create: `apps/erp/app/modules/settings/ui/Planning/ForecastConsumptionCard.tsx`+- Copy from (precedent): `RescheduleToleranceCard` in `apps/erp/app/modules/settings/ui/Planning/ResponsibleEmployeeCard.tsx` lines 248-323 (`NumberField` + `useFetcher` + intent pattern, exact imports listed there)++**Steps:**+1. Service fn, mirroring `setRescheduleToleranceDays`:++```ts+export async function setForecastConsumptionWindow(+ client: SupabaseClient<Database>,+ args: { companyId: string; backwardPeriods: number; forwardPeriods: number }+) {+ return client+ .from("companySettings")+ .update({+ forecastConsumptionBackwardPeriods: args.backwardPeriods,+ forecastConsumptionForwardPeriods: args.forwardPeriods+ })+ .eq("id", args.companyId);+}+```++2. `planning.tsx` loader: read both columns from the existing `getCompanySettings` result with `?? 4` / `?? 1` fallbacks, alongside `rescheduleToleranceDays`.+3. `planning.tsx` validator + action: inline `const consumptionValidator = z.coerce.number().int().min(0).max(52);` next to the existing `rescheduleToleranceValidator` (now `forecastConsumptionValidator`, both in `settings.models.ts`); new `case "setForecastConsumption"` parsing `backwardPeriods` and `forwardPeriods` form fields, calling `setForecastConsumptionWindow`, returning `{ success, message }` in the same shape as `setTolerance`.+4. `ForecastConsumptionCard.tsx`: clone `RescheduleToleranceCard`'s structure — one Card, two labelled `NumberField`s (min 0, max 52): "Consume forecast backward (weeks)" and "Consume forecast forward (weeks)", copy explaining: "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from up to this many weeks back (then forward) instead of double-counting." Submit both values with `intent=setForecastConsumption` via `useFetcher`. Wrap user-facing strings in Lingui (`t` / `<Trans>`) if and only if `ResponsibleEmployeeCard.tsx` does — match the host file's i18n usage exactly.+5. Render `<ForecastConsumptionCard …/>` in `planning.tsx` directly after `<RescheduleToleranceCard …/>` (~line 190). Export the new card from the `ui/Planning` barrel if one exists (check `apps/erp/app/modules/settings/ui/Planning/index.ts`; if absent, import directly like `RescheduleToleranceCard` is).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+grep -n "setForecastConsumption" apps/erp/app/routes/x+/settings+/planning.tsx | head -3+# Expected: validator/action case + card usage present+```++**Out of scope:** migrating `RescheduleToleranceCard` to `ValidatedForm`; `settings.models.ts` (the planning page's precedent is inline validators — follow the host file).++---++## Task 8: Consumed annotation in the forecast edit grid++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx` — loader passes per-week consumed values+- Modify: `apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx` — render annotation under each week cell+- Copy from (precedent): the loader's existing `weekValues` flattening (route lines ~45-65) and the week-cell render (form lines ~247-274)++**Steps:**+1. Route loader: next to the existing `weekValues` build, add:++```ts+const consumedValues: Record<number, number> = {};+periods.forEach((period, index) => {+ const row = existingProjections.data?.find((f) => f.periodId === period.id);+ if (row?.consumedQuantity && row.consumedQuantity > 0) consumedValues[index] = row.consumedQuantity;+});+```++Return `consumedValues` alongside `periods` and `initialValues`, and pass it into `<DemandProjectionForm …/>` as a new prop `consumedValues: Record<number, number>`.+2. In the form's week-cell render (the `<Number key={index} name={`week${index}`} …/>` block at ~lines 247-274), wrap each cell in a `<div>` and, when `consumedValues[index]` exists, render beneath the input:++```tsx+<span className="text-xs text-muted-foreground">+ {formatter.format(consumedValues[index])} consumed+</span>+```++where `formatter` is the app's quantity formatter hook (grep `useQuantityFormatter` in `apps/erp/app` for the import path; if the hook does not exist under that name, use the same formatter the `DemandProjectionTable` uses for quantities — do NOT inline `minimumFractionDigits`/`maximumFractionDigits`, per the numeric-precision rule). Wrap the "consumed" text for i18n exactly the way the rest of `DemandProjectionForm.tsx` handles user-facing strings (it imports Lingui if it does — match the file).+3. Do not make the annotation interactive and do not change the input's value semantics — `consumedQuantity` is display-only here; the action continues to write only `forecastQuantity` (absent columns are preserved by the PostgREST upsert, and zero-quantity deletes are correct: no forecast row, no consumption).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+grep -n "consumedValues" apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx | head -3+# Expected: prop received and rendered+```++**Out of scope:** the `DemandProjectionTable` list view; the chart inside the form; changing the action's upsert payload.++---++## Task 9: Docs/rules/spec sync++**Depends on:** Task 4 (describe reality, not intent)+**Files:**+- Modify: `docs/content/docs/reference/forecast.mdx` — the additive-demand paragraph + stale paths. (CORRECTED during execution: the plan originally named `apps/erp/app/modules/agent/kb/docs/reference/forecast.md`, but the agent knowledge base is baked from `docs/content/**` at build time per `.claude/rules/agent-knowledge-base.md` — edit the source page; nothing is generated or committed separately.)+- Modify: `.claude/rules/mrp-system.md` — run-flow inputs + new settings+- Modify: `.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md` — changelog note+- Modify: `.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md` — changelog + status++**Steps:**+1. `forecast.md`: replace the paragraph stating projections and actuals are "added in full alongside" with the consumption model (own week → backward N → forward M, company settings, `consumedQuantity`, remainder drives MRP; actuals always count in full). Fix the stale component/route paths it cites (`ui/Projection/…` → `ui/DemandProjection/…`, `projections.new.tsx` → `demand-forecasts.new.tsx`).+2. `mrp-system.md`: in the run-flow "Inputs (demand)" bullet, describe consumption (what consumes, window settings, `consumedQuantity` persisted in Phase 7, `GREATEST` netting at the read sites) and remove/replace the `<!-- UNVERIFIED -->` week-count note if Task 4 confirmed the horizon. Keep it factual to committed code only.+3. MRP v2 spec: append changelog line — "2026-09-11: `demandProjection` gains `consumedQuantity` (forecast consumption, see `.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md`), superseding this spec's 'demandProjection gains no columns' scope note."+4. This feature's spec: set `Status: in-progress`, append changelog line for implementation start.++**Verify:**+```bash+grep -n "consumedQuantity" docs/content/docs/reference/forecast.mdx .claude/rules/mrp-system.md+# Expected: both files describe the consumption model+grep -c "added in full alongside" docs/content/docs/reference/forecast.mdx+# Expected: 0+```++**Out of scope:** the customer docs site (`docs/`) — MRP forecast docs there, if any, ride a separate carbon-docs pass; glossary changes.++---++## Task 10: Validation gates + browser verification++**Depends on:** Tasks 1-9+**Files:** none (verification only)++**Steps:**+1. Run the gates:++```bash+pnpm --filter @carbon/ee test+pnpm exec turbo run typecheck --filter=@carbon/ee --filter=erp+pnpm run lint+pnpm db:check:datasets+pnpm db:check:backups+```++2. Browser verification via `/test` (requires the dev stack; boot with plain `crbn up` if not running, then `/auth`). Scenarios, per the spec's acceptance criteria:+ a. **Same week:** author a forecast of 10 for a Make item in week W (Production → Demand Forecasts); create+release a sales order for 10 of that item promised in week W (status must reach To Ship); run MRP via the planning page's Recalculate; verify the production planning grid shows week-W demand 10 (not 20) and exactly one suggestion of 10 given no stock; verify the forecast edit grid shows "10 consumed" on week W.+ b. **Gap:** forecasts 10 in week W+1 and 10 in week W+3 (0 elsewhere); SO for 10 promised in week W+2; Recalculate; verify W+1 shows consumed 10 / remainder 0, W+3 untouched, and total horizon demand for the item is 20.+ c. **Over:** forecast 10, SOs totalling 12 same week; Recalculate; demand 12, no remainder.+ d. **Settings:** change the window to 0/0 in Settings → Planning, Recalculate, verify the gap scenario now double-counts week W+2's SO (proves the setting is live); restore 4/1.+ e. **MTO coverage:** forecast 10 in week W; Make-to-Order SO for 10 in week W with a linked live job covering it (create the job from the SO line); Recalculate; verify the forecast still shows 10 consumed and the grid shows no phantom 10 of forecast remainder on top of the job-covered order.+ Record pass/fail per scenario; a failure means STOP and report, not improvise.++**Verify:**+```bash+# The commands in step 1, each exiting 0; step 2's four scenarios all "pass" in the /test report.+```++**Out of scope:** committing/pushing (Brad decides; no auto-commit), performance load-testing.diff --git a/.ai/plans/2026-09-29-planning-actions-grid-rows.md b/.ai/plans/2026-09-29-planning-actions-grid-rows.mdnew file mode 100644index 0000000000..f0a129d0e4--- /dev/null+++ b/.ai/plans/2026-09-29-planning-actions-grid-rows.md@@ -0,0 +1,36 @@+# Planning actions as grid column + expandable rows++Replaces the `PlanningActionsTable` card (hand-rolled table above the planning grid) with+Carbon-native surfaces on the existing `Table`: an **Actions** column, an **expandable row**+listing the item's persisted `planningAction` rows, an **Assigned to me** quick filter, and+an **Apply Suggested Changes** bulk item. One table per route, state in the URL.++Design rationale: this conversation's brief (Sept 29). Spec context:+`.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md` §P1.7 / §10.++## Tasks++- [x] 1. Shared UI: `modules/production/ui/Planning/PlanningActionLines.tsx`+ (type badge + icon vocabulary, Actions cell, expanded-row lines, filter options,+ `isApplyablePlanningAction`) + pure `planning-action-scope.ts` (URL keys, loader+ scope resolver, unit-tested). Delete `PlanningActionsTable.tsx`.+- [x] 2. Services: optional `itemIds` restriction on `getPurchasingPlanning` /+ `getProductionPlanning`.+- [x] 3. Loaders (both planning routes): strip the `planningActions` column filter and the+ assignee filter (first an `actions=mine` switch, now the Assignee column's people+ filter, `filter=planningAssignee:in:<userId>,…`) from the grid filters, resolve them to item ids from the loaded+ actions, pass `itemIds`. Drop the card.+- [x] 4. Grids (both): `planningActions` prop, Actions column (static type filter, export+ value), `canExpandRow` / `renderExpandedRow`, `headerActions` switch, worklist+ fetcher (apply / dismiss / reopen / assign-to-me → existing update route),+ "Apply Suggested Changes" in `renderActions`.+- [x] 5. Update routes (both): `reopen` case (mirror `dismiss`, calls the new+ `reopenDismissedPlanningActions`; the existing `reopenPlanningActions` is the apply claim rollback).+- [x] 6. Verify: `pnpm exec turbo run typecheck --filter=erp`, `pnpm run lint`.++## Verification++- typecheck + biome green+- Browser (if a dev server is up): Actions column shows badges; chevron only on items with+ actions; expanded lines show Apply / Review / Order; switch filters the grid; bulk+ "Apply Suggested Changes" posts one batched request.diff --git a/.ai/plans/2026-10-01-planning-horizon.md b/.ai/plans/2026-10-01-planning-horizon.mdnew file mode 100644index 0000000000..faf5f82f61--- /dev/null+++ b/.ai/plans/2026-10-01-planning-horizon.md@@ -0,0 +1,79 @@+# Planning horizon (time fence) for MRP planning actions++Adds a per-item **planning horizon** (days from today) that limits which planning+actions and suggested orders the two planning grids surface. MRP keeps generating+actions over the full 48 weeks; the horizon is a **read-time lens**, so a buyer can+widen it on one row without an MRP rerun and without saving anything.++Source request: `.context/attachments/7lixQz/pasted_text_2026-10-01_04-35-37.txt`.+Builds on `.ai/plans/2026-09-08-mrp-planning-actions.md` and+`.ai/plans/2026-09-29-planning-actions-grid-rows.md`.++## Decisions (agreed Oct 1)++- **One engine.** The request's four aggregate rules (supply vs demand inside the+ fence) are NOT implemented. The existing per-document actions map onto them:+ New = Order/Make/Increase, Cancel = Cancel/Decrease, Reschedule In = Expedite,+ Reschedule Out = Defer.+- **Planned POs stay supply.** Carbon has no requisition document.+- **Empty horizon = no fence** (today's behaviour). Resolution:+ `itemPlanning.planningHorizonDays` else `companySettings.defaultPlanningHorizonDays`+ else none.+- **Weekly dates.** "1st negative on-hand" is the start of the first week whose+ projection is below zero.+- **Per-row fence edit**, page state only. Sort/filter use the saved horizon.+- **No primary action / priority.** The Actions chips stay; no sort by action.+- **Bulk Order respects the fence.**+- Column name is `planningHorizonDays`, NOT `planningTimeFenceDays` — the MRP v2+ spec reserves that name for the auto-firm fence, a different concept.++## Tasks++- [x] 1. Migration `planning-horizon`: `itemPlanning.planningHorizonDays`,+ `companySettings.defaultPlanningHorizonDays`, `planningAction.horizonDate` ++ `latestOrderDate` (backfilled), and the two grid wrappers+ `get_purchasing_planning_grid` / `get_production_planning_grid` (base RPC ++ item group, horizon, time fence date, first negative week, latest order date,+ and the action-type / assignee filter evaluated inside the fence).+- [x] 2. `pnpm db:migrate` (regenerates types).+- [x] 3. Engine: `horizonDate` + `latestOrderDate` on every candidate, carried+ through the diff-write; unit tests.+- [x] 4. Pure fence helpers + tests (`planning-fence.ts`); scope resolver returns+ filter inputs instead of item ids.+- [x] 5. Services + loaders: grid RPCs, actions loaded for the page's items only+ (removes the 500-action cap).+- [x] 6. Grids (both): Item Group, Planning Horizon (editable), 1st Negative columns;+ fence-aware Actions cell, expanded row, bulk apply and bulk Order.+- [x] 7. Drawers (both): orders trimmed to the fence with an "include the rest"+ control, fence marker on the chart, the item's change actions listed.+- [x] 8. Item Planning tab field + Settings → Planning company default.+- [x] 9. Docs (`.claude/rules/mrp-system.md`), MCP digest, lint, typecheck, tests.++## As built++- Grid RPCs are WRAPPERS (`get_*_planning_grid`) around the base planning RPCs, not+ redefinitions: the base stays the one definition of the projection.+- `planningAction.horizonDate` = earlier of the target order's current date and the+ suggested date; `latestOrderDate` = required date less lead time (new supply only).+- The drawer lists suggested changes with the open-orders grid (`OpenOrdersGrid` in `PlanningOrderGrids.tsx`, each open order carrying its action), not the+ grid's `PlanningActionLines` — see the `@container` lesson in `.ai/lessons.md`.+- The drawer has its own Planning Horizon control; moving the fence re-splits the suggested+ orders and re-merges the existing ones.+- Browser pass done on the demo company at 1440 and 1100 px (fence in grid and drawer,+ pull-in, suggested-changes table, expanded row, chart marker).+- The drawer is two editable grids (`PlanningOrderGrids.tsx`): a draft Suggested Orders+ table and an Open Orders table whose cells autosave through new `updateLine` /+ `updateJob` actions; planning actions sit on the row of the order they target. New+ shared pieces: `EditableDate` and `Grid isRowEditable`. Drawer widened to `xl`.+- Browser-checked: draft edits (quantity, date), locked rows, refusal paths of both save+ actions (409 / 400 / 404). NOT exercised: a successful autosave, since that writes to+ the database.+- Not done: translations for the new strings (`pnpm translate` at commit time).++## Verification++- `pnpm --filter @carbon/planning test`, `pnpm --filter erp test` (touched files)+- `pnpm exec turbo run typecheck --filter=erp --filter=@carbon/planning`+- `pnpm run lint`+- SQL: call both grid RPCs against the local DB with and without a horizon and+ with the action filter.diff --git a/.ai/plans/2026-10-06-planning-po-reopen-finalize.md b/.ai/plans/2026-10-06-planning-po-reopen-finalize.mdnew file mode 100644index 0000000000..1f11e9dff3--- /dev/null+++ b/.ai/plans/2026-10-06-planning-po-reopen-finalize.md@@ -0,0 +1,33 @@+# Planning: reopen / finalize purchase orders from the action menu++Context: a planning action on a committed PO shows **Review**. The planner had to+leave the page, reopen the PO, come back, and wait for MRP before Apply showed.++Decisions (2026-10-06, with Brad):+- Reopen from planning moves the PO to **Planned**, not Draft — Draft is not MRP+ supply (`openPurchaseOrderLines` excludes it), so a Draft PO's lines drop out+ and the next run suggests the whole need again as a new order.+- Mirror the PO page: **Reopen** (no revision) and **Reopen as Revision** (only+ a released PO: locked status + orderDate) are separate items.+- **Finalize** reuses `PurchaseOrderFinalizeModal` + the finalize route.++## Tasks++- [x] Status route (`purchase-order+/$orderId.status.tsx`): reopen semantics+ (delete permission from a locked status, pending approvals cancelled,+ revision) apply to a reopen to Planned as well as Draft.+ `reopenPurchaseOrderAsRevision` / `canCreatePurchaseOrderRevision` take+ the target status.+- [x] `getPlanningActions`: embed the line's promised date, the delivery's+ promised date and the PO's orderDate.+- [x] `PlanningActionRowActions`: Review vs Apply from the LIVE PO status+ (`planningActionNeedsReview`, pure + tested); ⋯ gains Reopen / Reopen as+ Revision (committed PO) and Finalize (Draft / Planned PO).+- [x] Finalize from planning: `api+/purchasing.purchase-order.$id.finalize.ts`+ (PO + default CC) and `PurchaseOrderFinalizeModal` takes the id as a prop.+- [x] Apply quantity is received-aware: `purchaseQuantity` = received + the+ suggested remaining (a reopened PO can carry receipts).+- [x] MRP: an order late within the reschedule tolerance counts from its first+ need week when sizing (no "Increase 100 → 200" for a need it covers).+- [x] Remove unused `withoutOrdersFoldedIntoIncreases` (already removed in the working tree).+- [x] Verify: vitest (planning + erp tests touched), erp typecheck, biome.diff --git a/.ai/playbooks/forecast-consumption.md b/.ai/playbooks/forecast-consumption.mdnew file mode 100644index 0000000000..93f8f6b426--- /dev/null+++ b/.ai/playbooks/forecast-consumption.md@@ -0,0 +1,113 @@+# Forecast Consumption++Last tested: 2026-10-06+Routes: `/x/settings/planning`, `/x/production/demand-forecasts`,+`/x/production/planning`, `/x/inventory/quantities`++## Prerequisites++- An item with open sales order lines in status `To Ship` or `To Ship and Invoice`,+ each with a promised date, and with no forecast of its own. MRP reads only these+ statuses (`openSalesOrderLines`). A `Confirmed` or `In Progress` order is not demand.+- In the Carbon Development company, SAW-001 (`item_5gqknUZj6kFeQn4fxTHz5a`) at+ Manufacturing Plant (`loc_U6GKN77Hz2XnBM8h9hSyFv`) fits: 3 lines of 30, promised+ 10/14, 11/4 and 11/25. Check the dates again before each run, because they move.+- Ask the user before you create the forecast. The test writes to the database.++## Steps++### 1. Settings card (read-only)++1. Open `/x/settings/planning`.+2. Expect the "Forecast Consumption" card with "Look back (weeks)" = 4 and+ "Look ahead (weeks)" = 1.++### 2. Create the forecast++1. Open `/x/production/demand-forecasts/new`.+2. Item (first combobox): click it, type the part number, click the option.+3. Location (second combobox): check that it shows the right location.+4. Fill the weeks. The hidden inputs are 0-based: "Week 2 (10/11)" is `week1`.+ - In the 2026-10-06 run: Week 2 = 20, Week 4 = 30, Week 9 = 10, Week 10 = 15.+5. Click another week input after each fill, so the value commits.+6. requestSubmit the form whose button includes "Create Forecast".++### 3. Baseline before MRP++1. Open `/x/production/planning?location=<loc>&search=<part>`.+2. Expect "Qty to Order" = sales orders + full forecast (165 in the 2026-10-06 run).+ A new forecast counts at full value until the next run.++### 4. Run MRP++1. Click "Recalculate" (top right of Material Planning). No dialog opens.+2. Poll `demandProjection.consumedQuantity` until it changes. It took under 10 s.++### 5. Verify++| Surface | 2026-10-06 expected and seen |+|---|---|+| `demandProjection.consumedQuantity` | 20, 30, 10, 0 |+| Material Planning "Qty to Order" | 105; actions Make 30 (10/11) + 60 (11/1) + 15 (12/6) |+| Demand forecast edit drawer | "20 consumed", "30 consumed", "10 consumed" under the inputs |+| Inventory quantities "Demand Forecast" | 105 (90 actual + 15 forecast remainder) |+| `/api/items/<id>/<loc>/forecast` → `demandForecast` | only the 12/6 row, quantity 15 |+| `demandProjection.updatedAt` | unchanged by the MRP run |++### 6. Clean up++1. On `/x/production/demand-forecasts`, open the row's "Actions" menu.+2. Click "Delete", then click "Delete" in the dialog.+3. Click "Recalculate" on Material Planning again.+4. Expect "Qty to Order" back at the sales-order total (90).++## Test: 0/0 window++1. On `/x/settings/planning`, set "Look back (weeks)" and "Look ahead (weeks)" to 0.+ The last 2 textboxes on the page are these fields. requestSubmit the form of+ `input[name=backwardPeriods]`.+2. Add a SAW-001 forecast: Week 2 = 20, Week 4 = 30, Week 9 = 10.+3. Click "Recalculate". On 2026-10-06: consumed 20, 0, 0, and Qty to Order 130.+4. Set 4 / 1 again and click "Recalculate". Expect consumed 20, 30, 10, and Qty+ to Order 90. This proves that the next run heals the result.+5. Delete the forecast.++## Test: late orders consume no forecast++1. Use a part with no other demand. On 2026-10-06: ANT-PATCH-01+ (`item_8ErCmrbQ6o6EPQabHXDKMt`).+2. Add a forecast of 25 in Week 1 (the current week).+3. Create a sales order at `/x/sales-order/new`. Customer: "Apex Space Research".+4. Add a line at `/x/sales-order/<id>/new`: the part, quantity 10, a promised date+ in the current week. Type the date into the day segment as `DDMMYYYY`.+5. Click "Confirm", then requestSubmit the "Confirm" button in the dialog. The+ confirm action runs MRP. Expect consumed 10 and Qty to Order 25.+6. Click "More options" → "Reopen". Open `/x/sales-order/<id>/<lineId>/details`.+ Set the day to a date before the current week. Save.+7. Confirm again. Expect consumed 0 and Qty to Order 35 (10 + 25).+8. Check that `demandActual.updatedAt` is later than the order's confirm time.+ Then you know that the run counted the order.+9. Clean up: Reopen, then "More options" → "Delete Sales Order". Delete the+ forecast. Click "Recalculate".++Leftovers after cleanup: deleting a sales order keeps its `opportunity` row and+the confirm PDFs in storage (`<companyId>/opportunity/<oppId>/`). MRP sets a+`demandActual` row to 0. It does not delete the row.++## Selector Notes++- `/x/production/demand-forecasts/delete/<item>/<loc>` is an action-only route.+ A GET shows raw JSON. Delete through the row menu.+- The "Recalculate" button has no confirmation. Find it with `snapshot -i`.+- `agent-browser screenshot <path>` needs an absolute path.++## Common Failures++- A `To Ship` or `To Ship and Invoice` order is locked. Reopen it before you edit a+ line.+- If the dev server rebuilds (for example after another session changes files),+ the browser can hang. Check `ps` for the `react-router dev` process. When its CPU+ use drops, open the page again.++- An item whose sales orders are `Confirmed` or `In Progress` shows them in the+ Inventory "On Sales Order" column, but MRP ignores them. Nothing is consumed.diff --git a/.ai/research/demand-forecast-consumption.md b/.ai/research/demand-forecast-consumption.mdnew file mode 100644index 0000000000..72dd8a92f1--- /dev/null+++ b/.ai/research/demand-forecast-consumption.md@@ -0,0 +1,167 @@+# Demand Forecast Consumption Research: Best Practices Survey++## Summary++Surveyed how SAP, Oracle (EBS + Fusion), NetSuite, Dynamics 365 SCM, Epicor Kinetic,+Infor (SyteLine + LN), Plex, Odoo, and MRPeasy reconcile demand forecasts with actual+sales orders / production orders in MRP, with emphasis on the zero-forecast-gap problem+(an order landing in a bucket with no forecast) and configuration surface. Two families+emerged. The **classical APICS model** (SAP, Oracle, Epicor, SyteLine, LN): net demand =+actual orders + *unconsumed forecast remainder*, computed by decrementing individual+forecast entries within a backward/forward consumption window — precise, but the window+arithmetic is the #1 practitioner footgun (gaps double-count, overlaps over-consume).+The **modern bucket-native model** (Odoo MPS, MRPeasy, D365's "dynamic period"): per-bucket+greater-of / interval-owned consumption with no day-window arithmetic — trades entry-level+precision for eliminating the whole gap/window bug class. Nearly every modern engine+computes consumption **regeneratively at plan-run time** (SAP is dynamic-at-read; Fusion,+D365, LN recompute per run); only Oracle EBS persists consume/unconsume state, at the cost+of a background process and reconciliation reports. Universally, **only demand consumes+forecast** — production orders are supply and are netted by the planning balance, never by+forecast consumption (SAP strategy 70 / LN dependent-demand consumption being the deliberate+component-level exception).++## Competitors Surveyed++- **SAP S/4HANA / ECC PP** — the reference model: planning strategies, consumption modes 1–5, PIR reduction+- **Oracle EBS / Fusion Cloud Supply Planning** — richest windowing rules (workdays, bucket eligibility, overconsumption records)+- **Oracle NetSuite** — Oracle-derived but simplified; per item-location windows+- **Microsoft Dynamics 365 SCM** — reduction keys + the "dynamic period" alternative to windows+- **Epicor Kinetic** — mid-market discrete; days-before/days-after windows and their documented failure modes+- **Infor SyteLine (CSI)** — the most explicit backward/forward walk (`Look Behind`/`Look Ahead`); original vs outstanding quantity+- **Infor LN** — period-sequential consumption with backward/forward day parameters; "Nonconsumed Forecast" field+- **Plex** — negative result: no public consumption engine; demand arrives as EDI releases; real planning delegated to a separate product+- **Odoo MPS / MRPeasy** — the modern simplified bucket-native take++## Key Consensus Patterns++### 1. Net demand = actuals + unconsumed forecast remainder (never a blind sum)++- **SAP** (strategy 40): sales orders consume PIRs; remaining PIR + full sales orders drive MRP. Worked example: PIR 100, SO 90 → demand 90 (SO) + 10 (PIR) = 100. When actuals exceed forecast, excess stands as net additional demand ("the system automatically adjusts the master plan").+- **Oracle**: identical principle; forecast entries carry original vs current quantity; sales orders remain full demand, forecast floors at 0.+- **SyteLine**: `Original Quantity` vs `Outstanding Requirement`; the outstanding remainder is what plans.+- **Rationale**: reproduces `max(forecast, actual)` per bucket in the same-bucket case, while remaining well-defined when consumption crosses buckets. All three user cases fall out: 10F/10SO→10, 10F/5SO→10, 10F/12SO→12.++### 2. Consumption is regenerative, not stored state (modern consensus)++- **SAP**: allocation is dynamic — "nothing is changed on the database"; MD04 derives it at read time from sales requirements (VBBE) vs PIR tables. Order changes/cancellations self-heal on next read. (Permanent PIR *reduction* is a separate mechanism, at goods issue.)+- **Oracle Fusion**: consumption computed inside every plan run from the open-SO snapshot; a cancelled/shipped order simply isn't in the next snapshot.+- **D365**: reduction recomputed during each master-planning (regenerative) run; no consumed-qty on the forecast line.+- **Oracle EBS** is the counterexample — persisted consume/deconsume via the Planning Manager background process — and carries exactly the complexity you'd expect: deconsumption rules per change type, RMA/new-forecast edge cases, rebuild reports.+- **Rationale**: recomputing from the live order set is what makes forecasts "self-heal" with zero communication between sales and production — nothing to un-consume, no drift, no repair jobs.++### 3. Backward first, then forward (when windows exist)++- **SAP** mode 2 (backward then forward) is the conventional choice; search is nearest-date-first outward, in **workdays**.+- **Oracle** EBS/Fusion: exact-date match → backward day-by-day → forward.+- **SyteLine**: exact due-date match → backward (Look Behind) → forward (Look Ahead), in working days.+- **D365 Planning Optimization** (reduction-key overflow): previous period first, then next.+- **Rationale**: an order arriving "late" relative to its bucket was almost certainly part of the just-passed forecast; forward consumption is the fallback, and oversizing it "carries forecast demand deep into the period even when the likelihood of orders is diminishing" (Infor's own warning).++### 4. Window sized to the bucket — or replaced by the bucket++- **Oracle** weekly-bucket rule: once the window *touches* a week, the **whole week's** forecast is eligible — so "backward ≈ one work-week" suffices for weekly buckets; Fusion encodes the recommendation as a checkbox, "Consume by forecast bucket".+- **D365 "Transactions – dynamic period"**: each forecast entry owns the interval from its date until the next entry's date — zero-forecast gaps *between entries* cannot exist by construction; only orders before the first entry consume nothing. Excess is dropped, never forwarded.+- **Epicor/SyteLine** leave window sizing to the customer, and the epiusers threads document the result: monthly forecast + too-narrow window = orders at month-end "doubled up on expected demand," with no clean in-product fix — the exact bug this feature exists to solve.+- **Rationale**: day-granular windows on bucketed forecasts is complexity without benefit; bucket-granular consumption (same bucket, then N buckets back, then M forward) is where both Oracle and D365 landed.++### 5. Only demand consumes forecast; production orders are supply++- **SAP** strategy 40: production orders/stock never consume VSF PIRs — they net in the requirements calculation. (Strategy 70/dependent-requirements consumption is the deliberate assembly-level exception.)+- **Oracle**: WIP jobs trigger *production relief of the MPS* — a supply-side dedup, explicitly not forecast consumption.+- **Epicor**: "Forecast will only be consumed by Sales Orders, and nothing else."+- **D365** offers "Reduce forecast by: All transactions" (any issue transaction, incl. production consumption of BOM lines) as the opt-in broader mode.+- **Rationale**: a make-to-stock job *covers* the forecast (supply vs demand netting); making it also consume the forecast double-relieves. Component-level actual demand (job materials) consuming component-level forecast is the legitimate variant (LN dependent demand, SAP 70).++### 6. Past-due forecast must expire++- **SAP**: no automatic cleanup — stale PIRs keep driving supply until MD74/75/76 reorganization jobs zero them; a documented operational burden.+- **D365**: the opposite pole — all forecast dated on/before today is ignored wholesale by the run.+- **Epicor**: unconsumed past forecast generates backdated PO suggestions until manually deactivated (documented complaint).+- **NetSuite/Oracle**: demand time fence — inside the fence only actual orders count.+- **Rationale**: a forecast bucket in the past that didn't materialize is exactly the "sales didn't tell production" staleness this feature is meant to absorb; D365's drop-the-past rule is the self-healing default.++## Answers to Research Questions++1. **Canonical algorithm; run-time vs stored state** — Actuals + unconsumed forecast remainder per bucket (== `max` in the same-bucket case), computed regeneratively each plan run / at read time (SAP, Fusion, D365, LN). Stored consumed-state (EBS) is the legacy exception and brings deconsumption machinery with it.+2. **Window mechanics** — Exact bucket/date first; backward before forward everywhere except SAP mode 3/4 opt-ins; units are workdays (SAP, Oracle, SyteLine) or whole periods (D365 reduction keys, SAP mode 5, Oracle Fusion buckets); excess beyond the window's forecast stands as additional net demand (never forced onto out-of-window forecast; D365 drops rather than forwards overflow across entries).+3. **Configuration surface** — SAP: material master MRP 3 (per item) with MRP-group fallback (per plant). Oracle EBS: forecast set; Fusion: plan options. NetSuite: item-location. Epicor: company default + part/site override. SyteLine: site Planning Parameters + product-code override. D365: master plan (method) + coverage group (reduction key, what consumes). Standard names: *consumption mode*, *backward/forward consumption period* (SAP); *backward/forward consumption days* (Oracle/NetSuite); *reduction principle/key* (D365); *forecast window days before/after* (Epicor); *look behind/look ahead* (SyteLine). "Forecast consumption" is the industry term to adopt.+4. **Do jobs consume forecast?** — No, in every default configuration (jobs are supply; supply nets in the balance). Component-level dependent demand consuming component forecast is an explicit opt-in (LN, SAP 70, D365 "All transactions"). Shipped demand: handled by a *separate* relief/exclusion mechanism (SAP reduction at goods issue; D365 excludes invoiced/delivered by default in Planning Optimization — a known double-count gap they later patched; regenerative engines simply drop closed orders from the snapshot).+5. **Bucket granularity & the past** — Dated entries (SAP/Oracle/D365/Epicor) vs fixed buckets (Odoo/MRPeasy; Carbon's model). Oracle's whole-bucket-eligibility rule bridges the two. Past unconsumed forecast: dropped wholesale (D365), fenced (Oracle/NetSuite DTF), or a manual cleanup burden (SAP MD74, Epicor) — the burden is the anti-pattern.+6. **Terminology** — "Forecast consumption" (consume/consumed-by), "consumption window" (backward/forward), "net forecast" / "unconsumed forecast remainder". Avoid "reduction" (SAP/D365 use it for the *permanent* burn-down at goods movement, a different mechanism).++## Competitor-Specific Details++### SAP+Consumption modes: 1 backward, 2 backward+forward, 3 forward, 4 forward+backward, 5 period-based (S/4 only — consume only within the PIR's own planning period ± N periods). Periods in workdays, up to 999; **no periods maintained → only same-day PIRs consume** (classic gotcha). Fallback default mode 1 / 999 days via MRP group. Allocation is nearest-date-first, first-come-first-served across orders. Consumption (dynamic, at order entry) vs reduction (persisted, at goods issue — delivery GI for strategies 10/40, GR for 11) are distinct mechanisms.++### Oracle+EBS: backward/forward consumption days on the forecast set, workdays only; overconsumption creates an informational negative forecast entry at set level; outlier update percent caps one order's bite of any entry; demand classes fence who may consume what. Weekly/periodic bucket rule: window touching a bucket ⇒ whole bucket eligible; mixed granularity consumes daily entries → weekly → periodic. Fusion: per-plan options; "Consume by forecast bucket" checkbox; recomputed every run.++### Dynamics 365+Four methods on the plan: None / Percent–reduction key (time-based decay, orders irrelevant) / Transactions–reduction key (orders consume within calendar buckets from the key; Planning Optimization spills backward-then-forward, classic engine doesn't) / **Transactions–dynamic period** (each forecast entry owns [its date, next entry's date); no windows, no gaps possible; excess dropped). What consumes: coverage group "Reduce forecast by" = Orders | All transactions; intercompany opt-in. All forecast before today is excluded. Recomputed per regenerative run.++### Epicor Kinetic+Days Before/Days After around each forecast entry's date; company default + part/site override. No one-to-one tracking (one lingering order can eat multiple entries). Gap orders are additive demand — documented, unsolved, with workarounds being pure date arithmetic. Only sales orders consume; a real job against forecast double-counts until the forecast is manually deactivated. "MPS wins" over forecast when both exist.++### Infor SyteLine / LN+SyteLine: Forecast Look Behind/Look Ahead in working days, backward first; original vs outstanding qty; site default + product-code override; changing the window re-runs consumption for all items (documented as slow). Item parameter "Use CO or Forecast: Both" gates netting. LN: period-sequential consumption bounded by backward/forward day params; "Nonconsumed Forecast" field; optional dependent-demand consumption; ATP updates consume same-period only.++### Odoo MPS / MRPeasy (modern bucket-native)+Odoo: weekly/monthly grid; forecast drives replenishment; actuals displayed alongside with red "Forecast Too Low" flags; human raises the forecast (Odoo 19 adds one-click fill-from-actuals ± factor). No automatic netting. MRPeasy: cleanest automatic rule found — `GREATER OF(Forecast, Firm orders)` per period for future periods, **current period uses firm orders only**; same greater-of drives BOM-exploded dependent demand. No windows, no consumption bookkeeping.++### Plex (negative result)+No public forecast-consumption engine; core MRP sums firm releases/orders/forecasts from EDI release schedules; statistical planning lives in the separate DemandCaster-based Supply Chain Planning product. Do not cite Plex as precedent.++## Recommended Approach for Carbon++Carbon's forecast is already bucket-native (`demandProjection` keyed on weekly `periodId`),+which puts it in the Odoo/MRPeasy/D365-dynamic-period family — the day-window arithmetic+that generates Epicor/SyteLine's documented failure modes has no reason to exist here.++1. **Consume regeneratively inside `runMrp`, persist nothing on the forecast** (SAP/Fusion/D365 pattern). Every run: load open actual demand + projections, run consumption, use the remainder. Self-healing falls out — cancelled orders, changed dates, and edited forecasts all re-net on the next run with no deconsumption machinery. This also matches Carbon's existing wipe-and-rewrite MRP outputs.+2. **Per-bucket remainder algorithm** (APICS net): per (item, location), walk actual demand chronologically; each actual consumes forecast in its own bucket first, then backward up to N buckets, then forward up to M buckets (Oracle/SyteLine search order at bucket granularity — Oracle's own docs show whole-bucket eligibility is the effective semantics anyway). Net demand per bucket = actuals + unconsumed remainder. Reproduces the user's three cases and fixes the gap case.+3. **Window in weeks, not days**, with a small company-level default (backward ≈ 4 weeks / forward ≈ 1, or D365-style "back to the previous forecast entry") — flat config, no matrices; per-item override only if demanded later. Every vendor that exposed day-granular windows produced a support-forum genre of window-sizing bugs.+4. **Only demand consumes**: sales order lines and job-material lines consume projections on their own item. Make-to-stock jobs stay pure supply (already netted by the running balance — verified in the Phase-0 audit). Do not add D365's "All transactions" mode initially.+5. **Drop past forecast from the demand set** (D365 rule): unconsumed forecast in past buckets must not drive supply — this is the second half of "self-healing" and avoids SAP's MD74 cleanup-job burden.+6. **Compute the net once, read it everywhere.** The Phase-0 audit found four read sites re-implementing the demand union; consumption must be computed in one place (the MRP run) and persisted as output rows the RPCs/UI read, or the grid and the engine will disagree.++## Sources++### SAP+- https://help.freedsap.com/ENHELPhtml/PPMPDEM/ConsumptionStrategiesandLogic.html+- https://help.freedsap.com/ENHELPhtml/PPMPDEM/PlanningwithFinalAssembly41.html+- https://help.freedsap.com/ENHELPhtml/PPMPDEM/SampleScenarioStrategy41.html+- https://help.sap.com/docs/SUPPORT_CONTENT/mrp/3138698453.html (PIR reorganization)+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/9905622a5c1f49ba84e9076fc83a9c2c/a628a484ef6e4b0fbef4fce7eabc6dd6.html+- https://blogs.sap.com/2017/05/04/s4-hana-new-consumption-mode-for-planned-independent-requirements/ (mode 5, KBA 2939973)+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/pir-consumption-amp-reduction-mechanism/ba-p/13633872+- https://blog.sap-press.com/4-strategies-for-make-to-stock-production-with-sap-s4hana+- https://userapps.support.sap.com/sap/support/knowledge/en/3704214++### Oracle / NetSuite+- https://docs.oracle.com/cd/E26401_01/doc.122/e48795/T478564T483393.htm (EBS forecast consumption)+- https://docs.oracle.com/cd/A60725_05/html/comnls/us/mrp/timefo01.htm (weekly buckets)+- https://docs.oracle.com/cd/A60725_05/html/comnls/us/mrp/consum04.htm (windows + overconsumption)+- https://docs.oracle.com/cd/E26401_01/doc.122/e48795/T478564T478750.htm (shipment/production relief)+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/26b/fausp/forecast-consumption.html (Fusion)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1495718329.html (NetSuite examples)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_159172238892.html (NetSuite item-location params)+- https://docs.oracle.com/en/applications/jd-edwards/supply-chain-manufacturing/9.2/eoarp/understanding-forecast-consumption.html++### Dynamics 365+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/planning-optimization/demand-forecast+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/reduction-keys+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/deprecated-master-plans+- https://learn.microsoft.com/en-us/previous-versions/dynamicsax-2012/reduction-keys-form++### Epicor / Infor / Plex / Odoo / MRPeasy+- https://www.epiusers.help/t/forecast-window-by-part/111390+- https://www.epiusers.help/t/forecast-consumption/131684+- https://www.epiusers.help/t/how-to-consume-forecast-qty-now-real-job-exists/123948+- https://www.epiusers.help/t/forecast-window-within-a-calendar-month-rather-than-a-window-of-days-before-and-days-after/76733+- https://docs.infor.com/csi/9.01.x/en-us/csbiolh/lsm1454144400143.html (SyteLine Look Ahead/Behind)+- https://docs.infor.com/ln/2023.x/en-us/lnolh/cpordplanug/cpom000331.html (LN consumption)+- https://plex.rockwellautomation.com/en-us/blog/leveraging-demand-and-supply-planning-unlock-value-mrp.html+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/manufacturing/workflows/use_mps.html+- https://www.mrpeasy.com/resources/user-manual/settings/system/enterprise-functions/master-production-schedule-mps/+- https://frepple.com/blog/forecast-consumption/diff --git a/.ai/research/mrp-planning-actions.md b/.ai/research/mrp-planning-actions.mdnew file mode 100644index 0000000000..6df94e8c73--- /dev/null+++ b/.ai/research/mrp-planning-actions.md@@ -0,0 +1,443 @@+# MRP Planning Actions Research: Best Practices Survey++## Summary++This surveys how best-in-class manufacturing ERPs model MRP **action messages** /+**planning exceptions** — the full set of planning actions beyond just "create an+order" — and how those actions are routed to and worked by buyers/planners. The+motivation: Carbon's MRP today emits exactly one suggestion, "Order" (a computed,+non-persisted `quantityToOrder`), and cannot tell a planner to expedite, defer, or+cancel existing supply.++The consensus across SAP, Microsoft Dynamics 365 (SCM and Business Central),+Oracle NetSuite, Epicor Kinetic, and Infor (SyteLine/LN) is remarkably tight.+Every one of them separates **two concept classes**: (1) *actionable messages on+orders* — create a new order, pull-in/expedite, push-out/defer, cancel, and+(in some) change-quantity; and (2) *advisory exceptions/warnings* — below safety+stock, negative on-hand, cannot-meet-requested-date, master-data broken. All of+them gate reschedule noise behind a **tolerance window** so trivial date shifts+don't spam the worklist, and all of them **partition the worklist by an ownership+code** (SAP "MRP controller" for planning + "purchasing group" for buying; Epicor+"Buyer ID"; BC "planner"; LN "planner"). The pivotal enabling concept everywhere+is **firming**: a suggestion an engine freely rewrites only ever needs "create";+the moment an order can be committed/firmed, you need message-to-a-human actions+because the engine may no longer silently move it.++## Competitors Surveyed++- **SAP S/4HANA (and ECC)** — the enterprise reference; its 8-group numbered+ exception-message catalog (esp. Group 7: reschedule-in 10 / reschedule-out 15 /+ cancel 20 / plan-process 30) is the model every other ERP echoes.+- **Microsoft Dynamics 365 SCM (F&O)** — cleanest *directional* action taxonomy+ (Advance / Postpone / Increase / Decrease / Derived) plus the "Delays/futures"+ cannot-meet-date exception as a first-class output.+- **Microsoft Dynamics 365 Business Central** — cleanest *enum* to emulate:+ Planning Worksheet action messages New / Change Qty. / Reschedule / Resched. &+ Chg. Qty. / Cancel, orthogonal on (date, quantity) axes.+- **Oracle NetSuite Supply Planning** — Reschedule In / Reschedule Out / Cancel ++ numeric planning-exception codes; bulk approve/reject from a Planning Workbench.+- **Epicor Kinetic** — New PO Suggestions vs Change PO Suggestions (Expedite /+ Postpone / Cancel / Qty change), Buyer-ID-scoped worklists, reschedule-in/out+ delta tolerances.+- **Infor SyteLine (CSI) & LN** — planned orders + exception messages+ (Reschedule In / Reschedule Out / Cancel Order), firm/confirm to release,+ per-planner exception configuration.++## Key Consensus Patterns++### 1. Two concept classes: actionable messages vs. advisory exceptions++- **SAP**: Group 7 messages (10/15/20/30) are *actions on orders*; Groups 4/5/6/8+ are *advisory* (excess stock, below safety stock, no BOM, planning terminated).+- **Dynamics 365 SCM**: "Actions" (Advance/Postpone/Increase/Decrease) modify an+ existing order; "Delays/futures" is a separate cannot-meet-date exception.+- **Business Central**: the `Action Message` enum is the actionable set; the+ separate `Warning` field carries Emergency / Exception / Attention severities.+- **NetSuite**: order recommendations (Reschedule In/Out, Cancel, Create) are+ distinct from coded "Planning Action Messages" (100 below-zero, 110 below safety+ stock, 130 late PO, 140 late WO).+- **Infor LN**: order-planning messages (Reschedule In/Out, Cancel Order) sit in a+ broader exception taxonomy alongside quantity/lead-time/safety-time exceptions.+- **Rationale**: an actionable message maps 1:1 to a document edit a buyer/planner+ performs; an advisory flag needs human judgement and may not resolve to a single+ order edit. Modeling them separately (but linked) keeps the worklist crisp.++### 2. The actionable message taxonomy — six primitives++Every product implements the same core set (names vary):++| Primitive | SAP | D365 SCM | Business Central | NetSuite | Epicor | Infor LN |+|---|---|---|---|---|---|---|+| New buy order | new planned order / PR | planned purchase order | **New** | create/release | **New PO Suggestion** | Confirm planned PRP order |+| New make order | new planned order | planned production order | **New** | create/release | **New Job** (unfirm) | Confirm planned prod order |+| Pull in (earlier) | **10 reschedule in** | **Advance** | **Reschedule** | **Reschedule In** | **Expedite** | **Reschedule In** |+| Push out (later) | **15 reschedule out** | **Postpone** | **Reschedule** | **Reschedule Out** | **Postpone** | **Reschedule Out** |+| Cancel | **20 cancel process** | (Decrease→0) | **Cancel** | **Cancel** | **Cancel** | **Cancel Order** |+| Change quantity | (42 changed / 25-26 excess) | **Increase / Decrease** | **Change Qty.** (+ **Resched. & Chg. Qty.**) | via reschedule/qty | Change PO Suggestion (qty) | Qty < Min / > Max / <> Increment |++- **Directional vs. combined**: BC combines date+qty into `Resched. & Chg. Qty.`+ and leaves reschedule direction implicit; D365 SCM and SAP/Epicor/LN bake+ **direction** into the type (Advance/Postpone, expedite/de-expedite,+ reschedule-in/out). Direction-in-the-type is more legible to a buyer.+- **Cancel vs. Decrease-to-zero**: most products have an explicit **Cancel**;+ D365 SCM notably folds it into Decrease. Explicit Cancel reads better.+- **Rationale**: these six span the two axes a planner can change on any supply+ order — its **date** (earlier/later) and its **quantity** (more/less/none) —+ plus the create/cancel endpoints.++### 3. A reschedule proposal is a message + a proposed date, not a new order++- **SAP**: a reschedule (10/15) is *not* a new element — it's an exception message+ hung on the existing firmed receipt, plus a **rescheduling date** (the date MRP+ suggests moving it to), shown in a dedicated MD04/MD05 column.+- **NetSuite / Epicor / LN**: same — the recommendation references the existing+ order and carries a new suggested date/qty.+- **Rationale**: the buyer needs "move *this PO line* to *this date*", so the+ message must reference the concrete existing document + the target date/qty,+ distinct from a freestanding new-order proposal.++### 4. Tolerance windows gate reschedule noise++- **SAP**: the **rescheduling check** only proposes a reschedule when the mismatch+ exceeds configured forward/backward **tolerance values (in days)** within a+ **rescheduling horizon**.+- **D365 SCM**: `Advance margin` / `Postpone margin` cap and gate reschedules;+ action calculation is off unless within the **action message time fence**.+- **Business Central**: **dampener period / dampener quantity** suppress trivial+ messages.+- **Epicor**: separate **reschedule-in delta** and **reschedule-out delta** (days).+- **Infor LN**: per-planner exception-type configuration decides which fire.+- **Rationale**: without a tolerance, every 1-day drift generates a message and the+ worklist becomes noise the planner learns to ignore. This is a hard requirement,+ not a nice-to-have.++### 5. Firming is the concept that makes change-actions necessary++- Universal: an MRP engine freely creates, moves, and deletes its own *planned*+ proposals every run. Once a proposal is **firmed** (SAP asterisk / manual+ edit / planning-time-fence) or **converted** to a real PO/job, MRP must no+ longer silently touch it — so instead it raises a **reschedule/cancel message+ to a human**. SAP: 10/15/20 fire on *firmed* receipts; 30 fires on *planned*+ ones MRP can still auto-reschedule.+- **Conversion / "Carry Out" / "Firm" / "Confirm"**: the accept-and-convert step+ turning a proposal into a real document. SAP MD14/MD15 (planned→PR), CO40/CO41+ (planned→production); BC "Carry Out Action Message" after ticking "Accept+ Action Message"; Epicor "Buy"/"Firm"; LN/SyteLine "Confirm"/"Firm".+- **Rationale for Carbon**: Carbon already creates **real** POs (status `Planned`)+ and jobs directly from planning — there is no persisted "planned order" the+ engine owns. That means Carbon's change-actions (expedite/defer/cancel) in+ necessarily operate on **already-real** purchase orders and jobs, which is+ exactly SAP's "firmed receipt" case. Carbon effectively has no unfirmed tier,+ so *every* existing-supply action is a message-to-a-human by construction.++### 6. Owner-scoped, filterable, bulk-actionable worklists++- **SAP**: MD06 (snapshot) / MD07 (live) collective worklists filtered by **MRP+ controller** (planning) and **purchasing group** (buying); a **processing+ indicator** lets a planner tick off reviewed materials.+- **D365 SCM**: Master planning workspace + planned-orders lists filtered by+ vendor / coverage group / **buyer group**; group-by-vendor+buyer-group on firm.+- **Business Central**: **Planning Worksheet** (planners) vs **Requisition+ Worksheet** (buyers); Carry-Out can copy PO proposals into the Requisition+ Worksheet — the primary planner-vs-buyer routing mechanism.+- **NetSuite**: Supply Planning Workbench views grouped by subsidiary/location,+ header-checkbox **bulk approve/reject** ("Perform Selected Actions").+- **Epicor**: **Buyer Workbench** (POs) / **Planning Workbench** (jobs); Buyer ID+ resolved Part-Site → Part-Class → system default partitions the worklist.+- **Infor**: per-planner exception sessions; planner code + buyer on the item.+- **Rationale**: exception management only scales when each buyer/planner pulls+ "my materials" and can act in bulk; a single global list doesn't get worked.++## Answers to Research Questions++1. **Full catalog of action messages (beyond "Order")?** — Six primitives+ (§2): New buy, New make, Expedite/pull-in, Defer/push-out, Cancel, Change+ quantity — plus advisory exceptions (below safety stock, excess/over-supply,+ cannot-meet-date, late order, master-data broken). SAP's canonical action set+ is 10/15/20/30; BC's is New / Change Qty. / Reschedule / Resched.&Chg.Qty. /+ Cancel; D365's directional set is Advance / Postpone / Increase / Decrease.++2. **New order vs. change to existing order?** — Distinct outputs everywhere (§3).+ A new proposal is a freestanding planned order/requisition with its own dates; a+ change is a message referencing an existing (firmed/real) order + a proposed new+ date/quantity. SAP's "rescheduling date" is a first-class column.++3. **How planners work them?** — Owner-scoped, filterable worklists with+ accept/convert and bulk actions (§6): SAP MD06/MD07, BC Planning/Requisition+ Worksheet + Carry Out, NetSuite Workbench bulk approve, Epicor Buyer/Planning+ Workbench.++4. **Assignment to buyers/planners?** — A per-item/portfolio ownership code (§6):+ SAP MRP controller (mandatory MRP-1 material-master field) + purchasing group;+ Epicor Buyer ID (Part-Site → Part-Class → default); BC planner + worksheet+ split; Infor planner code + buyer. **Carbon has no buyer/planner field today** —+ only a generic document `assignee` (present on `purchaseOrder`, not populated by+ the planning path). This is the second gap the rewrite fills.++5. **Firming / conversion?** — §5. Firming protects a proposal from auto-change;+ conversion turns it into a real document. **Carbon skips the unfirmed tier** —+ it creates real `Planned`-status POs and real jobs directly — so its+ change-actions inherently target real documents (SAP's firmed-receipt case).++6. **Tolerance to suppress noise?** — Yes, universal (§4): SAP rescheduling-check+ tolerance days + horizon, D365 advance/postpone margins, BC dampeners, Epicor+ reschedule-in/out deltas. **Must-have** for Carbon's expedite/defer messages.++## Competitor-Specific Details++### SAP S/4HANA / ECC+8 exception groups; priority-1 messages on the results screen, priority-2 on+drill-in. Group 7 = actions: **10 reschedule in** (firmed receipt later than need),+**15 reschedule out** (firmed receipt earlier than need), **20 cancel process**+(firmed receipt with no matching requirement), **30 plan process** (planned receipt,+demand inside lead time). Priority order 10 → 20 → 15. Rescheduling date computed by+the rescheduling check within tolerance/horizon; can occasionally flag msg 10 with+no computable date. Worklists MD06 (snapshot, processing indicator) / MD07 (live) /+MD04 (single-material live cockpit). **MRP controller** = mandatory 3-char MRP-1+material-master field; **purchasing group** = analogous buy-side field. Firming via+manual edit / planning time fence; conversion MD14/MD15 (→PR, auto-firmed),+CO40/CO41 (→production).++### Microsoft Dynamics 365 SCM (F&O)+Master planning nets to **planned orders** (proposals). **Actions**:+Advance / Postpone / Increase / Decrease / **Derived** (propagate down to+components), gated by the **action message time fence** and advance/postpone+margins. **No explicit Cancel** (Decrease→0) and **no Create** action (a planned+order *is* the create). **Delays/futures**: a **delayed (futures) date** + delay+days when earliest fulfillment is later than requested — a first-class+cannot-meet-date exception, governed by the **futures time fence**; only propagates+to components once the top-level order is firmed. **Firming**: manual, auto+(firming time fence), or query-based batch; firmed PO is set to `Approved`.++### Microsoft Dynamics 365 Business Central+**Planning Worksheet** action-message enum: **New**, **Change Qty.**,+**Reschedule**, **Resched. & Chg. Qty.**, **Cancel** (spans purchase / production /+assembly / transfer). Separate **Warning** field: Emergency / Exception / Attention.+**Dampener period/quantity** suppress trivial messages. Planner ticks **Accept+Action Message** then runs **Carry Out Action Message** (choose planned vs firm+planned production orders; create POs/assembly/transfer). **Planning Flexibility**+(Unlimited vs None) controls whether planning may touch a supply line.+**Planning Worksheet (planners) vs Requisition Worksheet (buyers)** — Carry-Out can+copy PO/transfer proposals into the Requisition Worksheet when separate teams handle+purchasing vs production. Cleanest enum to emulate.++### Oracle NetSuite Supply Planning+Supply plan lists suggested POs/WOs/transfers as **planned orders**. Order+recommendations: **Reschedule In**, **Reschedule Out**, **Cancel**, plus+create/release. Coded **Planning Action Messages** (100 QtyOnHand<0, 110 below+safety stock, 120 above safety stock, 130 late PO, 140 late WO) on a Planning+Messages subtab, reusable in saved searches. **Supply Planning Workbench** views+grouped by subsidiary/location with header-checkbox **bulk approve/reject**+(Perform Selected Actions). 2025.2 added Reschedule In Firm / Reschedule Out Firm /+Cancel Firm views (recommendations now cover firm orders too).++### Epicor Kinetic+Process MRP → **manufacturing suggestions** (Planning Workbench, unfirm jobs) and+**purchasing suggestions** (Buyer Workbench). **New PO Suggestions** vs **Change PO+Suggestions** (Expedite / Postpone / Cancel / Qty change). **Reschedule-in delta**+and **reschedule-out delta** (days) gate expedite/postpone. Buyer clicks **Buy** to+convert (optionally via requisition); planner **firms** unfirm jobs. **Buyer ID**+resolution: Part-Site → Part-Class → system default; a buyer sees only their+authorized buyers' suggestions/POs.++### Infor SyteLine (CSI) & LN+SyteLine: planned orders on the Material Planner Workbench / Planning Detail; **firm**+a planned order → job / PO / PO requisition / transfer; item carries **planner code**++ **buyer**. LN: **planned orders** with Order Status "To be released" / "Not to be+released", turned real via **Confirm Planned Order**; exception messages+**Reschedule In** / **Reschedule Out** / **Cancel Order** plus quantity/lead-time/+safety-time exceptions; configured and worked **per planner** (Exception Message+Types by Planner / Exception Messages by Planner).++## Carbon Current-State (grounding)++**MRP is no longer an edge function** — the old Deno `mrp` function was deleted.+MRP now runs in-process in Node via **`runMrp`** exported from `@carbon/planning`+(`packages/planning/src/mrp/mrp.ts`, ~1149 lines). The pure BOM-explosion core+(`explodeBom`) still lives in `packages/database/supabase/functions/lib/mrp-engine.ts`+and is reached via the `@carbon/database/mrp-engine` barrel.+**Note: `.claude/rules/supersession-system.md` still references the old+`functions/mrp/**` path — it is stale for MRP's location.**++- **The engine emits no action messages.** `runMrp` writes only forecast/actual+ buckets: `demandForecast` (`forecastMethod='mrp'`), `demandForecastSource`+ (lineage), `demandActual`, `supplyActual`. It **deletes but never writes**+ `supplyForecast` (that's written by the user-driven `planning.update` routes).+- **The single "Order" suggestion is computed downstream and never persisted.**+ SQL RPCs `get_purchasing_planning` / `get_production_planning` ++ `calculate_quantity_to_order` (branching on `reorderingPolicy`) compute an+ ephemeral `quantityToOrder`, recomputed on every page load. A client-side mirror+ `calculateOrders` (`ItemReorderPolicy.tsx`) additionally emits `policyName`,+ `isASAP`, and `triggerValues` per suggestion — the only "why" metadata, thrown+ away after order creation.+- **Time horizon**: engine forecasts 72 weeks (`WEEKS_TO_FORECAST = 18*4`), weekly+ buckets only; purchasing planning route shows 48 weeks. Today =+ `datetime.today(companyTimeZone)`.+- **Consuming action supports only `action === "order"`** — `planning.update.tsx`+ (purchasing + production) explicitly rejects anything else. Purchasing groups+ planned orders by `supplierId::periodId`, finds-or-creates one PO per group+ (status `Planned`), merges lines, upserts `supplyForecast`. Production inserts+ jobs + methods, upserts `supplyForecast`, `recalculateJobRequirements()`.+- **No persisted suggestion / action-message table** exists — no+ `purchaseSuggestion` / `materialRequirement` / `actionMessage` / `planningSuggestion`.+- **Trigger**: Inngest (not Trigger.dev/DB-cron). Scheduled every 3h+ (`packages/jobs/src/inngest/functions/scheduled/mrp.ts`, `cron: "0 */3 * * *"`),+ per-company `runMrp(..., userId: "system")`, Cloud skips Canceled subscriptions.+ Manual via `apps/erp/app/routes/api+/mrp.ts` (POST, `update: "inventory"`) →+ `runMRP` wrapper in `production.service.ts`.+- **No buyer/planner concept.** Generic `assignee` FK exists on `purchaseOrder`+ (and part/customer/supplier), but the planning path never sets it; planned POs+ carry status/supplier/currency/createdBy only. Supplier defaulting comes from+ `itemReplenishment.preferredSupplierId` + `supplierPart`.+- **Relevant tables/enums**:+ - `itemReplenishment` (per item): `preferredSupplierId`, `purchasingLeadTime`,+ `purchasingUnitOfMeasureCode`, `conversionFactor`, `lotSize`, `manufacturingPolicy`.+ - `itemPlanning` (per item+location, unique `(itemId, locationId)`):+ `reorderingPolicy`, `safetyStockQuantity`, `reorderPoint`, `reorderQuantity`,+ `reorderMaximumInventory`, `minimumOrderQuantity`, `maximumOrderQuantity`,+ `orderMultiple`, `demandAccumulationPeriod`, `demandReschedulingPeriod`,+ `critical`.+ - `itemReplenishmentSystem` = `'Buy' | 'Make' | 'Buy and Make'`.+ - `itemReorderingPolicy` = `'Manual Reorder' | 'Demand-Based Reorder' |+ 'Fixed Reorder Quantity' | 'Maximum Quantity'`.+ - Planning tables `period`, `demandForecast`, `demandActual`, `supplyForecast`,+ `supplyActual`, `demandForecastSource`, `demandProjection`.++## Recommended Approach for Carbon++Modeled on **SAP's exception-message split + Business Central's clean enum ++Epicor's Buyer-scoped worklist**, adapted to Carbon's reality that it has **no+unfirmed planned-order tier** (it creates real `Planned` POs and jobs directly).++1. **Persist a planning action-message / suggestion table** keyed by+ `(itemId, locationId, periodId)` (or per suggestion), with an **action-type+ enum** and the proposal payload. This is the central new artifact — Carbon's+ suggestion is ephemeral today. `runMrp` already has net requirement, projected+ balance, supply timing, and lineage in Phase 5–7, so it can write these rows in+ the existing Phase-7 atomic transaction. Reuse the existing `policyName` /+ `reason` / `triggerValues` shape (already on `plannedOrderValidator`) as the+ persisted "why".++2. **Adopt a directional action-type enum** (direction-in-the-type reads best for a+ buyer): follow SAP/D365/Epicor rather than BC's implicit-direction enum.+ Proposed set: **Order** (new buy) · **Make** (new job) · **Expedite** (pull an+ existing PO/job in) · **Defer** (push an existing PO/job out) · **Cancel** (an+ existing PO/job no longer needed) · optionally **Increase Qty** / **Decrease+ Qty**. Keep a separate **advisory-exception** channel (below safety stock,+ excess/over-supply, cannot-meet-date/past-due, master-data broken) — do **not**+ overload the action enum with warnings. (Terminology to confirm with domain+ glossary — see Open Questions.)++3. **Change-actions target real documents.** Because Carbon has no unfirmed tier,+ Expedite/Defer/Cancel reference an existing `purchaseOrderLine` / job (SAP's+ firmed-receipt case). The message carries the **proposed new date** (and/or qty)+ — a first-class field (SAP's "rescheduling date"). Acting on it edits/cancels+ that real document.++4. **Gate reschedule messages behind a tolerance window** (mandatory, §4). Add+ forward/backward tolerance days (candidate home: `itemPlanning`, reusing+ `demandReschedulingPeriod`, or a company-level default) so Expedite/Defer only+ fire past a threshold. Without this the worklist becomes noise.++5. **Add a buyer/planner ownership + assignment model.** Follow Epicor's Buyer-ID+ idea but reuse Carbon's existing generic `assignee` pattern where possible.+ Options to resolve in spec: (a) an owner field on the item (per-item or+ per-item-location, analogous to SAP MRP controller / purchasing group), with a+ resolution fallback; and/or (b) an `assignee` on each action-message row that a+ lead can (re)assign. Populate the PO `assignee` when an Order action converts.+ Let the planning worklist filter by assignee ("my actions") and act in bulk.++6. **Generalize the consuming action + UI.** Extend `planning.update.tsx` beyond+ `action === "order"` to handle expedite/defer/cancel (edit/cancel the referenced+ document), and extend the planning tables/drawers to render the action type,+ proposed date, reason, and assignee, with **bulk accept/dismiss** (NetSuite's+ Perform-Selected-Actions). Preserve the existing "Order" behavior as one action+ type among several.++7. **Keep the two module views** (purchasing planning vs production planning) as the+ buyer/planner split (BC's Planning vs Requisition Worksheet analog): purchasing+ view shows buy actions to buyers, production view shows make actions to planners.++### Open questions to carry into the spec++- **Terminology**: confirm action-type names against `@carbon/glossary` domain+ terms ("Expedite"/"Defer" vs "Reschedule In/Out" vs "Pull In/Push Out";+ "Order" vs "New"). SAP/Epicor say expedite/de-expedite; NetSuite/LN say+ reschedule in/out.+- **Assignment axis**: per-item owner (SAP MRP-controller style) vs per-message+ assignee vs both? Where does the owner field live — `itemReplenishment`+ (buy-side) / `itemPlanning` (per-location) / a new `buyer`/`planner` reference?+- **Do we introduce an unfirmed "planned order" tier**, or keep creating real+ `Planned` POs/jobs and treat every change-action as operating on real documents?+ (Recommendation: keep Carbon's real-document model; it's simpler and matches+ SAP's firmed-receipt semantics — but this is a scope decision.)+- **Persistence vs recompute**: persist action messages (needed for assignment ++ bulk work + dismissal state) vs continue computing on read. (Recommendation:+ persist — assignment and dismissal state require it.)+- **Change-quantity actions**: include Increase/Decrease Qty, or fold into+ Expedite/Defer + Cancel like SAP does? (SAP folds; D365/Epicor split.)+- **Advisory exceptions scope**: which exceptions ship in v1 (below safety stock,+ over-supply, past-due/cannot-meet-date, master-data broken)?+- **Tolerance home + defaults**: company-level default days vs per-item override.++## Sources++### SAP+- MRP exception 30 vs 10 (firmed vs planned): https://community.sap.com/t5/enterprise-resource-planning-q-a/mrp-exception-message-difference-between-30-10/qaq-p/10550514+- KBA 1698291 — messages 10/15/20/26/30 not displayed in MD04: https://userapps.support.sap.com/sap/support/knowledge/en/1698291+- KBA 3542305 — msg 10 without reschedule date: https://userapps.support.sap.com/sap/support/knowledge/en/3542305+- KBA 2609209 — reschedule exceptions 10 and 30: https://userapps.support.sap.com/sap/support/knowledge/en/2609209+- Exception 20 vs 10 in MD04: https://community.sap.com/t5/enterprise-resource-planning-q-a/differences-between-exception-20-and-10-in-md04/qaq-p/10399918+- Froggy's SAP — exception messages 10/15/20: http://froggysap.blogspot.com/2014/07/sap-mrp-understanding-exception.html+- SAPinsider — manage MRP exception messages: https://sapinsider.org/manage-material-requirements-planning-exception-messages-in-sap/+- SAP supply chain — exception-minded business (8 groups, MD06 vs MD07): http://sap-supply-chain-ideas.blogspot.com/2012/05/moving-towards-exception-minded.html+- MD07 exception monitor: https://blogs.sap.com/2022/07/02/md07-mrp-exception-monitor-collective-stock-requirement-list/+- Converting planned orders → PRs (MD14, auto-firm): https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/9905622a5c1f49ba84e9076fc83a9c2c/49106354c08b063de10000000a441470.html+- Planned orders get firmed (PTF firming): https://community.sap.com/t5/enterprise-resource-planning-q-a/planned-orders-get-firmed/qaq-p/9599784+- Firming type in MRP types: https://www.stechies.com/what-is-firming-type-in-the-mrp-types/+- Define MRP controllers: https://www.saponlinetutorials.com/define-mrp-controllers-material-requirement-planning/+- Purchasing group vs MRP controller: https://community.sap.com/t5/enterprise-resource-planning-q-a/purchasing-group-and-mrp-controller/qaq-p/4888880+- MRP Exception Monitor (Fiori) PDF: https://help.sap.com/doc/80c6ad471d2d42598c766e3ef5c1fac4/2024.1/en-US/ERM-EN-PUBLIC.pdf++### Microsoft Dynamics 365+- SCM master planning home: https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/master-planning-home-page+- SCM delays (futures messages): https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/delays+- AX 2012 about action messages (Advance/Postpone/Increase/Decrease/Derived): https://learn.microsoft.com/en-us/previous-versions/dynamicsax-2012/appuser-itpro/about-action-messages+- SCM master planning performance (time fences): https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/master-planning-performance+- SCM firm planned orders: https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/planning-optimization/planned-order-firming+- SCM coverage settings: https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/coverage-settings+- SCM maintain/filter planned orders: https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/maintain-planned-orders+- BC about planning functionality: https://learn.microsoft.com/en-us/dynamics365/business-central/production-about-planning-functionality+- BC run MPS/MRP (action-message enum, Carry Out): https://learn.microsoft.com/en-us/dynamics365/business-central/production-how-to-run-mps-and-mrp+- BC planning journal action messages (plain-language): https://usedynamics.com/business-central/planning/action-messages/++### Oracle NetSuite+- Planning Action Messages (coded exceptions, Reschedule In/Out): https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_3865354301.html+- Supply Planning overview: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_159171867422.html+- Setting up Reschedule Out messages: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_162557605659.html+- Supply Planning Workbench: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_159187932855.html+- Creating a Planning Workbench View: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_164313117883.html+- NetSuite 2025.2 supply chain enhancements: https://www.netsuite.com/portal/resource/articles/supply-chain-management/netsuite-2025-2-optimizes-supply-chain-planning-and-execution-efficiency.shtml+- Rand Group — supply planning enhancements (bulk approve): https://www.randgroup.com/insights/oracle-netsuite/netsuite-supply-planning-and-allocation-enhancements/++### Epicor+- New vs Change PO Suggestions: https://www.epiusers.help/t/opinions-wanted-new-po-suggestions-vs-change-po-suggestions/101881+- Change PO Suggestions: https://www.epiusers.help/t/change-po-suggestions/136427+- Expedite from Change PO Suggestions: https://www.epiusers.help/t/expedite-pos-from-change-po-suggestions-benefit-or-liability/90485+- Reschedule out/in delta parameters: https://www.epiusers.help/t/reschedule-out-and-reschedule-in-parameters-affect-on-po-sugestions/116671+- Buyer field / Part-Plant→Part-Class→default: https://www.epiusers.help/t/buyer-field-in-new-po-suggestions/44378+- Filtering PO Suggestions by Site and Buyer: https://www.epiusers.help/t/filtering-po-suggestions-with-different-sites-and-buyers/97142+- MRP unfirming jobs: https://www.epiusers.help/t/mrp-is-unfirming-jobs/102553+- Production Management (workbenches): https://tomerlin-erp.com/knowledge-production-management/+- Kinetic Planning & Scheduling: https://www.epicor.com/en-us/products/enterprise-resource-planning-erp/kinetic/planning-and-scheduling/++### Infor+- SyteLine planning activity / firm planned orders / Order Action Report: https://csi.lamartcorp.com/syteline/language/en-us/mergedProjects/sl_invprod/forms/mrptopic/planning_activity.htm+- SyteLine APS overview: https://www.visualsouth.com/blog/advanced-planning-and-scheduling+- SyteLine PO requisitions from planned orders: https://inforcloudsuite.blogspot.com/2015/04/purchase-order-requisitions.html+- LN order/order-planning exception messages (Reschedule In/Out, Cancel Order): https://docs.infor.com/ln/10.5/en-us/lnolh/help/cp/onlinemanual/000069.html+- LN types of exception messages: https://docs.infor.com/ln/10.5/en-us/lnolh/help/cp/onlinemanual/000063.html+- LN Process Exception Messages (cprao1220m000): https://docs.infor.com/ln/10.3/en-us/lnolh/help/cp/rao/cprao1220m000.html+- LN Exception Message Types by Planner (cprao1110m000): https://docs.infor.com/ln/10.6/en-us/lnolh/help/cp/rao/cprao1110m000.html+- LN Planned Order (cprrp1600m000), Confirm/Order Status: https://docs.infor.com/ln/10.4/en-us/lnolh/help/cp/rrp/cprrp1600m000.html+- LN Planned Orders (cprrp1100m000): https://docs.infor.com/ln/10.5/en-us/lnolh/help/cp/rrp/cprrp1100m000.htmldiff --git a/.ai/runs/2026-09-08-mrp-planning-actions.md b/.ai/runs/2026-09-08-mrp-planning-actions.mdnew file mode 100644index 0000000000..0cc005cc90--- /dev/null+++ b/.ai/runs/2026-09-08-mrp-planning-actions.md@@ -0,0 +1,40 @@+# Feature run: MRP planning actions (Order / expedite / defer / cancel) assignable to buyers++- Date: 2026-09-08+- Mode: approval-per-phase (research + spec grill) → **fully-autonomous from 2026-09-08** (Brad: "use the autonomous flow to write the spec and the plan, then open a PR")+- Request: "use the /feature skill to rewrite MRP. currently the only action MRP suggests is 'Order' -- but this is not the whole story. in SAP, for instance, MRP will suggest a set of actions -- one of which is 'Order' -- but also includes moving the order date up, moving the order date back, and canceling orders. another big change in perspective is that these actions should be assignable to buyers. this is a big refactor, so let's start with some research."+- Phase plan: research [run — ERP-domain MRP logic, force-included] · spec [run — big refactor, multi-module, data model change] · plan [run] · execute [run] · test [run — user-facing planning UI] · self-review [run]++## Decisions+- Scope path (approval): **B** — focused spec carving the planned-order + action-message core out of MRP-v2 + adding buyer/planner assignment; RCCP / CTP / continuous-regen deferred to the MRP-v2 spec. — Brad, 2026-09-08++## Post-PR refinements+- 2026-09-09 (Brad): ladder item-group tier is **location-specific**. Tree = **all → location → item group** (per-item leaf + per-message assignee still on top). Item-group ownership moved OFF a column on itemPostingGroup INTO a sparse `itemPostingGroupResponsibility` table keyed (companyId, locationId, itemPostingGroupId) — mirrors the printer AssignmentsCard inheritance tree (location → work-center → here location → item-group). Updated spec §P1.2/§P1.3/§P1.8/§P1.11 + changelog; plan Task 1 (new table + PK-shape verify for composite FKs), Task 5 (resolver rung from the table by location+group), Task 10 (settings screen nests item-groups under each location). PR #1601 updated.+- 2026-09-09 (Brad): fix stale `.claude/rules/supersession-system.md` — MRP is `@carbon/ee/planning` `runMrp`, not the deleted `functions/mrp/**`.++## Open questions being grilled (one at a time)+- [x] Q1 assignment axis — **RESOLVED.** Decision C: per-level owner default + per-message assignee override (reuse Assignee/Employee picker, value=user.id). A SINGLE unified field `responsibleEmployee` (not separate buyer/planner) at each rung. Resolved via a PRIORITY LADDER (printer-style inheritance UI per resolveContextAssignment/AssignmentsCard), NOT a location×group matrix. Ladder most-specific→general: **item (planning tab) → item-group → location → company default → unassigned**; per-message assignee overrides. Same ladder for both purchasing (Buy) and production (Make) worklists; the item's replenishmentSystem decides which worklist shows it. itemPostingGroup table confirmed alive (only the party×item matrix was dropped); no buyer/planner table exists today (net-new). — Brad, 2026-09-08. **[Superseded 2026-09-09 — see Post-PR refinements]:** the item-group rung is LOCATION-SPECIFIC, looked up from the sparse `itemPostingGroupResponsibility` table by `(locationId, itemPostingGroupId)` — there is NO global item-group fallback. "Not a matrix" means the ownership model is an inheritance tree (each tier falls back up: item → location's item-group entry → location → company), not the removed customer-type × item-group cross-product; only configured cells are stored.+- [x] Q2 persistence model — **RESOLVED.** B + reconciliation (i): a focused persisted **`planningAction`** table is the v1 spine — ALL action types, each optionally referencing a real open PO-line/job, carrying resolved responsibleEmployee + overridable assignee + status (Open/Dismissed/Actioned), written **diff-write** (match on natural key, update in place, close stale, insert new; never delete-rewrite — preserves assignment/dismissal). **No Firm lifecycle in v1.** Heavy MRP-v2 pieces (plannedOrder Planned→Firm→Released lifecycle, plannedOrderPeg, planningRun, planningState, RCCP, CTP, continuous regen) → "Deferred / later phases" section of the SAME spec. **Home: UPDATE `.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md` in place, with changelog entry**; MRP-v2 becomes a phased spec. — Brad: "b" then "i", 2026-09-08+- NOTE: this run's home artifact is the UPDATED MRP-v2 spec, not a new .ai/specs file.+- [x] Q3 terminology/enum — **RESOLVED.** `planningActionType` = `Order | Make | Expedite | Defer | Cancel | Increase | Decrease` (capitalized display-friendly enum). Order=new PO (Buy), Make=new job (Make); Expedite=pull existing PO-line/job in, Defer=push out, Cancel=drop redundant existing order, Increase/Decrease=qty change on existing order (Increase/Decrease INCLUDED in v1 per Brad). Expedite/Defer/Cancel/Increase/Decrease target existing documents (PO-line or job). One atomic action per row; combined date+qty → single highest-priority message. Will sanity-check names vs @carbon/glossary when writing. — Brad 2026-09-08+- [x] Q4 advisory exceptions — **RESOLVED: actionable only in v1.** No standalone advisory/warning rows. Urgency = flag on the action row (persist isASAP/isPastDue). Condition (below safety stock, projected stock, reorder point) captured in each action's reason/triggerValues. Dedicated warning/alert channel (below-safety-stock alerts, excess-stock, master-data-broken/no-BOM diagnostics) DEFERRED to later phase. — Brad 2026-09-08+- [x] Q5 tolerance — **RESOLVED (my rec, surfaced for veto).** ONE company-level scalar `rescheduleToleranceDays` (default 7 = one weekly bucket, symmetric, gates Expedite+Defer). NO separate qty dampener in v1 — rely on existing orderMultiple/lotSize/min-max-OQ rounding to absorb trivial qty deltas; add a qty dampener later only if churn is observed. Brad asked for my rec given 80/20 → single scalar. — 2026-09-08. Applying 80/20 to remaining Qs.+- [x] Q6 acting on a message — **RESOLVED.** planningAction is a recommendation; existing owning subsystem executes. Creates (Order/Make) reuse existing planning.update + stamp assignee. Change actions (Expedite/Defer/Increase/Decrease/Cancel) branch on COMMITMENT STATE of target, not action type: (1) UNCOMMITTED (Draft/Planned PO line, un-released job) → one-click auto-apply via existing services (edit requiredDate/purchaseQuantity, cancel/remove line). (2) COMMITTED (PO sent to supplier, job released to floor) → NO silent edit; message still surfaces recommendation but acting NAVIGATES to the PO/job for manual reopen+notify; row flagged "Review on PO". Automated reopen + supplier-notification/change-order flow DEFERRED. One-click + bulk; status flips Actioned/Dismissed. TODO when writing: verify exact PO status marking "sent to supplier" + whether reopen action exists. — Brad "yes" 2026-09-08+- [x] Q7 live grid — **RESOLVED.** KEEP the live 48-week projection columns (cheap view over MRP's forecast/actual tables). ADD planningAction worklist on the same pages. Persisted planningAction becomes SINGLE SOURCE OF TRUTH for suggestions — grid's suggestion column reads persisted actions instead of live calculate_quantity_to_order; grid+worklist never disagree; change actions live alongside Order/Make. Consequence accepted: suggestions refresh per MRP run (3h + manual Recalculate), not per page load — the correct ERP model + prerequisite for assignment/dismissal. — Brad "i accept it" 2026-09-08+- [x] Q8 UI surface — **RESOLVED.** Extend the TWO existing planning pages in place (x+/purchasing+/planning, x+/production+/planning) — no new module/page. Add columns: action type, suggested date/qty, reason (triggerValues), assignee, status, urgency flag. Filters: assignee (default "my actions"=current user), action type, status. Reuse Assignee component per row (prefilled from resolved responsibleEmployee, reassignable), bulk assign + bulk accept/dismiss via existing multi-select. ONE new settings screen cloned from printer AssignmentsCard: company-default + list of locations + list of item-groups, inherited placeholders. Per-item override on item Planning tab (responsibleEmployee). Unified cross-module cockpit DEFERRED. — Brad "yes" 2026-09-08++## ALL 8 QUESTIONS RESOLVED.++## Phase log+- research: DONE — .ai/research/mrp-planning-actions.md (SAP, D365 SCM+BC, NetSuite, Epicor, Infor SyteLine/LN + Carbon current-state map). Key grounding finding: the prior draft MRP-v2 spec (all OQs resolved, NOT implemented) already specified a plannedOrder exception model but had NO buyer/planner assignment; the ee-planning extraction (runMrp in @carbon/ee/planning) IS implemented in code. That drove the Path-B/phased-spec decision above.+- spec: DONE — updated `.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md` in place, re-scoped into phases. Added §P1 (Phase 1: action messages + assignment) with data model, ladder, engine changes, acting, tolerance, UI, design decisions, forward-compat, acceptance criteria, resolved OQs. Reframed prior game-changer content as Phases 2+. Changelog + phase-2 OQ pointer added.+- plan: DONE — `.ai/plans/2026-09-08-mrp-planning-actions.md` (12 tasks, Phase 1 only; grounded against sso-connection migration precedent, printer AssignmentsCard, existing PO/job services, MRP Phase-7 write path; shared pure sizing module + parity test; generatePlanningActions diff-write wired into runMrp; commitment gate; two planning pages extended; ownership settings screen).+- PR: opening now (autonomous — Brad asked). Committing only my artifacts (spec update, plan, research, run record); NOT the unrelated pre-existing tool-manifest.digest.json change.++## Outcome+- PR: https://github.com/crbnos/carbon/pull/1601 — now CODE + docs. /execute completed 2026-09-11: all 12 plan tasks done across 8 implementation commits (96d53c0177…fc99093a9d).+- execute: DONE. Verification: 239 utils + 833 ee tests green (sizing parity, change-action derivation, diff-write); repo-wide pnpm test 27/27 tasks; scoped typechecks clean. Browser-verified on the satellite dataset (crbn up stack): 72 persisted actions (41 Order / 27 Make / 2 Expedite / 2 Defer) written by BOTH the scheduled Inngest run (createdBy='system' FK held) and manual Recalculate; commitment gate flagged all 4 change actions on sent POs → "Review on PO" navigates to the PARENT purchase order; company-default ladder rung → recalc → all 72 actions assigned, "My actions · 45"; diff-write idempotent (counts stable) and a Dismissed action survived a full re-run; /x/settings/planning (tolerance + ownership tree) and item Planning tab Responsible Employee field render. Screenshots: .ai/scratch/e2e/.+- Deviations from plan (surfaced for veto): (1) pure sizing fn takes an injected `todayDate` (clock-free purity; getLocalTimeZone is server-banned); (2) worklist renders as a dedicated actions card above the projection grid — the grid's legacy quantityToOrder column was NOT re-pointed to persisted rows (both derive from the same RPC inputs; divergence = staleness window only); Order/Make apply flows through the existing order drawer, change actions apply from the worklist; (3) "my actions" default is a local Mine/All toggle (default Mine) rather than a URL filter; (4) self-review fixes landed: Dismissed-row suppression + lot-split aggregation per (type, period).+- Follow-ups: /translate fill for the new UI strings (English fallback works meanwhile); optional grid-column re-point per Q7 strict reading; live one-click apply on an UNCOMMITTED PO change action not exercisable on this dataset (all change targets were sent POs) — covered by route logic + gate tests.+- Commit: b788d5ff2f on branch mrp-action-suggestions (4 files; unrelated tool-manifest.digest.json left uncommitted; later committed separately as b062309556 on Brad's ask).+- 2026-09-11: CodeRabbit review round (17 findings) folded into spec + plan — one-action-per-target precedence; no-swallow generation errors; Dismissed-vanished rows retired; strict-`>` tolerance boundary + CHECK(>=0) + 0–365 validation; gate on isPurchaseOrderLocked only; IDOR bind (apply loads persisted action by id+companyId, status Open, stored values); explicit job path (updateJob + notifyScheduleInputsChanged "reorder"); itemPostingGroup UNIQUE(id,companyId) prerequisite (PK verified ("id") alone; location already has it via 20260905132037); explicit ENABLE RLS on itemPostingGroupResponsibility; parent purchaseOrderId join for navigation; enum→lowercase wire map; system-user audit actor verified seeded (20230123004317). Proceeding to /execute.diff --git a/.ai/runs/2026-09-11-demand-forecast-consumption-audit.md b/.ai/runs/2026-09-11-demand-forecast-consumption-audit.mdnew file mode 100644index 0000000000..108a92755a--- /dev/null+++ b/.ai/runs/2026-09-11-demand-forecast-consumption-audit.md@@ -0,0 +1,302 @@+# Demand-forecast ↔ actual-demand audit (branch `mrp-action-suggestions`)++Audited 2026-09-11 by a read-only Explore agent as Phase 0 of the demand-forecast-consumption+feature run (`.ai/runs/2026-09-11-demand-forecast-consumption.md`). Findings below are the+agent's report, verbatim.++## Headline verdict++**The belief that same-period netting already works is REFUTED.** There is no netting, no `max()`, no consumption of any kind between forecast and actual demand — anywhere in the stack. Forecast and actual demand are **summed** in four independent places. A forecast of 10 plus sales orders of 10 in the same week produces **gross demand of 20**.++---++## 1. SCHEMA++### Two look-alike tables — input vs. output++| Table | Role | Written by |+|---|---|---|+| `demandProjection` | **Input.** The authored forecast ("we expect to sell 40 in March") | Planner, via the Demand Forecasts screen |+| `demandForecast` | **Output.** MRP's BOM-exploded *child/component* demand (`forecastMethod = 'mrp'`) | `runMrp`, wiped + rewritten every run |++`demandProjection` — `packages/database/supabase/migrations/20251020183630_mrp-projections.sql:3-25`:+```+itemId TEXT NOT NULL, locationId TEXT, periodId TEXT NOT NULL,+forecastQuantity NUMERIC NOT NULL DEFAULT 0,+forecastMethod TEXT, -- 'manual','statistical','ml' — never written by the UI+confidence NUMERIC(3,2), -- never written by the UI+notes TEXT, companyId TEXT NOT NULL,+createdBy/createdAt/updatedAt/updatedBy+PK (itemId, locationId, periodId) + UNIQUE (itemId, locationId, periodId, companyId)+```+A surrogate `id TEXT DEFAULT id()` was added later (`20260527110002_demand-forecast-source.sql:12-17`) so `demandForecastSource` can FK to it. Note: `mrp.ts:464` cites a migration filename `20260527115843_demand-projection-source.sql` **that does not exist** — minor comment drift.++`demandForecast` — `20250610000433_demand-planning.sql:37-55`: identical column shape; `PK (itemId, locationId, periodId)`, plus `UNIQUE (itemId, locationId, periodId, companyId)` from `20260527110002_demand-forecast-source.sql:1-3`.++`demandActual` — same file, lines 105-120: `PK (itemId, locationId, periodId, sourceType)` where `demandSourceType` is `'Sales Order' | 'Job Material'`. Mirror tables `supplyForecast` / `supplyActual` (`supplySourceType` = `'Purchase Order' | 'Production Order'`) exist for the supply side.++`demandForecastSource` — `20260527110002_demand-forecast-source.sql:30-95`: lineage/pegging for BOM-derived rows. Surrogate PK, `sourceType` enum `'Job Material' | 'Sales Order' | 'Demand Projection'`, exactly one of `jobId`/`salesOrderLineId`/`demandProjectionId` enforced by CHECK. `redirectedFromItemId` added in `20260618171234_material-supersession.sql`.++### Period granularity++`period` table (`20250610000433_demand-planning.sql:26-34`): `id`, `startDate DATE`, `endDate DATE`, `periodType ('Week'|'Day'|'Month')`. **No `companyId`** — periods are globally shared across tenants.++Granularity is **calendar week, Sunday-start (`en-US` locale), 7 days wide**, anchored on "today" in the **company** timezone for MRP and the **location** timezone for the UI:++- MRP: `packages/ee/src/planning/mrp/mrp.ts:105-107` → `datetime.today(await getCompanyTimeZone(db, companyId))`, then `getStartAndEndDates(today, "Week")` at `mrp.ts:1069-1097` → `startOfWeek(today, "en-US")`, 7-day buckets, `WEEKS_TO_FORECAST = 18 * 4 = 72` weeks (`mrp.ts:32`).+- UI: `apps/erp/app/modules/shared/shared.server.ts:498-560` (`getOrCreatePeriods`) → identical `startOfWeek(today, "en-US")` but with `getLocationTimeZone`.+- `'Day'` and `'Month'` both `throw new Error("Not implemented")` (`mrp.ts:1090-1093`).++### Scoping++`companyId` is a column on `demandProjection`/`demandForecast`/`demandActual` with RLS on `inventory_view`/`inventory_create`/`inventory_update`/`inventory_delete`. `locationId` is nullable in the DDL but part of the PK (so effectively NOT NULL). MRP **skips any row with a null `locationId`** rather than writing `""` and violating the FK — `mrp.ts:446-451`, `483`, `521`, `368`, `396`.++### UI to author forecasts++Route tree `apps/erp/app/routes/x+/production+/`:+- `demand-forecasts.tsx` — list; loads `getProductionProjections` RPC over `WEEKS_TO_PROJECT = 12 * 4` (line 26). Plan-gated by `usePlanGate({ feature: "FORECAST" })` (line 90) with `ForecastUpgradeOverlay`.+- `demand-forecasts.new.tsx`, `demand-forecasts.$itemId.$locationId.tsx` (52-week grid; `WEEKS_TO_PROJECT = 52` at line 19), `demand-forecasts.delete.$itemId.$locationId.tsx`.+- Components: `apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx` (382 lines, 52 cells in 4 quarter tabs + live chart) and `DemandProjectionTable.tsx`.+- Services: `production.service.ts:4657` `upsertDemandProjections` (zero → delete, non-zero → upsert on `itemId,locationId,periodId,companyId`), `:857` `getDemandProjections`, `:521` `deleteDemandProjections`. Parallel `*DemandForecasts` functions exist at `:497`, `:843`, `:4624` but operate on the MRP output table.+- Server writes go through `requirePlan({ feature: "FORECAST" })`.++### Forecasting configuration++**There is none, specific to forecasting.** No item-level "forecast consumption period" flag, no company planning setting, no forecast horizon config. `forecastMethod` and `confidence` are schema placeholders the UI never writes. The only planning config is on `itemPlanning` (`20230330024716_parts.sql:847-877` + later ALTERs): `reorderingPolicy`, `safetyStockQuantity`, `safetyStockLeadTime`, `demandAccumulationPeriod` (default forced to 30 by `20250610000433_demand-planning.sql:9-10`), `demandAccumulationSafetyStock`, `reorderPoint`, `reorderQuantity`, `minimumOrderQuantity`, `maximumOrderQuantity`, `orderMultiple`, `maximumInventoryQuantity`, `responsibleEmployee`. `demandReschedulingPeriod` was **dropped** in `20250616131548_production-planning.sql:1`. Company level: only `companySettings.rescheduleToleranceDays` (`20261006130000_mrp-planning-actions.sql:109-110`).++Note: `apps/erp/app/modules/production/forecast.server.ts` / `forecast.test.ts` are **capacity/scheduling** forecast (non-working intervals for the Gantt), unrelated to demand forecasting. Same for `routes/x+/scheduling+/forecast.tsx`.++---++## 2. DEMAND SOURCES in `runMrp`++All in `packages/ee/src/planning/mrp/mrp.ts`. Phase 1 bulk-loads at `:125-183` (all paginated via `fetchAll`). Phase 4 (`:419-552`) merges into a single map:++```ts+// mrp.ts:424+const grossDemand = new Map<string, number>(); // key = locationId ␟ periodId ␟ itemId+```++| # | Source | View/table | Loaded | Merged | Date → period |+|---|---|---|---|---|---|+| 1 | **Demand projections (the forecast)** | `demandProjection` | `:161-171` | `:442-477` | Row already carries `periodId` — no date mapping |+| 2 | **Sales order lines** | `openSalesOrderLines` | `:132-138` | `:480-515` | `promisedDate ?? today` → `findPeriod` (`:485-488`) |+| 3 | **Job materials** | `openJobMaterialLines` | `:139-145` | `:518-552` | `job.dueDate − item leadTime` → `findPeriod` (`:523-526`) |+| 4 | **BOM-exploded child demand** | derived | — | inside `explodeBom` | parent period index − `ceil(leadTime/7)` weeks, floored at period[0] |+| 5 | Open jobs (**supply**, not demand) | `openProductionOrders` | `:146-152` | `:363-389` → `jobSupplyByLocationPeriodItem` | `dueDate`, or `today+30d` if `deadlineType = 'No Deadline'`, else `today` |+| 6 | Open POs (**supply**) | `openPurchaseOrderLines` | `:153-160` | `:393-417` → `poSupplyByLocationPeriodItem` | `promisedDate ?? orderDate+leadTime ?? today+leadTime` |++**Safety stock is NOT a demand source in `runMrp`.** It enters only downstream, in the reorder-policy sizing (`calculate_quantity_to_order` in SQL / `computePlanningOrders` in TS) via `demandAccumulationSafetyStock` and `reorderPoint`.++Bucketing helper — `mrp.ts:1056-1067`:+```ts+function findPeriod(date, today, periods) {+ if (date.compare(today) < 0) return periods[0]; // anything past dumps into week 0+ return periods.find(p => p.startDate.compare(date) <= 0 && p.endDate.compare(date) >= 0);+}+```+A date outside the 72-week horizon returns `undefined` and the line is silently dropped (`:376-377`, `:404-405`, `:488-489`, `:526-527`).++---++## 3. NETTING LOGIC — **it does not exist**++### The decisive code++`packages/ee/src/planning/mrp/mrp.ts:438-477` — the projection (forecast) loop. The variable is *named* `netDemand` but nothing is netted from it:++```ts+// Demand projections. Do NOT net firm job/PO supply here — supply is+// credited exactly once by explodeBom's running balance ...+for (const projection of demandProjections.data ?? []) {+ if (!projection.itemId || !projection.forecastQuantity || !projection.locationId) continue;++ const netDemand = projection.forecastQuantity; // ← line 453: no netting at all++ if (netDemand > 0) {+ const key = makeKey(projection.locationId ?? "", projection.periodId, projection.itemId);+ grossDemand.set(key, (grossDemand.get(key) ?? 0) + netDemand); // ← line 461: ADD+```++`mrp.ts:480-492` — the sales-order loop writes to the **same key** and **adds again**:+```ts+const key = makeKey(line.locationId ?? "", period.id ?? "", line.itemId);+grossDemand.set(key, (grossDemand.get(key) ?? 0) + line.quantityToSend); // ← line 492: ADD+```++There is **no** `Math.max` anywhere in `packages/ee/src/planning/mrp/` except two unrelated clamps (`planning-actions.ts:210`, `:704`). Grep for `Math.max` across `mrp.ts` and `mrp-engine.ts` returns zero hits.++The only netting in `explodeBom` is **demand vs. on-hand + firm supply** — `packages/database/supabase/functions/lib/mrp-engine.ts:244-256`:+```ts+for (const period of periods) {+ running += jobSupply.get(periodKey) ?? 0;+ const grossQty = grossDemand.get(periodKey) ?? 0;+ if (grossQty <= 0) continue;+ const netRequirement = Math.max(0, grossQty - Math.max(0, running));+ running = Math.max(0, running - grossQty);+```+`grossQty` is the already-summed forecast+actual figure. There is no second dimension to reconcile.++### The same addition repeats in the read path — 4 sites total++**(a) `get_production_planning`** — latest definition `packages/database/supabase/migrations/20260715195226_planning-reads-demand-projections.sql:130-158`:+```sql+demand_data AS (+ SELECT "itemId","periodId",+ SUM(COALESCE("actualQuantity",0) + COALESCE("forecastQuantity",0)) AS "demand"+ FROM (+ SELECT ... FROM "demandActual" WHERE ... -- line 137+ UNION ALL+ SELECT ... FROM "demandForecast" WHERE ... -- line 143+ UNION ALL+ SELECT ... FROM "demandProjection" WHERE ... -- line 153+ ) combined+ GROUP BY "itemId","periodId"+)+```++**(b) `get_purchasing_planning`** — `20260831190142_purchasing-planning-reads-demand-projections.sql:115-145`, byte-identical union.++**(c) `generatePlanningActions`** — `packages/ee/src/planning/mrp/planning-actions.ts:527-574`, with a comment that *states* the design:+```ts+// ── demand per (item, location, period): actual + forecast + projection,+// the same union the planning RPCs read+...+byPeriod.set(periodId, (byPeriod.get(periodId) ?? 0) + (Number(quantity) || 0)); // line 560-563+```+called three times, once per table (`:566-574`).++**(d) `get_inventory_quantities`** — `20260316000000_inventory-demand-forecast.sql:141-153`: `demandActual + demandForecast` (notably **omits** `demandProjection`, inconsistent with (a)–(c)).++### The three numeric cases++Take item X, location L, week W. Authored `demandProjection.forecastQuantity = 10`.++| Case | Authored forecast | Open SO lines | MRP `grossDemand[L␟W␟X]` | RPC `demand_data` | Correct answer under consumption |+|---|---|---|---|---|---|+| A | 10 | 10 | **20** | **20** | 10 |+| B | 10 | 5 | **15** | **15** | 10 |+| C | 10 | 12 | **22** | **22** | 12 |++Trace for case A: `mrp.ts:461` sets the key to 10; `mrp.ts:492` adds 10 → 20. `explodeBom` (`mrp-engine.ts:248-251`) reads `grossQty = 20` and drives 20 units of component demand down the BOM. On the read side, the SO's 10 was written to `demandActual` (`mrp.ts:494-503` → `:821-835`), and the projection's 10 still sits in `demandProjection`, so `demand_data` sums 10 + 10 = 20 again.++### So: which formula is it?++**None of the netting formulas.** It is plain `forecast + actual` — pure addition. Not `max(forecast, actual)`, not `(forecast − actual) + actual`.++### Period boundary++Calendar week, **Sunday-start**, `en-US` locale, derived from `startOfWeek(datetime.today(companyTimeZone), "en-US")` and materialized as explicit `period` rows with `startDate`/`endDate` DATE columns. Matching is an **exact `periodId` equality join** on the read side (`d."periodId" = periods[n]`) and an exact map-key match in TS. It is *not* a date range between forecast entries and it is *not* a sliding window.++---++## 4. JOBS++### Make-to-stock jobs (not linked to a sales order)++They are **supply, never demand**, and they do **not** consume forecast. `openProductionOrders` (current definition, `20260811123619_widen-sales-production-scale.sql`, forked from `20260417000300`):+```sql+WHERE j."status" IN ('Planned','Ready','In Progress','Paused')+AND j."salesOrderId" IS NULL+```+They land in `jobSupplyByLocationPeriodItem` (`mrp.ts:363-389`), get merged with PO supply into `jobAndPoSupplyByLocationPeriodItem` (`mrp.ts:618-626`), and are credited **once** in the `explodeBom` running balance (`mrp-engine.ts:246`) and again on the read side via `supplyActual` (`mrp.ts:877-897`) → the RPC's `supply_data` CTE.++The practical consequence: a make-to-stock job reduces the *projected balance*, not the forecast. With forecast 10 + SO 10 = 20 demand and a 10-unit stock job, `netRequirement = 20 − 10 = 10`, and MRP suggests **another 10** — the double count is untouched.++### Sales-order-linked jobs — yes, deliberately excluded, but on the *supply* side++Two complementary guards prevent SO↔job double counting:++1. `openProductionOrders` drops `salesOrderId IS NOT NULL` jobs from supply entirely (above).+2. `openSalesOrderLines` (current, forked from `20260710051147_mto-sales-lines-drive-demand.sql`) **reduces the SO line's demand by its linked jobs' outstanding quantity**:+```sql+CASE+ WHEN sol."methodType" = 'Make to Order' THEN GREATEST(+ sol."quantityToSend" - COALESCE((+ SELECT SUM(GREATEST(j."quantity" - j."quantityReceivedToInventory" - j."quantityShipped", 0))+ FROM "job" j+ WHERE j."salesOrderLineId" = sol."id"+ AND j."companyId" = sol."companyId"+ AND j."status" IN ('Planned','Ready','In Progress','Paused')+ ), 0), 0)+ ELSE sol."quantityToSend"+END AS "quantityToSend"+```++3. `openJobMaterialLines` excludes `jm."methodType" != 'Make to Order'` (a sub-job will be spawned), and `explodeBom` skips writing `bomDerivedDemand` for MTO+Make children for the same reason (`mrp-engine.ts:264-267, 288-293`).++**This proves the codebase already knows how to prevent double counting between two demand-ish sources — it just applies that logic only between an SO line and its own job, never between a forecast and an SO.**++Also note the SO gate: `openSalesOrderLines` requires `so."status" IN ('To Ship','To Ship and Invoice')`. A `Confirmed` or `In Progress` sales order contributes **zero** demand to MRP.++---++## 5. THE GAP BUG — **CONFIRMED (as a special case of "no consumption at all")**++A sales order due in a period with zero forecast consumes **nothing** from any adjacent period. There is no backward consumption, no forward consumption, no consumption window at all.++Structural proof, three independent layers:++1. **Key identity.** Demand is stored in a flat map keyed on the exact triple `locationId ␟ periodId ␟ itemId` (`mrp-engine.ts:71-77`). Reads are `grossDemand.get(periodKey)` — a hash lookup on one exact key (`mrp-engine.ts:248`). Nothing in `mrp.ts` or `mrp-engine.ts` ever iterates neighbouring periods looking for forecast to draw down. The only code that *does* walk periods sequentially is the supersession on-hand draw-down (`mrp.ts:575-606`) and the `explodeBom` running balance (`mrp-engine.ts:244`), and both consume **inventory/supply**, not forecast.++2. **SQL join.** `demand_data` in both RPCs groups by `("itemId","periodId")` and the recursive `projections` CTE joins `d."periodId" = periods[p.period_index + 1]` — an equality join on a single period. A SQL window function or range join would be required for cross-period consumption; there is none.++3. **Nothing survives to a later stage that could do it.** By the time `computePlanningOrders` (`packages/utils/src/planning-sizing.ts:66`) runs, its input is a flat `projections: number[]` of already-collapsed running balances (`:49-50`). The forecast/actual distinction has been destroyed by the `SUM`, so no downstream consumption is even expressible.++**Compounding factor worth flagging:** `projections` is a **cumulative running balance** (recursive CTE, `20260715195226_...:238-241` and `:262-264`: `p."projection" + supply − demand`). So a double count in week 3 depresses weeks 3 through 52, not just week 3. The over-ordering is permanent across the horizon, not a one-week blip.++The nearest existing analog to a window is `itemPlanning.demandAccumulationPeriod`, used by the Demand-Based Reorder branch of `computePlanningOrders` (`planning-sizing.ts:91-120`) to chunk periods for **order sizing**. It operates on the already-summed balance and cannot repair double counting — it only smears the inflated requirement across a wider window.++---++## 6. PLANNED ACTIONS — where a netting change propagates++`runMrp` commits forecasts/actuals in one transaction (`mrp.ts:938-1032`), then calls `generatePlanningActions(client, db, { companyId, userId })` at `mrp.ts:1039` in a separate transaction so the planning RPCs read committed data.++Inside `packages/ee/src/planning/mrp/planning-actions.ts`, the netted demand reaches `planningAction` by **two distinct paths**:++- **New-supply actions (`Order` / `Make`).** Per location, `client.rpc("get_purchasing_planning" | "get_production_planning", ...)` at `:679-690`; the `week1..weekN` projected-balance columns are unpacked at `:735-738` and fed to `computePlanningOrders` at `:739-756`. Those week columns are the recursive `projections` CTE output, i.e. the additively-summed demand.+- **Change actions (`Expedite` / `Defer` / `Cancel` / `Increase` / `Decrease`).** The in-Node additive union at `:529-574` builds `demandByItemLocation`, converted to `demandPeriods` at `:777-785` and passed to `deriveChangeActions` at `:787-795`. That function runs a chronological *supply*-consumption walk (`:181-206`) — demand draws down on-hand, then the earliest open orders — and emits exactly one action per document.++Candidates are then diff-written against `planningAction` on the natural key `(item, location, type, period, target document)`.++**A netting change must therefore land in three places to stay consistent** — plus a fourth for UI truth:+1. `mrp.ts` Phase 4 (`:442-515`) — the gross-demand construction that drives BOM explosion.+2. Both SQL RPCs' `demand_data` CTE — `20260715195226_...:130-158` and `20260831190142_...:115-145`.+3. `planning-actions.ts:529-574` — the in-Node union.+4. (`get_inventory_quantities` `demand_forecast` CTE, `20260316000000_...:141-153`, if the Inventory table's `demandForecast` column should agree.)++Changing only one produces a grid and a worklist that disagree — exactly the failure mode the MRP-v2 spec calls out at `.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md:376`.++---++## 7. LOOSE ENDS++**No prior attempt at forecast consumption exists.** Searches for `consumption`, `consumeForecast`, `forecastConsum*`, `netting`, and "double count" across `packages/ee/src`, `packages/database/src`, and the ERP production/items modules return only: accounting netting, scheduling remaining-work netting, `explodeBom`'s inventory netting, and `planning-actions.ts:181`'s supply-consumption walk. No `consumedQuantity` / `consumptionPeriod` / `forecastConsumed` columns exist on any table. No TODOs about forecast double counting.++**The additive behavior is documented as intentional** — `apps/erp/app/modules/agent/kb/docs/reference/forecast.md`:+> "A projection's full `forecastQuantity` enters gross demand at face value — it is *not* pre-netted against open production. ... Actual **sales orders** and **job material** demand are firm too — **they're added in full alongside the projection**."++That paragraph is accurate about the code and is the clearest statement that the "same-period netting" belief is mistaken. Note the doc also cites stale paths (`ui/Projection/...`, `routes/.../projections.new.tsx`) that are now `ui/DemandProjection/...` and `demand-forecasts.new.tsx`.++**MRP v2 spec touches the area but does not fix it** — `.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md`:+- `:622` describes gross demand as "independent demand (sales orders, demand projections)" — still additive.+- `:851-868` (§8) proposes *suggested* projections (trailing average, `forecastMethod = 'suggested'`, CV gate), never auto-applied. `:1230-1231` explicitly says "`demandProjection` gains no columns."+- `:1225-1231` relates the forecast tables to the proposed `plannedOrder` entity; `plannedOrderPeg` (`:1027`, `:1122-1124`) mirrors `demandForecastSource`.++**Supersession interaction with forecasts — partially applied, and inconsistent.** `buildSupersessionRedirectMap` (`packages/database/supabase/functions/lib/supersession-pick.ts:33-84`, re-exported via `packages/database/src/supersession-pick.ts`) is built at `mrp.ts:256-259` gated on `today`, and Phase 4.5 (`mrp.ts:563-608`) redirects `grossDemand` — which by then **includes projection demand** — to the successor, stamping contributors with `redirectedFromItemId` (`:595-599`). So yes, supersession applies to forecasts *inside the explosion*.++But it does **not** apply on the read path:+- `demandProjection` rows still carry the **old** `itemId`, and the RPCs' third UNION arm reads that table raw. So in production/purchasing planning and in `planning-actions.ts`, a projection for a superseded part shows up under the old part, not the successor.+- Same for `demandActual`: `salesDemandByKey` / `jobMaterialDemandByKey` are populated at `mrp.ts:494-503` and `:531-540`, **before** Phase 4.5, and Phase 4.5 mutates only `grossDemand` and `topLevelContributors`. Actuals are written under the pre-redirect item.+- `base_items` in the RPCs then filters superseded items out (`20260715195226_...:216-231`), so that demand can vanish from the grid entirely.++**Other inconsistencies found:**+- `getItemDemand` (`apps/erp/app/modules/items/items.service.ts:647-683`, backing `ItemPlanningChart` via `routes/api+/items.$id.$locationId.forecast.ts`) reads `demandActual` + `demandForecast` but **not** `demandProjection` — so a top-level Make item whose only demand is a projection shows zero demand on its planning chart, while the planning grid shows it.+- `get_inventory_quantities` `demand_forecast` CTE likewise omits `demandProjection` (`20260316000000_...:141-153`).+- `mrp.ts:453` `const netDemand = projection.forecastQuantity` is a vestigial name from a version that netted supply here; the comment at `:438-441` explains why that netting was removed but the variable name was never updated. Likely a source of the "netting already works" belief.+- `mrp.ts:464` cites a non-existent migration filename.+- `getStartAndEndDates` is duplicated between `mrp.ts:1069-1097` and `shared.server.ts:498-560` (`getOrCreatePeriods`), differing only in company vs. location timezone — a company/location timezone mismatch can bucket the same date into different weeks for MRP vs. the authoring UI.+- Horizon mismatch: MRP plans 72 weeks (`mrp.ts:32`), `generatePlanningActions` 48 (`planning-actions.ts:37`), the forecast list 48 (`demand-forecasts.tsx:26`), the forecast edit grid 52 (`demand-forecasts.$itemId.$locationId.tsx:19`), and the RPCs take up to 52 `week` columns.++**Test coverage:** only `packages/database/supabase/functions/lib/mrp-engine.test.ts` exercises the engine, and it contains **no** `demandProjection` / `demandForecast` / `demandActual` references — `explodeBom` is tested purely on gross demand + on-hand + supply. `planning-actions.test.ts` tests `deriveChangeActions` / `convertOrdersToIncreases` in isolation. **No test pins the current additive behavior**, so a netting change would not be caught (in either direction) by the existing suite.diff --git a/.ai/runs/2026-09-11-demand-forecast-consumption.md b/.ai/runs/2026-09-11-demand-forecast-consumption.mdnew file mode 100644index 0000000000..b328a7dc99--- /dev/null+++ b/.ai/runs/2026-09-11-demand-forecast-consumption.md@@ -0,0 +1,27 @@+# Feature run: Demand forecast consumption for MRP++- Date: 2026-09-11+- Mode: fully-autonomous through plan; execute gated on Brad's veto+- Branch: mrp-action-suggestions (worktree kelowna)+- Request (verbatim): "we've rewritten a lot of the MRP functionality in this branch -- to move to a planned action approach -- but one problem that we still haven't solved is demand forecasting. the basic problem is double counting. a sales order due date and a projection for the same week should reconcile, such that if there are 10 sales orders and 10 forecasted for the week, there are 10 demands driving MRP and if there are 5 sales orders and 10 forecasted for the week, there are 10 demands driving MRP and if there are 12 sales orders and 10 forecasted for the week, there are 12 driving MRP. this that i described above should be working already, although it's worth an audit to verify. jobs for inventory should work similar to sales orders in that they should net out. but here's the complication: when there are gaps between forecasts (e.g 0 this week, 10 next week, 0 the following week, 10 the week after that), and a sales order comes in that matches a 0, we don't back out the forecast and we end up with a double count. the basic problem we're trying to solve is how do we make the forecasts self-heal to the actuals without requiring communication between sales and production regarding updating the forecast. production should be able to set a rough estimate, and it should be flexible enough to work flexibly without the double counting. let's treat this like a feature"+- Phase plan: research [run — ERP-domain (MRP) logic, force-include] · spec [run — new data model + crosses sales/production/MRP] · plan [run] · execute [run, gated on veto] · test [run — MRP run + forecast UI are user-facing] · self-review [run — default]++## Decisions+- Autonomy gates: research→spec and spec→plan auto-resolved with recommendations recorded in the spec's Open Questions; plan→execute is a HUMAN stop (Brad's veto), per established workflow for domain-heavy features. — 2026-09-11++## Phase log+- Phase 0 (audit): DONE — `.ai/runs/2026-09-11-demand-forecast-consumption-audit.md`. **Belief REFUTED**: no netting exists anywhere; forecast + actuals are summed in 4 places (mrp.ts Phase 4, both planning RPCs' demand_data CTE, planning-actions.ts union). 10F+10SO = 20 demand today. MTS jobs DO net correctly (as supply, via explodeBom running balance). Gap bug confirmed as a special case of "no consumption at all". No test pins current behavior.+- Phase 1 (research): DONE — `.ai/research/demand-forecast-consumption.md`. Consensus: net = actuals + unconsumed forecast remainder, computed regeneratively per plan run; backward-then-forward search; bucket-granular windows for bucket-native forecasts; only demand consumes (jobs are supply); past forecast drops out. Recommended for Carbon: regenerative consumption in runMrp, week-bucket windows, compute-once/read-everywhere.+- Phase 2 (spec): DONE — `.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md`. Design: consumeForecast pure fn in @carbon/ee (actuals consume own bucket → backward 4 → forward 1, week-granular), regenerative in runMrp Phase 4 (pre-supersession), persisted as demandProjection.consumedQuantity, GREATEST-subtracted at 5 read sites (2 planning RPCs, planning-actions union, get_inventory_quantities, getItemDemand). New view column quantityToConsume (pre-job-dedup) so covered MTO orders still consume. 9 open questions autonomously resolved (recorded in spec) for veto at plan gate.+- Phase 3 (plan): DONE — `.ai/plans/2026-09-11-demand-forecast-consumption.md`. 10 tasks: pure fn+tests → migration (2 columns + quantityToConsume view column + 3 function forks) → types → runMrp wiring → planning-actions + getItemDemand + settings card + grid annotation (parallelizable) → docs sync → gates + /test (5 browser scenarios). Two spec corrections made during planning: get_inventory_quantities forks 20260716142907 (true newest), and upsertDemandProjections needs no change (PostgREST upserts preserve absent columns).++- GATE RESOLVED: Brad approved spec + plan ("let's execute") — 2026-09-11.+- Phase 4 (execute): DONE — 9 tasks, 9 commits (e24cc547b6 pure fn, 322288b5be migration+types, 42c3a86f5c runMrp wiring, 201a87040b planning-actions, 69747ad71a docs, 9a154bfdda settings card, a592b29b80 item chart, e91aae491e grid annotation, 2f99cf4255 translations). Tasks 5-8 dispatched as parallel subagents.+- Phase 5 (test): DONE — data+browser e2e on the satellite dev company. Settings "Forecast Consumption" card renders (defaults 4/1). Seeded 3 projections on item_XNY7 against its existing SO lines, ran real MRP via /api/mrp, and proved through get_production_planning: (A) same-week forecast 30 + SO 30 → net 30 not 60, consumed 30; (C) forecast 20 + SO 30 → net 30, consumed 20; (B gap) forecast 30 in an SO-less week + SO 30 the next week → SO reached back and consumed 30, net 0 that week / 30 the next, no double-count; (D) window set to 0/0 → gap forecast no longer consumed (setting is live), same-week still nets. Demand Forecasts grid renders. Test data + settings restored.+- Session note: hit a Haiku session rate limit mid-translate; resumed next session, finished the fill (0 missing). crbn/ERP dev server needed a restart via ./packages/dev/bin/crbn up (crbn not on non-interactive PATH). db:check:backups needs SUPABASE_DB_URL with 127.0.0.1 not localhost (node-pg IPv6 quirk).++## Outcome+- All 10 plan tasks complete and committed on mrp-action-suggestions (10 commits total incl. translations). Feature verified end-to-end. Not pushed / no PR opened (awaiting Brad). Self-review next.++## Outcome+- (pending)diff --git a/.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md b/.ai/specs/2026-08-22-mrp-v2-planned-order-generation.mdindex 285793cbbd..2a0015174a 100644--- a/.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md+++ b/.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md@@ -1,17 +1,464 @@# MRP v2: Live Planned-Order MRP — Generation, Cascade, Capacity & Simulation-> Status: draft+> Status: phased — **Phase 1 implemented** (PR #1601); Phases 2+ designed, not started> Author: Brad Barbin (with Claude)-> Date: 2026-08-22-> Scope: **game-changer v1** — everything in this spec ships in v1. That includes the-> full standard MRP feature set (planned orders, pegging, action messages over open-> orders, planning time fence/auto-firm, period-of-supply lot-sizing, worklist QoL),-> the five differentiators (continuous event-driven regeneration, capacity-honest-> netting + rough-cut capacity, what-if/CTP simulation, a self-explaining plan,-> workflow-programmable release), **and the calm-by-default layer** (§9) that keeps-> all of that enjoyable: one-click release, a worklist that never moves under the-> planner, confidence-gated exceptions, bucket-attributed capacity, and autopilot-> safety rails. The only explicitly post-v1 items are listed in **Deferred**.+> Date: 2026-08-22 (re-scoped into phases 2026-09-08)+> Scope: **now phased.** Originally written as a single "game-changer v1" that shipped+> everything at once. As of **2026-09-08** (Brad) it is re-scoped into delivery phases+> so the highest-value, lowest-complexity slice ships first:+>+> - **Phase 1 — Planning Action Messages & Buyer/Planner Assignment (ships first; fully+> specified in §P1 below).** MRP stops emitting only "Order": it emits a full set of+> assignable, dismissible **planning actions** — `Order`, `Make`, `Expedite`,+> `Defer`, `Cancel`, `Increase`, `Decrease` — persisted in a focused `planningAction`+> table and routed to a responsible buyer/planner via an inheritance ladder. Built on+> the **current** per-item netting; **no** planned-order cascade, **no** Firm+> lifecycle, **no** capacity/simulation. This is the 80/20.+> - **Phases 2+ — the full planned-order vision (everything from "## TLDR" / "Proposed+> Solution" onward, now DEFERRED).** The multi-level planned-order cascade ++> lot-sizing, the Planned→Firm→Released lifecycle, pegging, continuous regen,+> rough-cut capacity, what-if/CTP, the self-explaining plan, programmable release, and+> the calm-by-default layer (§9). All of that design is preserved below as the+> phase-2+ record; Phase 1's `planningAction` table is forward-compatible with it+> (see §P1.9).+>+> **Read §P1 first for what ships now.** Everything after "## TLDR" describes Phases 2++> unless §P1 cites it.++# §P1 — Phase 1: Planning Action Messages & Buyer/Planner Assignment (ships first)++> **This is Phase 1 — the slice that ships now.** Resolved with Brad on 2026-09-08 (run+> record: `.ai/runs/2026-09-08-mrp-planning-actions.md`; research:+> `.ai/research/mrp-planning-actions.md` — SAP, Dynamics 365 SCM + Business Central,+> NetSuite, Epicor, Infor SyteLine/LN). Everything from "## TLDR" onward is the Phase 2++> vision, deferred.++## P1.0 TLDR++Today MRP emits exactly one suggestion — **Order** — computed live in SQL+(`calculate_quantity_to_order`) and thrown away on every page load. Phase 1 makes MRP+emit the **full set of planning actions every ERP has** — `Order`, `Make`, `Expedite`,+`Defer`, `Cancel`, `Increase`, `Decrease` — **persists** them in a focused+`planningAction` table, and **routes each to a responsible buyer/planner** resolved+through an inheritance ladder (item → item group → location → company). A buyer opens+the planning page filtered to *"my actions"* and works a queue: one-click apply on+uncommitted supply, review-on-document for anything already sent to a supplier.++Phase 1 deliberately builds on the **current** per-item netting. It does **not** include+the multi-level planned-order cascade, the Planned→Firm→Released lifecycle, rough-cut+capacity, or what-if/CTP — those are Phases 2+ (the rest of this spec). This is the+80/20: the whole user-visible outcome (a full, assignable action worklist) at a fraction+of the full-vision build.++## P1.1 Scope — what Phase 1 does and does not do++**Does:**++- Emit and **persist** the seven `planningActionType` values as assignable, dismissible+ rows, refreshed each MRP run (diff-write).+- Compute **change actions** (Expedite/Defer/Cancel/Increase/Decrease) by comparing+ **real open POs/jobs** against net requirements — the SAP "reschedule/cancel on a+ firmed receipt" model.+- Resolve a **`responsibleEmployee`** per action via the inheritance ladder, stamp it as+ the row's assignee, and let a lead reassign per row (bulk-capable).+- Let a buyer **act** on a message: apply directly on uncommitted supply, navigate to the+ document on committed supply.+- Gate reschedule noise with a single company tolerance.++**Does NOT (deferred to Phases 2+):**++- The multi-level **planned-order cascade** (a parent's reorder need generating child+ demand before a job exists — the original MRP-v2 problem statement). Phase 1 Order/Make+ actions come from the **current** per-item reorder + demand netting, unchanged.+- The **Planned → Firm → Released** lifecycle, pegging tables, `planningRun`/+ `planningState`, continuous event-driven regen, rough-cut capacity, what-if/CTP,+ programmable release, and the §9 calm-by-default layer.+- A dedicated **advisory/warning** channel (below-safety-stock alerts, excess-stock,+ master-data-broken). Phase 1 is **actionable-only**; urgency is a flag, conditions live+ in each action's `reason`/`triggerValues`.++## P1.2 Data model++One new table, two new enums, four new `responsibleEmployee` columns, one tolerance+column. Standard Carbon conventions (composite PK, `id('…')` default, audit columns, four+RLS policies, `companyId` scoping; RLS uses `get_companies_with_employee_role()` /+`get_companies_with_employee_permission()`).++```sql+CREATE TYPE "planningActionType" AS ENUM+ ('Order', 'Make', 'Expedite', 'Defer', 'Cancel', 'Increase', 'Decrease');+CREATE TYPE "planningActionStatus" AS ENUM ('Open', 'Dismissed', 'Actioned');++CREATE TABLE "planningAction" (+ "id" TEXT NOT NULL DEFAULT id('pla'),+ "companyId" TEXT NOT NULL,++ "itemId" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "periodId" TEXT NOT NULL, -- weekly bucket (get-or-create)+ "type" "planningActionType" NOT NULL,+ "status" "planningActionStatus" NOT NULL DEFAULT 'Open',++ "suggestedQuantity" NUMERIC NOT NULL, -- lot-sized order qty (Order/Make) or target qty (Increase/Decrease)+ "suggestedDate" DATE NOT NULL, -- recommended due date for the action+ "isASAP" BOOLEAN NOT NULL DEFAULT false, -- urgency: release/need date already in the past++ -- Target of a CHANGE action (exactly one set; both NULL for Order/Make):+ "purchaseOrderLineId" TEXT,+ "jobId" TEXT,+ "requiresManualAction" BOOLEAN NOT NULL DEFAULT false, -- target committed (sent PO / released job) → "Review on document"++ -- Suggestion attribution (the "why"; computed today, discarded today):+ "supplierId" TEXT, -- resolved/preferred supplier for an Order+ "policyName" TEXT,+ "reason" TEXT,+ "triggerValues" JSONB, -- {projectedStock, safetyStock, reorderPoint, reorderQuantity, lotSize, leadTime}++ -- Assignment:+ "assignee" TEXT REFERENCES "user"("id"), -- resolved responsibleEmployee snapshot; overridable+ "assigneeOverridden" BOOLEAN NOT NULL DEFAULT false, -- true once a human reassigns; regen won't re-resolve it++ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+ -- + CHECK: purchaseOrderLineId/jobId both NULL for Order|Make; exactly one set otherwise+);+CREATE INDEX "planningAction_companyId_idx" ON "planningAction" ("companyId");+CREATE INDEX "planningAction_assignee_idx" ON "planningAction" ("companyId", "assignee");+CREATE INDEX "planningAction_item_loc_idx" ON "planningAction" ("companyId", "itemId", "locationId");+CREATE INDEX "planningAction_status_idx" ON "planningAction" ("companyId", "status");+-- Deterministic regen identity (diff-write): one non-terminal action per+-- (item, location, type, period, target document)+CREATE UNIQUE INDEX "planningAction_natural_key_idx" ON "planningAction"+ ("companyId", "itemId", "locationId", "type", "periodId",+ COALESCE("purchaseOrderLineId", "jobId", ''))+ WHERE "status" <> 'Actioned';+```++Ownership ladder (tree: **company default → location → location-specific item group → item**) + the tolerance scalar:++```sql+ALTER TABLE "itemPlanning" ADD COLUMN "responsibleEmployee" TEXT REFERENCES "user"("id"); -- per item+location (most specific leaf)+ALTER TABLE "location" ADD COLUMN "responsibleEmployee" TEXT REFERENCES "user"("id"); -- per location+ALTER TABLE "companySettings" ADD COLUMN "defaultResponsibleEmployee" TEXT REFERENCES "user"("id"); -- company default (all)+ALTER TABLE "companySettings" ADD COLUMN "rescheduleToleranceDays" INTEGER NOT NULL DEFAULT 7+ CHECK ("rescheduleToleranceDays" >= 0); -- negative would make every gap actionable++-- The "location > item group" tier. Item-group ownership is LOCATION-SPECIFIC — the+-- same group can have a different owner at each location — so it is NOT a column on+-- itemPostingGroup; it is a sparse per-(location, group) assignment table (the printer+-- AssignmentsCard tree: location default → per-work-center override, here location →+-- per-item-group override). Rows exist only for configured cells.+CREATE TABLE "itemPostingGroupResponsibility" (+ "id" TEXT NOT NULL DEFAULT id('pgr'),+ "companyId" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "itemPostingGroupId" TEXT NOT NULL,+ "responsibleEmployee" TEXT REFERENCES "user"("id"),+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ -- Composite-FK prerequisites (verified 2026-09-11): "location" already has+ -- UNIQUE ("id","companyId") (20260905132037_job-operation-batching.sql), but+ -- "itemPostingGroup"'s PK is ("id") ALONE (parts.sql:69) — the migration must first+ -- add an idempotent UNIQUE ("id","companyId") on itemPostingGroup or this FK fails.+ CONSTRAINT "itemPostingGroupResponsibility_location_fkey"+ FOREIGN KEY ("locationId", "companyId") REFERENCES "location"("id", "companyId") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_group_fkey"+ FOREIGN KEY ("itemPostingGroupId", "companyId") REFERENCES "itemPostingGroup"("id", "companyId") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_unique" UNIQUE ("companyId", "locationId", "itemPostingGroupId")+);+```++`itemPostingGroupResponsibility` has RLS **explicitly enabled**+(`ALTER TABLE ... ENABLE ROW LEVEL SECURITY;` — policies are inert without it) plus the+four standard policies (SELECT via `get_companies_with_employee_role()`; writes via+`settings_update`, since it is configured on the settings screen).++`planningAction` gets the four standard RLS policies — SELECT via+`get_companies_with_employee_role()`, writes via `production_*`/`purchasing_*` (mirroring+the two planning pages). Any view surfacing `itemPostingGroup`/`location`/`itemPlanning`+is DROP/recreated with `SELECT *` to pick up the new column (per the view-redefinition+convention).++## P1.3 Ownership resolution (the inheritance ladder)++`responsibleEmployee` for an item+location resolves **most-specific first**. Drawn as a+tree it is **all → location → item group**, with a per-item leaf override on top (and the+per-message assignee override on top of that):++```text+itemPlanning.responsibleEmployee -- this item at this location (leaf override)+ ?? itemPostingGroupResponsibility[location, group] -- the item's group AT THIS LOCATION+ ?? location.responsibleEmployee -- this location+ ?? companySettings.defaultResponsibleEmployee -- company default (all, the root)+ ?? NULL -- Unassigned+```++- `itemPostingGroupId` lives on **`itemCost`** (not `item`), so the resolver joins+ `item → itemCost.itemPostingGroupId`, then looks up+ `itemPostingGroupResponsibility` by `(companyId, locationId, itemPostingGroupId)` — the+ item-group tier is **location-specific** (same group, potentially different owner per+ location).+- It is a **hierarchical inheritance tree, not a free classification matrix.** Although+ the item-group tier is keyed by `(location, group)`, it is the exact shape of the+ printer `AssignmentsCard` tree (location default → per-work-center override): a **sparse**+ set of configured cells that each fall back up the tree, resolved by one shared+ function. This is deliberately different from the removed N×M posting-group matrix+ (`20260229000000_drop-posting-groups.sql`), which was an independent customer-type ×+ item-group cross-product with no inheritance. Here every tier inherits from the tier+ above and returns the first non-null.+- The engine stamps the resolved value onto each `planningAction.assignee` at write time.+ A human reassignment (P1.7) sets `assigneeOverridden = true`; subsequent regens leave+ that row's assignee alone.++One **unified** `responsibleEmployee` covers both buy and make — the item's+`replenishmentSystem` decides which worklist (purchasing vs production) an action shows+on; the owner is the same person either way. Configured in a new settings screen cloned+from the printer `AssignmentsCard` (P1.7).++## P1.4 Engine changes (`runMrp`)++`runMrp` already computes period-phased net requirements per (item, location). Phase 1+adds a generation step that **diff-writes** `planningAction` rows in **its own atomic+Kysely transaction, immediately after the Phase-7 transaction commits** (it reads the+planning RPCs, which see only committed data, so it cannot live inside Phase-7 itself).+A generation failure **propagates to the caller** — `runMrp` reports the run failed+rather than succeeding with stale actions; the already-committed forecasts are correct+and the actions self-heal on the next successful run. For each (item, location, period):++- **No open supply covers the net requirement** → **`Order`** (Buy item) or **`Make`**+ (Make item). `suggestedQuantity` = the lot-sized reorder quantity (the same number the+ grid shows today, via the shared sizing function — P1.8 "sizing home"); `suggestedDate`+ = the need date; `supplierId` = preferred supplier for Buy.+- **An open PO-line/job covers it on the wrong date**, gap **strictly greater than**+ `rescheduleToleranceDays` (a gap ≤ tolerance is suppressed; the same `>` comparison is+ used everywhere — engine, tests, acceptance) → **`Expedite`** (needs to be earlier) or+ **`Defer`** (later). `suggestedDate` = the recommended new date; the target ref points+ at the open document.+- **An open order's quantity no longer matches** the requirement (after lot/order-multiple+ rounding) → **`Increase`** or **`Decrease`**.+- **An open order has no remaining requirement** → **`Cancel`**.+- **One action per target document.** Date and quantity rules can both match the same+ open PO-line/job; the engine emits only the **single highest-priority** action per+ target: **Cancel** (no remaining requirement — mutually exclusive with the rest) →+ **Expedite/Defer** (date) → **Increase/Decrease** (quantity). A target needing both a+ date and a qty change gets the date action; the qty change surfaces on a later run+ once the date is fixed (SAP folds qty into reschedule the same way). This is MRP-v2's+ "single highest-priority message on the line" rule applied to Phase 1.++Each row carries the resolved assignee (P1.3), the `reason`/`policyName`/`triggerValues`+attribution (computed by the sizing logic, discarded today), the `isASAP` urgency flag+(start/need date already past), and `requiresManualAction` (target already committed —+P1.5).++**Diff-write, never delete-and-recreate** (assignment + dismissal state must survive a+run). On the natural key `(item, location, type, period, target document)`:++- a matched **Open** row is **updated in place** (suggested qty/date/reason refreshed;+ `assignee` re-resolved only when `assigneeOverridden = false`);+- a matched **Dismissed** row stays dismissed **unless** the suggestion changed materially+ (qty beyond rounding, or date beyond `rescheduleToleranceDays`), in which case it+ re-opens;+- an unmatched **Open** *or* **Dismissed** row whose need has vanished is **deleted**+ (retired) — a dismissal suppresses a *persisting* need; once the need disappears the+ row must not linger, or its natural key would block a fresh Open row if the same need+ returns later. A returning need is a new situation and re-surfaces as a new Open row;+- **Actioned** rows are terminal and ignored — if the same need recurs, a fresh row is+ created.++Two consecutive unchanged runs are therefore idempotent (no churn of assignments or+dismissals). The current unconditional `supplyForecast` delete stays as-is for now+(Phase 2 removes it); the live `quantityToOrder` SQL suggestion is superseded on the+suggestion path (P1.6) while the weekly projection columns (`week1…weekN`) stay live.++## P1.5 Acting on a message++The `planningAction` row is a **recommendation**; the existing owning subsystem executes+it. No new execution engine.++| Type | On apply |+|---|---|+| **Order** | Reuse the existing `planning.update` `"order"` path (group by supplier+period, find-or-create a `Planned` PO, merge lines); stamp the assignee onto the PO. |+| **Make** | Reuse the existing production `planning.update` job-creation path. |+| **Expedite / Defer** | Uncommitted target — PO line: update `requiredDate`. Job: update the **job's demand target** via `updateJob({ dueDate: suggestedDate })`, then `notifyScheduleInputsChanged(companyId, "reorder", reason, jobId)` so the scheduler re-plans. Never `updateJobOperationDueDate` (that pins an *operation* need-by and sets `manuallyScheduled` — a different input) and never direct `jobOperation` date writes. |+| **Increase / Decrease** | Uncommitted — update `purchaseQuantity` (PO) or the job qty via existing services. |+| **Cancel** | Uncommitted — cancel/remove the PO line, or cancel the job, via existing services. |++**Commitment gate.** A change action's target may be **committed** — a PO already sent to+the supplier, or a job already released to the floor. Then the action is flagged+`requiresManualAction = true`: the message still surfaces the recommendation ("this sent+PO should pull in to Sep 12") but **does not silently edit** the document. Acting on it+**navigates the buyer to the PO/job** to handle through the existing workflow (reopen ++renegotiate + notify supplier); the UI shows **"Review on PO/Job"** instead of one-click+apply. An **automated reopen + supplier-notification / change-order flow is explicitly+deferred** — a separate feature.++**Apply binds to the persisted action (IDOR guard).** The apply route receives only a+`planningActionId`. The server loads the `planningAction` by **id + companyId**, requires+`status = 'Open'`, and executes from the row's **stored** type, target reference, and+proposal values — never from client-supplied targets or quantities. Mismatched or+non-Open requests are rejected; every target lookup and mutation is `companyId`-scoped.++Applied → the row flips to **`Actioned`** (next run won't recreate it). A buyer may also+**`Dismiss`** (won't recur until the underlying need changes materially). Both are+available in bulk.++> Commitment-gate facts (verified): "sent to supplier" = `isPurchaseOrderLocked(status)`+> (`PURCHASE_ORDER_LOCKED_STATUSES` = To Receive / To Receive and Invoice / To Invoice /+> Completed / Closed, `purchasing.models.ts`). Do **not** gate on `orderDate` —+> `insertPurchaseOrder` defaults it to today, so it is set even on freshly planned POs+> and would flag every one `requiresManualAction`. Jobs are committed at status+> `Ready` or later (`Ready`/`In Progress`/`Paused`); `Draft`/`Planned` are uncommitted.+> A reopen path exists (`reopenPurchaseOrderAsRevision`) for the manual flow.++## P1.6 Noise gating++A single company-level **`rescheduleToleranceDays`** (default **7** = one weekly bucket)+gates Expedite/Defer. **Canonical boundary: a message fires only when the date gap is+strictly greater than the tolerance (`gap > rescheduleToleranceDays`); a gap ≤ tolerance+is suppressed.** The same comparison is used in the engine, the tests, and the acceptance+criteria — at exactly 7 days, nothing fires. The column carries a `CHECK (>= 0)` (a+negative value would make every gap actionable) and the settings mutation validates+`0–365`.+Because Carbon already buckets planning by week, sub-week noise is invisible anyway. **No+separate quantity dampener in Phase 1** — Carbon's existing `orderMultiple`/`lotSize`/+min-max-OQ rounding absorbs trivial qty deltas; a dampener is a later add if churn+appears. (In/out split and per-item tolerance overrides are later refinements.)++## P1.7 UI++Extend the **two existing planning pages** — no new module or page. Files:+`apps/erp/app/routes/x+/{purchasing,production}+/planning.tsx`,+`apps/erp/app/modules/{purchasing,production}/ui/Planning/`.++- **Planning pages:** keep the live 48-week projection grid; the suggestion/action column+ now reads persisted `planningAction` rows. New columns: **action type**, **suggested+ date/qty**, **reason** (from `triggerValues`), **assignee**, **status**, urgency flag.+ Each row's primary control is **Apply** (one-click; bulk via the existing+ multi-select) — except `requiresManualAction` rows, which show **"Review on PO/Job"**+ and navigate.+- **Filters:** **assignee** (default *"my actions"* = current user — the buyer's+ cockpit), plus action type and status. **Bulk assign** and **bulk accept/dismiss** via+ the existing multi-select.+- **Assignment control:** the existing **`Assignee`** component per row, pre-filled from+ the resolved `responsibleEmployee`, reassignable inline (sets `assigneeOverridden`).+- **Settings — one new screen** cloned from the printer `AssignmentsCard`+ (`settings/ui/Printing/`): a **company-default** row, a list of all **locations**, and a+ list of all **item groups**, each with an `Employee` picker and an inherited-placeholder+ ("inherits {default}") when unset. Per-**item** override lives on the item's existing+ **Planning tab** (`responsibleEmployee`).+- **Deferred:** a unified cross-module "all my actions" cockpit (each page filtered to the+ user already is their queue).++Suggestions are **as-fresh-as-the-last-run** (3-hour cron + the existing manual+"Recalculate" button), not recomputed per page load — the correct ERP model and the+prerequisite for persistence/assignment.++## P1.8 Phase 1 Design Decisions++| Decision | Choice | Rationale |+|---|---|---|+| Persistence | **New focused `planningAction` table** (not the Phase-2 `plannedOrder` lifecycle) | Assignment + dismissal require persistence; the full planned-order lifecycle is deferred. All action types in one table so the worklist is uniform. |+| Firm lifecycle | **None in v1** | Carbon converts a suggestion straight into a real `Planned` PO/job; no unfirmed tier needed for action messages. Planned→Firm→Released is Phase 2. |+| Action enum | **`Order\|Make\|Expedite\|Defer\|Cancel\|Increase\|Decrease`** (directional, user-facing) | Direction-in-the-type reads best for a buyer (SAP/D365/Epicor); Increase/Decrease included per Brad. Advisory/warning types excluded (actionable-only). |+| Change-action source | **Real open POs/jobs vs net requirement** | SAP's reschedule/cancel-on-firmed-receipt model; needs no planned-order layer. |+| Assignment | **Unified `responsibleEmployee` inheritance tree** all → location → location-specific item group → item, + per-row assignee override | Auto-routes on day one (SAP MRP-controller / Epicor Buyer-ID). The item-group tier is location-specific (sparse `itemPostingGroupResponsibility` table), mirroring the printer AssignmentsCard tree — an inheritance hierarchy, not the removed N×M classification matrix. |+| Acting | **Recommendation; existing subsystem executes.** Apply on uncommitted supply; navigate on committed | Committed = external commitment (sent PO / released job); silent edits there are wrong. Change-order/notify automation deferred. |+| Noise gating | **One company `rescheduleToleranceDays` (7)**, no qty dampener | 80/20 — date reschedules are the dominant noise; qty deltas already partly rounded. |+| Suggestion source of truth | **Persisted `planningAction`**; keep live projection columns | Grid and worklist can't disagree; refreshes per run (assignment prerequisite). |+| Reorder-sizing home | **Pure TS function shared by engine + client** (four existing policies) | The engine must produce the Order/Make quantity the grid shows; today the logic is duplicated in SQL (`calculate_quantity_to_order`) + client (`calculateOrders`). Aligns with the Phase-2 `computePlannedOrderQuantity` decision; POQ not required for Phase 1. |+| UI | **Extend the two existing planning pages** + one printer-style settings screen | Copy precedent; no new module. |++## P1.9 Relationship to the Phase 2 planned-order model++Phase 1 is forward-compatible with the `plannedOrder` design below:++- Phase 2's `plannedOrder.exceptionType` (`Release/Expedite/DeExpedite/Cancel/…`) is the+ same action vocabulary; Phase 1's `planningActionType` uses user-facing names for the+ same concepts (`Order/Make` ≈ `Release` + planned-order generation; `Defer` ≈+ `DeExpedite`).+- When Phase 2 lands the cascade + lifecycle, a `planningAction` can gain an optional+ `plannedOrderId` reference (an Order/Make action becomes "release this planned order"),+ while change actions keep targeting real open documents. The assignment ladder,+ worklist, filters, and acting-on-messages built in Phase 1 are reused unchanged.+- Nothing in Phase 1 has to be torn out for Phase 2.++## P1.10 Phase 1 Acceptance Criteria++- [ ] An MRP run writes `planningAction` rows: a Buy item short of coverage yields an+ **Order** (qty = the grid's lot-sized quantity, `supplierId` = preferred); a Make+ item yields a **Make**.+- [ ] An open PO due later than the net requirement (gap > `rescheduleToleranceDays`)+ yields an **Expedite** with `suggestedDate`; an open PO due too early yields a+ **Defer**; both reference the `purchaseOrderLineId`.+- [ ] An open order whose qty falls short / exceeds the requirement yields **Increase** /+ **Decrease**; an open order with no remaining requirement yields **Cancel**.+- [ ] A date mismatch **≤** `rescheduleToleranceDays` yields **no** message; a mismatch+ **strictly greater** fires (boundary test at exactly the tolerance value).+- [ ] `responsibleEmployee` resolves item → item-group → location → company; the engine+ stamps the resolved user as `assignee`; an unset ladder leaves the action+ Unassigned. Setting the item-group employee routes all that group's actions to+ them; a per-item override wins.+- [ ] Reassigning an action in the UI sets `assigneeOverridden`; the next run does not+ overwrite that assignee, but still refreshes suggested qty/date.+- [ ] Two consecutive runs with unchanged inputs produce **byte-identical**+ `planningAction` rows (diff-write); a **Dismissed** action stays dismissed across a+ run unless its suggestion changes materially; an **Actioned** action is not+ recreated.+- [ ] Applying an **Order** on an uncommitted plan creates/merges a `Planned` PO (the+ existing behavior) and flips the action to **Actioned**; applying **Expedite** on a+ Draft/Planned PO line edits its `requiredDate`.+- [ ] A change action whose target PO is already **sent** is flagged+ `requiresManualAction`; the worklist shows **"Review on PO"** and navigates to the+ PO instead of editing it.+- [ ] The planning pages render the new columns; the **"my actions"** filter defaults to+ the current user; bulk apply/assign/dismiss work via multi-select.+- [ ] The settings screen lists company default + every location + every item group with+ inherited-placeholders; the item Planning tab has a `responsibleEmployee` field.+- [ ] Gates: `pnpm --filter @carbon/ee test` (action-message generation + resolver ++ sizing) green; scoped ERP typecheck green; `pnpm run generate:types` committed;+ browser verification of the worklist + settings on the satellite dataset.++## P1.11 Phase 1 Open Questions++> All resolved with Brad 2026-09-08 (run record:+> `.ai/runs/2026-09-08-mrp-planning-actions.md`). Kept as the decision record.++- [x] **Scope vs the full MRP-v2 build?** — **Phased.** Ship action messages ++ assignment first (Phase 1); defer the planned-order cascade/lifecycle/capacity/+ simulation to Phases 2+ of this spec.+- [x] **Persistence: full plannedOrder lifecycle or focused table?** — **Focused+ `planningAction` table, no Firm lifecycle**, diff-write, all types persisted.+- [x] **Assignment axis?** — **Unified `responsibleEmployee` inheritance tree**+ all → location → **location-specific** item group → item + per-row assignee+ override (2026-09-09 refinement: the item-group tier is per-location, stored in a+ sparse `itemPostingGroupResponsibility` table — a printer-style inheritance tree,+ not the removed N×M matrix).+- [x] **Enum names + Increase/Decrease in v1?** — **`Order|Make|Expedite|Defer|Cancel|+ Increase|Decrease`**; Increase/Decrease **included**.+- [x] **Advisory exceptions in v1?** — **Actionable-only**; urgency is a flag, conditions+ in `reason`/`triggerValues`; warning channel deferred.+- [x] **Tolerance?** — **One company `rescheduleToleranceDays` (7)**, no qty dampener.+- [x] **Acting on committed vs uncommitted supply?** — **Apply on uncommitted; navigate+ ("Review on document") on committed**; automated reopen+notify deferred.+- [x] **Keep or replace the live grid?** — **Keep projection columns; persisted+ `planningAction` is the suggestion source of truth** (refresh per run).+- [x] **UI surface?** — **Extend the two existing planning pages** + one printer-style+ settings screen; unified cockpit deferred.++---++> **Everything below is the Phase 2+ vision** — the full planned-order MRP. Preserved as+> the design record; **not** what ships in Phase 1. Where Phase 1 diverges, §P1 above is+> authoritative.## TLDR@@ -31,7 +478,7 @@ lifecycle.And it goes past parity. Every system in the research runs MRP as a batch reportplanners learn to distrust. Carbon's engine now runs a full company in **~0.3–0.5 s**(`.ai/research/2026-08-12-mrp-findings.md`), lives **in the same Node process and-package as the finite scheduler** (`@carbon/ee/planning`), and sits next to a+package as the finite scheduler** (`@carbon/planning`), and sits next to acustomer-programmable workflow engine and an in-app agent whose data-tool mechanismis already built. v1 therefore ships MRP that is:@@ -71,7 +518,7 @@ from Node via the `@carbon/database/mrp-engine` barrel) is a correct multi-levelexplosion: it computes low-level codes, walks items level-by-level, nets each againston-hand, and explodes the shortfall to children with lead-time offset. But it onlycascades what is already in `grossDemand`, and `grossDemand` is seeded-(`packages/ee/src/planning/mrp/mrp.ts`, Phase 4) from exactly three **actual**+(`packages/planning/src/mrp/mrp.ts`, Phase 4) from exactly three **actual**sources:- `openSalesOrderLines` — sales-order demand@@ -786,7 +1233,7 @@ rows with `forecastMethod = 'suggested'`).## API / Service Changes-**Engine (`packages/ee/src/planning/`)**+**Engine (`packages/planning/src/`)**- New `lot-sizing` in `@carbon/utils`: pure`computePlannedOrderQuantity(netRequirement, policy, params): { quantity, trace }` —@@ -818,7 +1265,7 @@ rows with `forecastMethod = 'suggested'`).hypothetical demand line, `persist: false`; returns `{ promiseDate, planDelta,capacityImpact, estimatedCost, assumptions }`.- All relocated/new value-bearing math stays under `@carbon/checks` coverage- (`packages/ee/src/planning` is already in the TS source set on this branch); no+ (`packages/planning/src` is already in the TS source set on this branch); noscale literals, whole-unit ceils via `round(x, 0, Up)`.**Jobs (`packages/jobs`)**@@ -1095,6 +1542,9 @@ except `api+/planning.what-if.ts`.> All resolved 2026-08-22 (Brad accepted the recommendations). Kept as the decision> record.+>+> **Note (2026-09-08):** the questions in this section belong to the **Phase 2+** vision.+> **Phase 1's** open questions and their resolutions live in **§P1.11**.- [x] **Materialize-on-release vs keep materialize-on-Make?** — **Resolved: trueplanned-order layer.** Real `job`/PO created only on Release; Planned orders are@@ -1206,7 +1656,7 @@ except `api+/planning.what-if.ts`.`PlanningExceptions` digest). Fixed from the code review: `jobId` peg source,`'Transfer'` reserved, working-day date math, `splitIndex` + partial-unique naturalkey, suggested demand projections. Updated all file references to the- `@carbon/ee/planning` extraction. Added the **Deferred** list.+ `@carbon/planning` extraction. Added the **Deferred** list.- 2026-08-22: **Calm-by-default layer** (Brad: "implement the annoyance fixes").New §9 + supporting schema: one-click Release with warnings-only draftinterposition and plain-language Firm prompt (`firmedBy`/`firmedAt`);@@ -1224,3 +1674,51 @@ except `api+/planning.what-if.ts`.with `location.planningTimeFenceDays` as the plant default — SAP/Oracle/Dynamicsall fence per item, and `itemPlanning` already owns the planning-behavior fields(`reorderingPolicy`, accumulation/rescheduling periods).+- 2026-09-08: **Re-scoped into phases** (Brad). The single "game-changer v1" is split+ so the 80/20 slice ships first. Added **§P1 — Phase 1: Planning Action Messages &+ Buyer/Planner Assignment**: a focused persisted `planningAction` table (enums+ `planningActionType` = Order/Make/Expedite/Defer/Cancel/Increase/Decrease,+ `planningActionStatus`), a unified `responsibleEmployee` inheritance ladder+ (item → item-group → location → company; new columns on `itemPlanning`,+ `itemPostingGroup`, `location`, `companySettings`) with per-row assignee override, a+ single `companySettings.rescheduleToleranceDays` (default 7) noise gate, diff-write+ regen, commitment-gated apply (auto-apply on uncommitted supply, "Review on+ document" on sent POs / released jobs), the two existing planning pages extended+ with a "my actions" worklist, and one printer-style ownership settings screen. All+ Phase-1 open questions resolved with Brad (§P1.11). The prior "game-changer v1"+ (planned-order cascade + Planned→Firm→Released lifecycle, pegging, continuous regen,+ rough-cut capacity, what-if/CTP, self-explaining plan, programmable release, §9+ calm-by-default) is retained below as **Phases 2+**, deferred. Research:+ `.ai/research/mrp-planning-actions.md`; run record:+ `.ai/runs/2026-09-08-mrp-planning-actions.md`.+- 2026-09-09: **Ladder refinement** (Brad): the item-group tier is now+ **location-specific** — the tree is **all → location → item group** (per-item leaf ++ per-message assignee still on top). Item-group ownership moves off a column on+ `itemPostingGroup` into a sparse `itemPostingGroupResponsibility` table keyed+ `(companyId, locationId, itemPostingGroupId)`, mirroring the printer AssignmentsCard+ inheritance tree. Updated §P1.2 (data model), §P1.3 (resolver), §P1.8, §P1.11.+- 2026-09-11: **CodeRabbit review round (PR #1601) folded in.** Generation runs in its+ own atomic transaction after Phase-7 and failures **propagate** (no swallow); **one+ action per target** precedence (Cancel → Expedite/Defer → Increase/Decrease); vanished+ **Dismissed** rows are deleted (retired) so the natural key can't block a returning+ need; tolerance boundary fixed as strictly `>` with `CHECK (>= 0)` + 0–365 validation;+ commitment gate keys on `isPurchaseOrderLocked(status)` only (NOT `orderDate`, which+ defaults to today on insert); apply **binds to the persisted action** by id+companyId+ with `status='Open'` (IDOR guard); job Expedite/Defer = `updateJob({dueDate})` ++ `notifyScheduleInputsChanged("reorder")`, never operation-date writes;+ `itemPostingGroup` needs `UNIQUE ("id","companyId")` before the responsibility FK+ (verified: PK is `("id")` alone); explicit `ENABLE ROW LEVEL SECURITY` on+ `itemPostingGroupResponsibility`; scheduled runs' `userId: "system"` is a real seeded+ user row (`20230123004317_companies-rls.sql`).++- **2026-09-11**: `demandProjection` now DOES gain a column — `consumedQuantity`+ (forecast consumption, migration `20261006130001`), superseding this spec's+ "demandProjection gains no columns" scope note (§ suggested projections, ~line+ 1230; that section's own scope is unchanged — suggestions still write ordinary+ rows). Design + rationale: `.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md`.+- **2026-10-04**: Phase 1 (§P1, planning action messages + responsible-employee+ assignment) implemented on `mrp-action-suggestions` (PR #1601; plan+ `.ai/plans/2026-09-08-mrp-planning-actions.md` 12/12). The same branch also ships the+ planning horizon / time fence (`.ai/plans/2026-10-01-planning-horizon.md`) and a+ company-chosen daily MRP run time. Phases 2+ are unchanged and not started, so this+ spec stays out of `implemented/`.diff --git a/.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md b/.ai/specs/implemented/2026-09-11-demand-forecast-consumption.mdnew file mode 100644index 0000000000..ba4967420a--- /dev/null+++ b/.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md@@ -0,0 +1,315 @@+# Demand Forecast Consumption++> Status: implemented (PR #1601; plan `.ai/plans/2026-09-11-demand-forecast-consumption.md` complete, 10/10 tasks)+> Author: Claude (feature run `.ai/runs/2026-09-11-demand-forecast-consumption.md`)+> Date: 2026-09-11+> Research: `.ai/research/demand-forecast-consumption.md`+> Audit: `.ai/runs/2026-09-11-demand-forecast-consumption-audit.md`++## TLDR++Actual demand (open sales order lines and job-material lines) will **consume** the+authored demand forecast (`demandProjection`) so the two never double-count: per weekly+bucket, MRP demand becomes *actuals + unconsumed forecast remainder* — which equals+`max(forecast, actuals)` when both land in the same week — with a bucket-granular+**backward-then-forward consumption window** so an order landing in a zero-forecast week+consumes the nearest adjacent forecast. Consumption is computed **regeneratively inside+`runMrp`** (nothing to un-consume; cancelled orders and edited forecasts self-heal on the+next run, no sales↔production communication required) and persisted as+`demandProjection.consumedQuantity`, which every read path (both planning RPCs,+`generatePlanningActions`, inventory quantities, the item planning chart) subtracts —+one implementation, read everywhere.++**The audit refuted the premise that same-week netting already works.** Today forecast+and actuals are *summed* in four independent places; 10 forecast + 10 SOs = 20 demand.+This spec fixes the same-week case and the gap case in one mechanism.++## Problem Statement++`demandProjection` (the authored forecast) and actual demand are both fed to MRP at+face value and **added** (audit §3):++- `mrp.ts:442-515` — projections and SO lines write to the same `grossDemand` key additively.+- `get_production_planning` / `get_purchasing_planning` `demand_data` CTEs — `demandActual + demandForecast + demandProjection`, summed.+- `planning-actions.ts:529-574` — the same union in Node for change actions.+- `get_inventory_quantities` — sums actual + forecast (and omits projections entirely).++Concretely, for one item/location/week with forecast 10:++| Open SOs | Demand today | Correct |+|---|---|---|+| 10 | **20** | 10 |+| 5 | **15** | 10 |+| 12 | **22** | 12 |++And the gap case: forecast `0, 10, 0, 10` across weeks 1–4; an SO for 10 due in week 3+adds 10 on top of the untouched week-2 and week-4 forecasts — the order that *is* the+forecasted demand, counted twice. Because the planning RPCs project a **cumulative**+running balance, a double count in week 3 depresses the projected balance for every+subsequent week — over-ordering across the whole horizon, not a one-week blip.++Make-to-stock jobs are *not* part of the problem: they are supply, netted once by+`explodeBom`'s running balance (audit §4), and the SO↔linked-job dedup already works.+What's missing is exclusively forecast-vs-actual-demand consumption.++## Proposed Solution++### The algorithm (industry-standard forecast consumption, bucket-granular)++A pure function `consumeForecast` in `packages/planning/src/mrp/forecast-consumption.ts`:++```+Inputs, per (itemId, locationId):+ forecast: Map<periodIndex, qty> // demandProjection rows within the horizon+ actuals: Map<periodIndex, qty> // consumption quantities (see below)+ window: { backward: B, forward: F } // in periods (weeks)++Walk actuals in ascending period order. Each actual quantity consumes forecast:+ 1. its own period first,+ 2. then backward: p−1, p−2, … p−B (nearest first),+ 3. then forward: p+1, … p+F (nearest first),+decrementing remaining forecast as it goes. Excess actual beyond reachable+forecast consumes nothing further (it simply stands as real demand).++Outputs:+ consumed: Map<periodIndex, qty> // per forecast period, how much was consumed+ remainder: Map<periodIndex, qty> // forecast − consumed, floored at 0+```++Net demand per period = `actuals[p] (demand quantity) + remainder[p]`.++Properties:+- Same-bucket cases reduce to `max(forecast, actuals)`: 10F/10SO→10, 10F/5SO→10, 10F/12SO→12.+- Gap case (F = 0,10,0,10; SO 10 due wk3, B≥1): wk2 forecast fully consumed; demand = 10 (SO, wk3) + 10 (forecast, wk4). No double count, and the still-unmaterialized second month's forecast survives.+- `B = F = 0` degrades to strict same-bucket netting.+- Deterministic: earlier actuals claim forecast first; backward always precedes forward (SAP mode 2 / Oracle / SyteLine consensus — a "late" order belongs to the just-passed forecast).+- Past-due actuals are already dumped into period[0] by `findPeriod`, so they consume the current week's forecast then forward — no special-casing.+- Past forecast (projection rows whose `periodId` predates the horizon) is already inert in both the engine and the RPCs (periodId never matches a horizon period); it stays that way — self-expiring, no SAP-style cleanup job.++### Where it runs and how it propagates (compute once, read everywhere)++**Computed in `runMrp` Phase 4** (before the Phase-4.5 supersession redirect):++1. Build the actuals maps first (SO + job-material loops, as today).+2. Run `consumeForecast` per (item, location).+3. Add the **remainder** (not the raw `forecastQuantity`) to `grossDemand`; projection+ contributor rows in `demandForecastSource` carry the remainder (a fully consumed+ projection contributes no row).+4. In the existing atomic Phase-7 transaction, persist per-row+ `demandProjection.consumedQuantity` (rounded at internal scale via `round()` from+ `@carbon/utils` at the persist boundary; horizon rows only, others untouched).++**Read paths subtract, never re-implement.** Every reader changes its projection term+from `forecastQuantity` to `GREATEST("forecastQuantity" - "consumedQuantity", 0)`:++| Read site | Change |+|---|---|+| `get_production_planning` `demand_data` (fork of `20260715195226`) | projection arm nets |+| `get_purchasing_planning` `demand_data` (fork of `20260831190142`) | projection arm nets |+| `planning-actions.ts:529-574` union | select both columns, net in TS |+| `get_inventory_quantities` (fork of `20260716142907`, the newest def) | **add** net projection arm (fixes its existing omission of projections) |+| `getItemDemand` (`items.service.ts:647`) | add net projections (fixes the planning-chart blind spot) |++Freshness note: `demandActual` is already an MRP output (rebuilt each run, cron every+3 h + manual Recalculate), so the read paths are already run-stale for actuals. Netting+the projection arm with a run-stamped `consumedQuantity` makes the projection term+*consistent* with the actual term rather than fresher than it. A projection authored+between runs counts at face value until the next run — the same grace it gets today.++### What consumes, what doesn't++| Source | Role |+|---|---|+| Open SO lines (`openSalesOrderLines`) | **consume**, at the line's *pre-job-dedup* open quantity (new view column `quantityToConsume` — see Data Model). Demand contribution stays the deduped `quantityToSend`. Without this, an MTO order fully covered by its linked job would consume nothing and its forecast would drive phantom stock production. |+| Open job-material lines (`openJobMaterialLines`) | **consume** projections on their own (component) item — real dependent demand consuming a component-level forecast. |+| Make-to-stock jobs (`openProductionOrders`) | **never consume** — they are supply, already netted once by the running balance (SAP/Oracle/Epicor consensus: production is relieved on the supply side). |+| BOM-exploded *planned* dependent demand | **does not consume** component projections in v1 (SAP strategy-40 default; strategy-70-style dependent-demand consumption is a possible later opt-in). |++Consumption is strictly per (itemId, locationId) — an order at location A never consumes+a forecast at location B (matches the tables' keys and every surveyed vendor).++### Configuration (flat, company-level)++Two integer columns on `companySettings`, following `rescheduleToleranceDays` precedent:++- `forecastConsumptionBackwardPeriods` — default **4** (bridges monthly-granularity forecasts authored on the weekly grid; Oracle's guidance "backward ≈ one bucket span" scaled to the common author-monthly pattern)+- `forecastConsumptionForwardPeriods` — default **1** (early orders; every vendor warns against large forward windows)++`0/0` = strict same-week netting. No per-item override, no matrix (per the no-matrix-config+principle; SyteLine/Epicor per-item overrides are the request to watch for later).+Surfaced in the same settings UI as `rescheduleToleranceDays`.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Netting formula | actuals + unconsumed remainder (≡ `max` same-bucket) | The user's three cases; APICS/SAP/Oracle/SyteLine consensus (research §Pattern 1) |+| Compute timing | Regenerative, inside `runMrp`; no stored consume/unconsume events | Self-healing with zero deconsumption machinery (SAP-dynamic/Fusion/D365 pattern); fits Carbon's wipe-and-rewrite MRP outputs |+| Window granularity | Whole periods (weeks), not days | Forecast is bucket-native (`periodId`); day windows are the documented Epicor/SyteLine footgun class (research §Pattern 4) |+| Search order | Own bucket → backward → forward, nearest-first, earlier actuals first | Cross-vendor consensus; deterministic |+| Persistence | `demandProjection.consumedQuantity NUMERIC NOT NULL DEFAULT 0`, MRP-written | One implementation feeds all five read sites; enables "consumed" display in the forecast grid; PK (itemId, locationId, periodId) already matches the consumption grain. Deliberately supersedes the MRP-v2 spec's "demandProjection gains no columns" scope note |+| Consumption vs supersession order | Consume **before** the Phase-4.5 redirect (authored item identity) | The read path does not redirect projections/actuals at all today (audit §7); pre-redirect consumption keeps engine and grid consistent. Successor-aware consumption lands with the (pre-existing, separately tracked) read-path redirect work |+| Current-week forecast | Kept, consumed normally — no D365-style drop-today rule | Week 0 is 0–6 days out; job-shop orders due this week were often booked weeks ago and consume it anyway. A drop-current-week knob can come later if wanted |+| SO consumption quantity | `quantityToSend` pre-job-dedup (`quantityToConsume` view column) | MTO correctness (above). Partially-shipped lines under-consume until their week rolls out of horizon — bounded wobble, accepted for v1 (SAP solves it with persisted goods-issue reduction; not worth the state) |+| Heuristic 1 (multi-tenancy) | No new tables; new columns on existing RLS'd tables | `demandProjection` + `companySettings` already carry `companyId` + RLS |+| Heuristic 2/6 (service/module shape) | No new service files; changes live in `production.service.ts`, `items.service.ts`, `@carbon/ee` planning | Existing module layout |+| Heuristics 3/4/5 | No new tables/routes/forms except settings fields on the existing settings form | Existing `ValidatedForm` + action; `settings` permission scope unchanged |+| Heuristic 7 (compat) | Additive columns with defaults; view gains a column; RPC signatures unchanged | Zero-downtime; old readers unaffected |++## Data Model Changes++One migration (idempotent per lessons; randomized HHMMSS timestamp):++```sql+-- 1. Consumption state (MRP-written, derived — never user-authored)+ALTER TABLE "demandProjection"+ ADD COLUMN IF NOT EXISTS "consumedQuantity" NUMERIC NOT NULL DEFAULT 0;++-- 2. Company-level consumption window+ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "forecastConsumptionBackwardPeriods" INTEGER NOT NULL DEFAULT 4,+ ADD COLUMN IF NOT EXISTS "forecastConsumptionForwardPeriods" INTEGER NOT NULL DEFAULT 1;++-- 3. openSalesOrderLines: expose the pre-job-dedup open quantity+-- (fork newest def from 20260811123619_widen-sales-production-scale.sql;+-- DROP VIEW IF EXISTS + recreate WITH (security_invoker=true);+-- add: sol."quantityToSend" AS "quantityToConsume" alongside the existing+-- job-deduped "quantityToSend" CASE expression)++-- 4. get_production_planning / get_purchasing_planning: fork newest defs+-- (20260715195226 / 20260831190142); demandProjection arm becomes+-- GREATEST(dp."forecastQuantity" - dp."consumedQuantity", 0).++-- 5. get_inventory_quantities: fork newest def (20260316000000); ADD the+-- net-projection arm to its demand CTE (currently omits projections).+```++No RLS changes (existing table policies cover the new columns). No new enums.+`pnpm run generate:types` after; types propagate via `Awaited<ReturnType>` chains.++## API / Service Changes++- **`packages/planning/src/mrp/forecast-consumption.ts`** (new): pure+ `consumeForecast(forecast, actuals, window)` + types. Sibling+ `forecast-consumption.test.ts` (vitest, `pnpm --filter @carbon/ee test`).+- **`packages/planning/src/mrp/mrp.ts`**: Phase 4 reordered — actuals loops first+ (also accumulating per-key `quantityToConsume`), then projections loop runs+ `consumeForecast` per (item, location) and adds remainders to `grossDemand` /+ contributors; reads the two window settings from `companySettings` once per run;+ Phase 7 persists `consumedQuantity` (batched update inside the existing transaction).+ Also fix the vestigial `netDemand` name and stale migration-filename comment flagged+ by the audit while in there.+- **`packages/planning/src/mrp/planning-actions.ts`**: projection query selects+ `forecastQuantity, consumedQuantity`; union adds the `GREATEST` diff.+- **`apps/erp/app/modules/items/items.service.ts` `getItemDemand`**: add net+ projections so the item planning chart agrees with the planning grid.+- **`upsertDemandProjections` needs no change**: PostgREST upserts only update the+ columns present in the payload, so `consumedQuantity` survives a re-authored+ forecast (and keeping it until the next run is *more* accurate than resetting —+ the remainder stays netted). Zero-quantity weeks delete the row, which correctly+ deletes its consumption state with it.+- **Settings action/validator** for the two new fields (existing settings form pattern).++## UI Changes++- **Settings** (wherever `rescheduleToleranceDays` lives): two number fields —+ "Forecast consumption: weeks backward / weeks forward", with help text.+- **`DemandProjectionForm` 52-week grid**: per-cell read-only annotation of consumed+ quantity (e.g. muted "8 consumed" under the input) so a planner can see the forecast+ self-healing. Copy the nearest existing grid-annotation precedent; no new interaction.+- **Planning grids / worklists**: no UI change — they reflect net demand automatically+ via the RPC/union changes.+- i18n: new strings through Lingui extract + `/translate` at commit time.++## Docs / knowledge sync (required by keep-sources-in-sync)++- `docs/content/docs/reference/forecast.mdx` (the agent knowledge base is baked from it) — currently documents the+ additive behavior as intentional; rewrite for consumption (and fix its stale paths).+- `.claude/rules/mrp-system.md` — describe consumption in the run flow.+- MRP v2 spec (`.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md`) — changelog+ note that `demandProjection` now gains `consumedQuantity`, superseding its §scope line.++## As Built++Where the shipped code differs from the design below:++- **One migration, every read path.** `20261006130001_demand-forecast-consumption.sql`+ holds all of it: the two columns, `openSalesOrderLines.quantityToConsume`, and the+ netted `get_production_planning`, `get_purchasing_planning` and+ `get_inventory_quantities`. The last two are forked from the guarded+ `20260925121735_rpc-function-guards.sql` bodies (they open with+ `assert_company_access`), not from the defs named in Data Model Changes.+- **`consumeForecast` lives in `@carbon/planning`** (`packages/planning/src/mrp/forecast-consumption.ts`);+ its tests run with `pnpm --filter @carbon/planning test`, not `@carbon/ee`.+- **The item planning chart nets in the route, not the service.** `getItemDemand`+ returns raw projections; `api+/items.$id.$locationId.forecast.ts` subtracts+ `consumedQuantity` before merging them into the chart.+- **Settings.** The window is the "Forecast Consumption" card on Settings → Planning,+ fields "Look back (weeks)" and "Look ahead (weeks)" (defaults 4 and 1).++Verification (`.ai/runs/2026-09-11-demand-forecast-consumption.md`, Phase 5): unit tests,+plus a real MRP run on a seeded company proving same-week netting (forecast 30 + SO 30+→ 30), a partial forecast (20 + SO 30 → 30), the gap case (an SO reaching back into the+previous week's forecast, no double count), a 0/0 window turning reach-back off, the+settings card and the grid annotation. The run record does not show the MTO-covered+line, the re-saved cell, or the four-surface agreement criteria below exercised one by+one, so their boxes are left unticked.++## Acceptance Criteria++- [ ] Unit (`forecast-consumption.test.ts`): same-bucket 10F/10A→10, 10F/5A→10,+ 10F/12A→12 (net totals); gap `0,10,0,10` + actual 10 in p3 with B=1 → wk2+ remainder 0, wk4 remainder 10; forward-only reach (actual in p1, forecast in p2,+ F=1) consumes; window exhaustion leaves excess actual standing; B=F=0 ≡ per-bucket+ max; two actuals competing for one forecast bucket resolve earlier-period-first;+ actual beyond all forecast in window consumes nothing outside it.+- [ ] After an MRP run with forecast 10 and one open SO of 10 in the same week (no+ stock/supply): production planning grid shows week demand 10, and exactly one+ Make/Order suggestion of 10 for that item.+- [ ] Gap scenario seeded end-to-end (forecast weeks 2 & 4 = 10, SO 10 due week 3):+ total horizon demand for the item is 20 (10 SO + 10 remaining forecast), planning+ actions suggest supply for 20, and `demandProjection.consumedQuantity` = 10 on the+ week-2 row, 0 on week-4.+- [ ] With forecast 10 and SOs totalling 12 in-window: demand 12; no forecast remainder.+- [ ] MTO SO line fully covered by a linked live job still consumes its week's forecast+ (grid demand shows no phantom forecast remainder).+- [ ] Forecast edit grid displays consumed quantities after a run; a re-saved cell+ keeps its consumption (remainder stays netted) until the next run recomputes it.+- [ ] `get_production_planning`, `get_purchasing_planning`, `planningAction` worklist,+ and Inventory quantities agree on the same net demand for the seeded scenarios.+- [ ] `pnpm --filter @carbon/ee test`, scoped typechecks, `pnpm db:migrate` ++ `pnpm run generate:types`, `pnpm db:check:datasets` and `pnpm db:check:backups` all green.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| A read site is missed and grid/worklist disagree (the audit's four-site trap) | High | The five-site table above is the checklist; acceptance criterion pins cross-surface agreement; grep for `demandProjection` at plan time to catch stragglers |+| Staleness between runs (new SO consumes nothing until next run) | Med | Same staleness contract as `demandActual` today (3 h cron + manual Recalculate); documented in the KB doc |+| Partial-shipment under-consumption wobble | Low | Bounded to the current week; self-heals when the week rolls; noted for a future goods-issue-analog refinement |+| Supersession read-path divergence for superseded items | Med (pre-existing) | Not worsened (consumption runs pre-redirect); tracked as the existing read-path redirect gap (audit §7) |+| `consumedQuantity` default backfill on a large `demandProjection` table | Low | `ADD COLUMN ... DEFAULT 0` is metadata-only on PG11+; no rewrite |+| Window defaults wrong for some tenants | Low | Company-settable; `0/0` opt-out; defaults grounded in research |++## Open Questions++> All resolved autonomously (research + codebase precedent) per the declared run mode;+> Brad vetoes at the plan gate before any execution. Items 1–3 are effectively fixed by+> the user's own problem statement; 4–9 are the judgment calls to eyeball.++- [x] Same-bucket semantics? — **Autonomous:** actuals + unconsumed remainder (≡ `max`), exactly the user's three worked cases; APICS consensus.+- [x] Do jobs consume forecast? — **Autonomous:** No — MTS jobs are supply (already netted); job-material lines DO consume component-level projections. Matches the user's "jobs net out" intent and SAP/Oracle/Epicor.+- [x] How do gaps heal? — **Autonomous:** bucket-granular backward(4)-then-forward(1) window; the user's 0/10/0/10 example nets correctly with B≥1.+- [x] Window unit and config surface? — **Autonomous:** whole weeks (periods), two company-level `companySettings` columns, defaults 4/1, no per-item matrix. Alternatives (day windows, per-item overrides) rejected as the documented vendor footgun / config sprawl.+- [x] Recompute vs stored consumption state? — **Autonomous:** regenerative in `runMrp`, persisted only as derived `consumedQuantity` output. Stored consume/unconsume events (Oracle EBS) rejected — deconsumption machinery for no benefit at Carbon's run cadence.+- [x] Where does the net live so all readers agree? — **Autonomous:** `demandProjection.consumedQuantity` + `GREATEST` subtraction at five read sites; supersedes MRP-v2's "no new columns on demandProjection" scope note.+- [x] Which SO quantity consumes? — **Autonomous:** pre-job-dedup `quantityToSend` (new `quantityToConsume` view column); deduped quantity stays the demand driver. Full-sale-quantity (shipment-proof) variant deferred.+- [x] Consumption vs supersession ordering? — **Autonomous:** consume first, on authored identity — keeps engine consistent with the (non-redirecting) read path; successor-aware consumption rides the existing read-path redirect gap.+- [x] Current-week forecast dropped (D365) or kept? — **Autonomous:** kept and consumable; drop rule deferred as a possible future knob.++## Changelog++- 2026-09-11: Created after Phase-0 audit (refuted existing-netting belief) and 4-vendor research; all open questions autonomously resolved for veto at the plan gate.+- 2026-09-11 (plan phase): corrected `get_inventory_quantities` fork source to the true newest def (`20260716142907`); dropped the `upsertDemandProjections` reset — PostgREST upserts preserve absent columns, so consumption state survives re-authoring (deliberately kept until next run).+- 2026-09-11 (execute): approved by Brad; implementation started. Docs correction: the agent-KB forecast doc is generated from `docs/content/docs/reference/forecast.mdx` (edit source + `generate:agent-kb`, per `.claude/rules/agent-knowledge-base.md`), not the kb/ copy directly.+- 2026-10-04: implemented on `mrp-action-suggestions` (PR #1601); moved to `implemented/`. Added As Built: the read paths ship in one migration, `consumeForecast` is in `@carbon/planning`, and the chart nets in its route.diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.mdindex a5985dc573..4c4adbb3e1 100644--- a/.claude/rules/company-backup-restore.md+++ b/.claude/rules/company-backup-restore.md@@ -101,7 +101,14 @@ both use it; `company-backup.ts` re-exports it), exported to app code asCHECK (`sourceType` ↔ which of `jobId`/`salesOrderLineId`/`demandProjectionId`is non-null) made a remapped restore crash — the FK-nulling dangling-ref policyin `buildRowTransforms` nulls a set FK and violates the CHECK. `demandForecast`- is deliberately kept: it has a user-forecast write path and no such CHECK. The+ is deliberately kept: it has a user-forecast write path and no such CHECK.+ `planningAction` is kept too — `Dismissed` and `assigneeOverridden` are the+ planner's own state, not regenerable — even though it has a comparable CHECK+ (`planningAction_change_target_chk`, `20261006130000`: a change action keeps+ its `jobId` or `purchaseOrderLineId`). Its target FKs are nullable with ON+ DELETE CASCADE, so a consistent snapshot never carries a dangling target; a+ remapped restore that did would null the FK and fail that CHECK. The dataset+ wipe (`wipe.ts` `TRANSIENT_MRP_TABLES`) deletes it, which is a different path. Thetwo excluded sets are unioned into `CATALOG_EXCLUDED_TABLES`, which`assertBackupImportable` also skips — an OLDER backup that still carries anexcluded table is not schema drift, its rows are just ignored on load),diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.mdindex eb3e56ebcf..f33ce78bd5 100644--- a/.claude/rules/inventory-system.md+++ b/.claude/rules/inventory-system.md@@ -131,14 +131,16 @@ Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptVal- **`enforcementRule`** + assignment tables — ONE table for storage and sales rules, discriminated by `family` (`20260817143022`/`20260817143512`). Storage-family reads must filter `family = 'storage'`. Lineage: `itemRule` → `customRule` → `storageRule` → merged into `enforcementRule`.`get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL)` — the central-read. Newest definition is `20260713235406_item-ledger-snapshot.sql` (snapshot + delta via-`itemLedgerSnapshot`; `item_id` restricts to one item for detail-page loads). Returns ~52 cols:+read. Newest definition is `20261006130001_demand-forecast-consumption.sql` (the+`20260713235406_item-ledger-snapshot.sql` body — snapshot + delta via `itemLedgerSnapshot`,+`item_id` restricts to one item for detail-page loads — plus a net-projection demand arm:+`GREATEST("forecastQuantity" - "consumedQuantity", 0)` of `demandProjection`). Returns ~52 cols:item identity + material props, planning fields, and quantities `quantityOnHand`, `quantityOnHold`,`quantityRejected` (status-aware: excludes `Rejected`, surfaces `On Hold`), `quantityOnSalesOrder`,`quantityOnPurchaseOrder`, `quantityOnProductionOrder`, `quantityOnProductionDemand`, `demandForecast`,`usageLast30Days`, `usageLast90Days`, `daysRemaining`, plus `storageTypeIds`/`storageUnitIds` arrays.Aggregates from `itemLedger`, open `purchaseOrder(Line)`, `salesOrder(Line)`, `job`/`jobMaterial`,-and `demandForecast`/`demandActual`.+`demandForecast`/`demandActual`, and `demandProjection` net of `consumedQuantity`.Relevant enums: `itemLedgerType`, `itemLedgerDocumentType` (includes `Scrap`,`20260807090400`), `trackedEntityStatus`@@ -156,7 +158,7 @@ Relevant enums: `itemLedgerType`, `itemLedgerDocumentType` (includes `Scrap`,`pol."receivedComplete" = false` (`20260708204214`). A line short-closed via`shortClosePurchaseOrderLine` ("Stop Receiving") keeps `quantityToReceive > 0` but is excluded from`quantityOnPurchaseOrder`.-- **`get_inventory_quantities` has many revisions.** Always read the newest (`20260713235406`), not the+- **`get_inventory_quantities` has many revisions.** Always read the newest (`20261006130001`), not thefirst match. `quantityOnHand` is status-aware: `Rejected` tracked entities are excluded, and trackedrows are always computed live (never from `itemLedgerSnapshot`) so status flips are never stale.- **The auto-generated MCP reference (`.claude/rules/mcp-tools-reference.md`) is stale** for storage units —diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.mdindex 589d8a646c..db329a1860 100644--- a/.claude/rules/mrp-system.md+++ b/.claude/rules/mrp-system.md@@ -2,9 +2,23 @@description: MRP (Material Requirements Planning) — run flow, data model, planning UIpaths:- "packages/jobs/src/inngest/functions/scheduled/mrp.ts"+ - "packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts"- "packages/planning/src/mrp/**"- "packages/database/src/mrp-engine.ts"+ - "packages/utils/src/planning-sizing.ts"- "apps/erp/app/modules/{production,purchasing}/ui/Planning/**"+ - "apps/erp/app/modules/production/planning-action-claims.ts"+ - "apps/erp/app/modules/settings/ui/Planning/**"+ - "apps/erp/app/routes/x+/{production,purchasing}+/planning*.tsx"+ - "apps/erp/app/routes/x+/settings+/planning.tsx"+ - "apps/erp/app/modules/production/production.service.ts"+ - "apps/erp/app/modules/production/production.server.ts"+ - "apps/erp/app/modules/purchasing/purchasing.service.ts"+ - "apps/erp/app/modules/settings/settings.service.ts"+ - "apps/erp/app/modules/settings/settings.models.ts"+ - "apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts"+ - "apps/erp/app/hooks/useMrpScheduleDescription.ts"+ - "packages/planning/src/index.ts"---# MRP (Material Requirements Planning)@@ -13,8 +27,9 @@ MRP nets demand against supply per item/location/period and projects on-handforward so users can create planned purchase orders (purchasing) and jobs(production). It runs **IN-PROCESS in Node** via `runMrp` (exported from`@carbon/planning`, source `packages/planning/src/mrp/mrp.ts`), driven-either by an **Inngest** scheduled cron or a manual route POST — NOT a Supabase-edge function (the old `mrp` Deno function and its `config.toml` entry were+by an **Inngest** scheduled cron, a manual route POST, or a status change on a+document that moves demand or supply (below) — NOT a Supabase edge function+(the old `mrp` Deno function and its `config.toml` entry wereDELETED), and NOT Trigger.dev. `runMrp(client, db, payload)` takes an injectedservice-role Supabase client (PostgREST reads) and a Kysely handle (the atomicPhase-7 write) and throws on failure.@@ -22,14 +37,43 @@ Phase-7 write) and throws on failure.## Run flow (inputs → compute → outputs)1. **Scheduled job** — `packages/jobs/src/inngest/functions/scheduled/mrp.ts`.- `inngest.createFunction({ id: "mrp", retries: 2 }, { cron: "0 */3 * * *" }, …)`- — every 3 hours. A `find-companies` step selects all rows from `company`,- narrowed by `companiesWithPlanningWork` (`scheduled/mrp-companies.ts`): one- UNION over the open demand/supply views, `demandProjection`, and the rows an- earlier run wrote (`demandForecast` with `forecastMethod = 'mrp'`,- `demandForecastSource`, `supplyForecast`, non-zero actuals). A company in- none of them would read nothing and write nothing, so it is skipped; a- failed lookup plans for every company. Then **one `step.run` per company**+ `inngest.createFunction({ id: "mrp", retries: 2 }, { cron: "*/15 * * * *" }, …)`+ — a tick every 15 minutes, on which a company is **due** either every 3+ hours (the default) or once a day at `companySettings.mrpRunTime` (a `TIME`+ on the company's own clock, `company.timezone`; set in Settings → Planning+ → MRP Schedule (`MrpScheduleCard`, intent `setMrpSchedule`), where the form+ offers whole hours plus the stored time when it is not on the hour — an+ MCP-set 14:30 saves back unchanged rather than cut to 14:00 —+ `mrpScheduleValidator`, normalised to `HH:MM:SS`; the Recalculate tooltip+ names the company's timezone). Setting a time REPLACES the 3-hourly runs for that company. The+ rule is the pure `isMrpDue(tick, { timezone, mrpRunTime })`+ (`scheduled/mrp-companies.ts`, unit-tested): the default is "UTC hour+ divisible by 3, minute 0"; a daily time is due on the FIRST tick at or after+ the run time's instant, tested against the instant (not the local hour) so a+ spring-forward day still runs once and a fall-back day does not run twice,+ and checked for yesterday's date too (23:50 is first reached at 00:00). The+ tick is `mrpTick(event.ts)` — the cron's own timestamp plus one minute,+ floored to the 15-minute slot (the minute absorbs a cron that fires just+ before the boundary), so a retried step answers for its own slot; with no+ `event.ts` it falls back to `now("UTC")`. A tick with nobody due returns+ early, before the plan lookup — and a tick between the+ 3-hourly runs with no company on a daily time returns before `company` is+ read at all (the `mrpRunTime` read comes first for that reason). A failed `mrpRunTime` read+ **throws** (defaulting would plan a daily company at the wrong hours and skip+ its own); an unparseable timezone/time falls back to the default cadence for+ that one company. A `find-companies` step selects all rows from `company`,+ narrowed to the due ones and then by `companiesWithPlanningWork`+ (`scheduled/mrp-companies.ts`): one UNION over the open demand/supply views,+ `demandProjection`, and the rows an earlier run wrote (`planningAction`,+ `demandForecast` with+ `forecastMethod = 'mrp'`, `demandForecastSource`, `supplyForecast`, non-zero+ actuals), plus the stock-only sources: an `itemPlanning` row with a positive+ floor its policy reads (minimum reserve; safety stock on Demand-Based+ Reorder; reorder point on Fixed Reorder Quantity / Maximum Quantity) and+ negative `itemStockQuantities` — the planning actions size an Order / Make+ from on-hand alone. A company in none of them would read nothing and write+ nothing, so it is skipped; a failed lookup plans for every due company. Then **one+ `step.run` per company**(`mrp-<companyId>`) calls `runMrp(serviceRole, getJobDatabaseClient(),{ type: "company", id, companyId, userId: "system" })` **in-process** (`runMrp` throws on failure;the loop try/catches per step and returns `{ companies, failed }`). Every@@ -50,31 +94,50 @@ Phase-7 write) and throws on failure.silently never ran MRP, reporting a green Inngest run. Do not reintroduce it:the work list is `company`, and a company with no plan row must still run.On **Cloud only**, companies whose `stripeSubscriptionStatus` is `'Canceled'`- are skipped, because `weekly.ts` deletes those. The selection rule is the pure- `selectCompaniesForMrp` (`scheduled/mrp-companies.ts`), unit-tested in its- sibling `.test.ts`; the scheduler logs a `warn` when the list comes back- empty, so "no work" can never again look like "worked fine".+ are skipped: the company is on its way out (Stripe removes the plan row when+ the subscription ends, and `weekly.ts` then deletes the planless company).+ The selection rule is the pure `selectCompaniesForMrp`+ (`scheduled/mrp-companies.ts`), unit-tested in its sibling `.test.ts`. Every+ tick with someone due logs `Companies scheduled for MRP` (company / due /+ scheduled counts), and a `warn` fires when companies were due but the plan+ and planning-work filters left none. A tick with NOBODY due returns `[]`+ without a log — most ticks are like that. An EMPTY `company` read warns+ (`No companies found to plan for`) before that return: the read happens only+ on a 3-hourly tick or when a company set a time, so empty there is a broken+ work list — the `companyPlan` failure above — never a quiet tick.- Both reads go through `fetchAllFromTable` with a stable `.order("id")` — the+ All three reads (`companySettings.mrpRunTime`, `company`, `companyPlan`) go+ through `fetchAllFromTable` with a stable `.order("id")` — thesame reason every engine read pages (below): `max_rows = 1000` truncates abare select, and the dev stack does not enforce the cap, so a dropped tail is- invisible locally. A failed `company` read **throws**; returning would make- the step succeed having planned for nobody, which is this function's whole- bug class. A failed `companyPlan` read does not — it leaves `plans` null and+ invisible locally. A failed `mrpRunTime` or `company` read **throws**;+ returning would make the step succeed having planned for nobody (or for the+ wrong companies), which is this function's whole bug class. A failed `companyPlan` read does not — it leaves `plans` null andplans for everyone, which is the fail-safe direction.2. **Manual trigger** — POST `apps/erp/app/routes/api+/mrp.ts` (permission- `update: "inventory"`). Reads `?location` query param; calls- `runMRP(getCarbonServiceRole(), { type: locationId ? "location" : "company",- id: locationId ?? companyId, companyId, userId })`. `runMRP` lives in+ `update: "inventory"`). Reads the `?location` query param, confirms it+ belongs to the company (`requireCompanyRecord`), then calls+ `runMRP(getCarbonServiceRole(), getDatabaseClient(), { type: locationId ?+ "location" : "company", id: locationId ?? companyId, companyId, userId })`.+ `runMRP(client, db, params)` lives in`apps/erp/app/modules/production/production.service.ts`; it dynamic-imports- `runMrp` from `@carbon/planning`, gets a Kysely handle via- `getSchedulingDb()`, calls `runMrp(client, db, params)` **in-process**, and- preserves the `{ data, error }` shape (catching the throw). The planning tables- submit to this via `path.to.api.mrp(locationId)`.+ `runMrp` from `@carbon/planning`, calls it **in-process** with the Kysely+ handle the route passed in (never built in the service file), and preserves+ the `{ data, error }` shape (catching the throw). The planning tables submit+ to this via `path.to.api.mrp(locationId)`.++ **Event triggers** — the same `runMRP` runs after a document changes demand+ or supply: job status changes (`x+/job+/$jobId.status.tsx`, and+ `releaseJobs` in `production.server.ts`), PO status changes+ (`x+/purchase-order+/$orderId.status.tsx`), sales order confirm+ (`x+/sales-order+/$orderId.confirm.tsx`) and kanban+ (`api+/kanban.$id.tsx`). The demo template's `planDemoCompany`+ (`packages/jobs/src/demo-planning.ts`) calls `runMrp` directly. None of these+ is affected by `mrpRunTime`, which only governs the cron.3. **In-process engine** — `packages/planning/src/mrp/mrp.ts`- (`runMrp(client, db, payload)`, Node, ~1130 lines). Reads go through the+ (`runMrp(client, db, payload)`, Node, ~1390 lines). Reads go through theinjected service-role Supabase client (PostgREST); the atomic Phase-7 writegoes through the injected Kysely handle. Payload validator accepts`type: "company" | "location" | "item" | "job" | "purchaseOrder" |@@ -83,12 +146,44 @@ Phase-7 write) and throws on failure.`packages/database/src/mrp-engine.ts` (`explodeBom(...)`, `@carbon/database/mrp-engine`),also used by get-method (`@carbon/server-functions`).- - **Periods**: generates/fetches weekly `period` rows ~18 weeks (126 days)- forward from today (`"Week"` granularity). <!-- UNVERIFIED: exact week count not re-confirmed line-by-line; old doc said 72, code comment said 18 -->+ - **Periods**: generates/fetches weekly `period` rows 72 weeks forward from+ today on the company's clock (`WEEKS_TO_FORECAST = 18 * 4`, `"Week"`+ granularity).- **Inputs (demand)**: views `openSalesOrderLines`, `openJobMaterialLines`,- plus the user-entered `demandProjection` for forecast netting. Don't conflate it- with the output: MRP **consumes `demandProjection`** (user-entered) and **writes+ plus the user-entered `demandProjection`. Don't conflate it with the+ output: MRP reads `demandProjection` (user-entered) and **writes`demandForecast`** (rebuilt each run — see Outputs below).+ - **Forecast consumption** (`forecast-consumption.ts`, wired in Phase 4):+ actual demand consumes the projections for the same (item, location) —+ own weekly bucket first, then backward+ `companySettings.forecastConsumptionBackwardPeriods` (default 4) then+ forward `forecastConsumptionForwardPeriods` (default 1) buckets. Only the+ unconsumed remainder enters gross demand/contributors; SO lines consume at+ `openSalesOrderLines.quantityToConsume` (PRE-job-dedup, so an MTO line+ covered by its job still consumes) while demand still uses the deduped+ `quantityToSend`; job materials consume at `quantityToIssue`. Runs BEFORE+ the Phase-4.5 supersession redirect on purpose (read paths don't redirect+ either). Phase 7 persists `demandProjection.consumedQuantity` (batched+ `UPDATE … FROM (VALUES …)`, an UPDATE never an upsert) and every read+ path nets with `GREATEST("forecastQuantity" - "consumedQuantity", 0)`:+ both planning RPCs, `generatePlanningActions`' union,+ `get_inventory_quantities`, and the item forecast API+ (`api+/items.$id.$locationId.forecast.ts`, which nets the raw projections+ `getItemDemand` returns). Regenerative: nothing to+ un-consume — cancelled orders/edited forecasts re-net on the next run.+ Consumption is re-netted only inside MRP's window, so a PAST week keeps+ its last leftover: every read path must stop at the current week. The+ planning RPCs do by their `periods` argument; `get_inventory_quantities`+ joins `period` and keeps `endDate >= location_today(...)` (without it the+ Inventory screen's Demand Forecast grew by each past week's leftover).+ Unit tests: `forecast-consumption.test.ts`. Spec:+ `.ai/specs/implemented/2026-09-11-demand-forecast-consumption.md`.+ Backlog consumes nothing (`actualConsumesForecast`): an SO line promised,+ or a job material whose job is due, before the first period is still+ demand in that period, but the forecast that predicted it was for a week+ that is gone. Consuming this week's forecast with it left this week's+ predicted customers unplanned. Job materials are judged on the job's due+ date, not the lead-time-shifted required date.- **Inputs (supply)**: views `openProductionOrders`, `openPurchaseOrderLines`.- **Inputs (on-hand)**: the `itemStockQuantities` table (trigger-maintained,`20260812002454`) — an indexed per-company read, replacing the old full@@ -112,10 +207,36 @@ Phase-7 write) and throws on failure.- **BOM explosion**: for `Make` items, explodes the active make method toderive child demand with low-level-code ordering, per-period inventorynetting, and lead-time offsetting.- - **Outputs (DB writes)**: deletes prior MRP forecast rows, then batch-inserts+ - **Outputs (DB writes)**: deletes prior MRP forecast rows — including EVERY+ `supplyForecast` row at the company's locations (MRP never inserts+ `supplyForecast`; the planning.update routes do) — then batch-inserts(500/chunk) `demandForecast` (`forecastMethod: "mrp"`), `demandForecastSource`- (lineage), `demandActual`, and `supplyActual`. Writes are stamped with the- payload `userId` (`"system"` for cron).+ (lineage), `demandActual`, and `supplyActual`, and persists+ `demandProjection.consumedQuantity`. Writes are stamped with the payload+ `userId` (`"system"` for cron).+ - **Planning actions**: after the Phase-7 transaction commits, `runMrp` calls+ `generatePlanningActions` (`planning-actions.ts`), which diff-writes the+ `planningAction` worklist in its own transaction. That transaction takes+ `pg_advisory_xact_lock` on `planning-actions:<companyId>` BEFORE it reads+ the existing rows: nothing else serialises `runMrp` per company (the cron+ and the five route-triggered runs can overlap), and two runs that both+ read "no row" for a natural key both insert — the second fails on+ `planningAction_natural_key_idx` and rolls the whole write back. Under+ the lock the second run reads the first run's rows and updates them in+ place. Its errors propagate, so+ a run whose actions failed reports failure even though the forecast rows+ are already committed. The write is `writePlanningActionDiff`+ (RecordingDriver-tested in `planning-actions.write.test.ts`): its DELETE+ and UPDATE skip `Actioned` rows themselves, because the run read the+ actions before diffing and a row applied in between would otherwise be+ deleted or reopened. Updates go as one `UPDATE … FROM (VALUES …)` per set+ of changed columns (cast through `PATCH_COLUMN_TYPES`), never one per row,+ and each row keeps its own patch — writing every column would drift a+ dismissed row's stored quantity so a changed need never reopens it.+ The shared sizing (`computePlanningOrders`, `@carbon/utils`) suggests+ nothing when a policy's order quantity comes out 0 — a Fixed Reorder+ Quantity item with reorder point and quantity both 0 used to emit an+ "Order 0" action for every short week.## Planning data model (tables — all in newest schema)@@ -125,13 +246,18 @@ Base tables defined in `20250610000433_demand-planning.sql`; lineage table in| Table | PK | Key cols | Notes ||-------|----|----|-------|| `period` | `id` | `startDate`, `endDate`, `periodType` | enum `'Week'\|'Day'\|'Month'`; no companyId (uniform RLS) |+| `demandProjection` | `(itemId, locationId, periodId)` | `forecastQuantity`, `consumedQuantity` | user-authored forecast; `consumedQuantity` is MRP-written derived state (`20261006130001`), never user-edited || `demandForecast` | `(itemId, locationId, periodId)` | `forecastQuantity`, `forecastMethod` | MRP writes `forecastMethod='mrp'` || `demandActual` | `(itemId, locationId, periodId, sourceType)` | `actualQuantity`, `sourceType` | `sourceType` enum `demandSourceType` = `'Sales Order'\|'Job Material'` |-| `supplyForecast` | `(itemId, locationId, periodId)` | `forecastQuantity`, `forecastMethod` | written by **planning.update** routes (planned POs/jobs), not by MRP |+| `supplyForecast` | `(itemId, locationId, periodId)` | `forecastQuantity`, `forecastMethod` | written by **planning.update** routes (planned POs/jobs); MRP never inserts it but DELETES every row at the company's locations in Phase 7 |+| `planningAction` | `(id, companyId)` | `type`, `status`, `suggestedQuantity`, `suggestedDate`, `horizonDate`, `latestOrderDate`, `purchaseOrderLineId` / `jobId`, `assignee` | the MRP worklist (`20261006130000`). `type` enum `planningActionType` = Order / Make / Expedite / Defer / Cancel / Increase / Decrease / Release; `status` = Open / Dismissed / Actioned. Diff-written by `generatePlanningActions`; one non-Actioned row per (item, location, type, and the target order — or, for a new Order / Make, its week) via a partial unique index on `COALESCE(purchaseOrderLineId, jobId, periodId)`. `naturalKey` matches rows the same way, with every week up to the current one as one "now" (`keyPeriodFor`), and the diff updates `periodId` in place — so a dismissal or a hand-set assignee survives the weekly roll of the first period || `supplyActual` | `(itemId, locationId, periodId, sourceType)` | `actualQuantity`, `sourceType` | `sourceType` enum `supplySourceType` = `'Purchase Order'\|'Production Order'` || `demandForecastSource` | surrogate `id` | `sourceType`, `jobId`/`salesOrderLineId`/`demandProjectionId`, `parentItemId`, `quantity` | MRP lineage; enum `demandForecastSourceType` = `'Job Material'\|'Sales Order'\|'Demand Projection'`; CHECK exactly one source id set |+| `itemPostingGroupResponsibility` | `(id, companyId)` | `locationId`, `itemPostingGroupId`, `responsibleEmployee` | one rung of the action owner ladder (`20261006130000`): the owner of an item group AT a location; UNIQUE `(companyId, locationId, itemPostingGroupId)`; RLS employee read, `settings_update` writes (`20261006130100`). Written by `upsertItemPostingGroupResponsibility` (a null employee deletes the row) |-`locationId` is declared `TEXT` (no `NOT NULL`) on all five planning tables, but+`locationId` is declared `TEXT` (no `NOT NULL`) on the five original planning+tables (`demandProjection`, `demandForecast`, `demandActual`, `supplyForecast`,+`supplyActual`; `planningAction` declares it `NOT NULL` outright), butit is part of the PRIMARY KEY of every one of them (see the PK column above), soPostgres makes it **implicitly NOT NULL** — a null `locationId` raises 23502, andit is also an FK to `location(id)`, so a bogus value (e.g. the empty string@@ -144,8 +270,13 @@ no `locationId` rather than fabricating one. Audit cols (`createdBy/At`,## Planning split functions-Latest definition: `20260324120000_planning-quantity-to-order.sql` (supersedes the-old `20251205000037_include-reorder-quantity-in-planning.sql`).+Latest definition of BOTH, and of `get_inventory_quantities`:+`20261006130001_demand-forecast-consumption.sql`. `get_production_planning`+supersedes `20260715195226`; `get_purchasing_planning` and+`get_inventory_quantities` are forked from the guarded `20260925121735` bodies+and open with `assert_company_access`.+Their `demand_data` CTEs read the projection arm net of consumption+(`GREATEST("forecastQuantity" - "consumedQuantity", 0)`).- `get_purchasing_planning(company_id, location_id, periods[])` — items where`replenishmentSystem != 'Make'` (includes "Buy" and "Buy and Make"),@@ -169,29 +300,151 @@ to child demand. Note current `methodType` enum is## Source views (open demand/supply)-Newest defs in `20260417000300_storage-unit-recreate-dependents.sql`-(`openPurchaseOrderLines` in `20260529074512_open-po-lines-required-date.sql`,-`openSalesOrderLines` in `20260710051147_mto-sales-lines-drive-demand.sql`).+Newest defs: `openPurchaseOrderLines` in `20260811123616_widen-purchasing-scale.sql`,+`openProductionOrders` in `20260811123619_widen-sales-production-scale.sql`,+`openJobMaterialLines` in `20260926093417_open-job-material-lines-invoker.sql`,+`openSalesOrderLines` in `20261006130001_demand-forecast-consumption.sql`.All join through `itemReplenishment` to expose `replenishmentSystem`, `leadTime`,`itemTrackingType`.- `openSalesOrderLines` — `salesOrderLineType != 'Service'`, status IN`('To Ship','To Ship and Invoice')`. Newest def:- `20260710051147_mto-sales-lines-drive-demand.sql`. Make to Order lines ARE- included (they were excluded before that migration), but their- `quantityToSend` is netted down by the remaining output+ `20261006130001_demand-forecast-consumption.sql`. Make to Order lines ARE+ included, but their `quantityToSend` is netted down by the remaining output(`quantity − quantityReceivedToInventory − quantityShipped`) of live jobslinked via `job.salesOrderLineId` (statuses Planned/Ready/In Progress/Paused —the same set as `openJobMaterialLines`, so each unit is counted exactly once:SO line while unjobbed, job materials once a job is released, inventory once- produced). Draft/Cancelled jobs do not suppress line demand.+ produced). Draft/Cancelled jobs do not suppress line demand. The view also+ exposes `quantityToConsume` — the PRE-job-dedup open quantity, used only by+ forecast consumption (a job-covered MTO line still consumes forecast).- `openJobMaterialLines` — job status IN `('Planned','Ready','In Progress','Paused')`,`methodType != 'Make to Order'`.- `openProductionOrders` — job status IN those 4, `salesOrderId IS NULL`(make-to-stock jobs only); `quantityToReceive = productionQuantity − received`.- `openPurchaseOrderLines` — `purchaseOrderLineType != 'Service'`, status IN- `('To Receive','To Receive and Invoice','Planned')`; `dueDate` = requiredDate- (falls back to receiptPromisedDate).+ `('To Receive','To Receive and Invoice','Planned')`; `dueDate` = the line's+ `requiredDate`, `promisedDate` = the line's promised date, else the order+ delivery's `receiptPromisedDate`.++### When a PO line arrives — one rule++`purchaseOrderLineArrivalDate` (`packages/planning/src/mrp/supply-date.ts`,+pure, tested): promised date, else required date, else order date + lead time+(7 days when the item has none; from today when the order has no date). Both+`runMrp` (which week the supply lands in) and `generatePlanningActions` (the+order's "current date" for Expedite / Defer) call it. They used to disagree —+the projection never read the required date, the check read it first — so+applying an Expedite, which writes the required date, moved the action and left+the projected shortage and its Order suggestion in place. Never date a PO line+anywhere else.++A PROMISED date (the line's, else its delivery's `receiptPromisedDate`) is the+supplier's, and planning writes only the required date, which a promise+outranks. So an Expedite / Defer on a promised line is `requiresManualAction`+("Review on PO", `OpenSupplyOrder.dateIsPromised`), and both planning routes+refuse to move its date: Apply sends it to review, and the drawer's inline due+date edit returns 409 (`promisedDateOf`, `purchasing+/planning.update.tsx`).+Applying it used to mark the action done, move nothing, and get the same+action back from the next run. Quantity actions on a promised line are+unaffected.++### When a job finishes — one rule++`jobCompletionDate` (same file, tested): the job's due date, else today + 30+days for a `No Deadline` job (the default on a new job), else today. Both+engines call it. The reschedule check used to skip an undated job that the+projection counted as supply, so the two saw different supply and the job was+never offered a Cancel, Defer or Expedite.++### Reads and the horizon in `generatePlanningActions`++- The generator's reads are grouped: the responsible-employee resolver and+ the two open-supply views in one `Promise.all`, then the three demand+ tables, on-hand and the open jobs in a second (five Kysely reads at once —+ `getJobDatabaseClient()` shares the 16-connection process pool, so a bounded+ group leaves room for the run's other work). They were six waits in a row.+- The two planning RPCs are read through `fetchAll` with `.order("id")`, like+ every other read in the run. A bare `client.rpc(...)` stops at PostgREST's+ `max_rows` (1000); an item missing from those rows has no candidates, and the+ diff then deletes its existing actions, dismissals and assignee overrides+ included.+- Change actions are derived BEFORE new-supply sizing, and sizing reads+ `projectionsWithExpedites`: the projection with every open order counted+ from its need week — every Expedite done, and an order late by no more than+ the reschedule tolerance (no Expedite) counted from its first need too+ (`firstNeedPeriodByOrder`, the same walk as `deriveChangeActions`). Sized on+ the raw projection, a shortage an Expedite covered also got an Order for the+ same week; and a need this week covered by a PO landing a few days into next+ week read as short, so sizing ordered it again and the fold made it+ "Increase from 100 to 200" on that very PO — then a Decrease on the next run.+- **Release** (`deriveReleaseActions`, migration `20261006210557`): every line+ of a Planned PO and every Planned job gets one, dated `releaseByDate` — the+ order's due date (`purchaseOrderLineArrivalDate` / `jobCompletionDate`) less+ the item's lead time less one day, so due in 8 days with a 7-day lead time+ is today. A PO is released once, so all its lines carry the EARLIEST line's+ date (`earlierRelease`). `horizonDate` is that date (the fence hides it until+ it is close), `isASAP` once it has come, `latestOrderDate` null (not new+ supply), and an order MRP would Cancel gets none; it sits beside a change to+ the same order (the natural key includes the type). It is never applied+ by the planning routes (Apply Suggested Changes skips it,+ `isApplyablePlanningAction`, and both Apply routes refuse the type): the+ row's **Release** button runs the order's OWN release from the page through+ `PlanningActionHandlers.onRelease` — purchasing opens the PO's Finalize modal+ (`usePurchaseOrderPlanningCommands().finalizePurchaseOrder`), production+ posts the job to the jobs table's release route (`useJobPlanningRelease` →+ `path.to.bulkReleaseJob`: the job page's readiness checks, the release, the+ location's schedule run). A host with no `onRelease` gets a link to the+ order instead. It+ applies only while the order is Planned — MRP stops raising it, and between+ runs the planning pages drop it once the order's live status moves on+ (`isStaleRelease` in `usePlanningActions`; the grid RPCs' Actions filter+ ignores it the same way, `20261006205037`). It lights the Order button's dot+ red on and after its day and not before (every planned order has one); its+ date reads late only once the day has passed. In the drawer a change on the+ same order takes the row's one action slot (`actionForOrder`).+- `deriveChangeActions` measures Expedite / Defer from the order's EXPECTED date:+ its due date, or today when it is overdue (`laterDate`). Measured from the old+ due date, a late order read as early and got a Defer to a date already past.+ The NEED date is clamped the same way: a need in the current week is needed+ today, not on the week's (past) start. Apply writes the suggested date onto+ the order, so an Expedite to last Sunday made the order overdue, read as+ arriving today, and with a tolerance under a week the same Expedite came+ back on every run. `convertOrdersToIncreases` compares both dates clamped.+- **Quantity suggestions are what the order will hold** (`quantityAfterApply`).+ Apply writes a PO line in whole PURCHASE units (`conversionFactor`, read for+ the open lines whose factor is not 1), so a Decrease to 55 on a 10-per-box+ line wrote 60 and the next run asked for 55 again, forever. Decrease and+ Increase on a PO line are rounded up to the purchase multiple, and a line+ already at it gets no action. An Increase names the PO line's supplier, not+ the item's preferred one.+- `deriveChangeActions` claims the policy floor (safety stock, reorder point,+ minimum reserve) FIRST — from on-hand, then the earliest orders — and an+ order holding part of it is never Cancelled, Decreased or Deferred. The floor+ has no date and never Expedites an order by itself. It used to take what the+ demand walk left, undated: an order holding safety stock was dated by a later+ demand and deferred, which put stock under the floor until that date.+- `deriveChangeActions` gives NO verdict on an order due after the last planning+ week (`WEEKS_TO_PLAN` = 48; MRP itself plans 72). Its demand is not loaded, so+ it would otherwise read as "nothing needs it" and be offered for Cancel. Such+ an order is not pulled in to cover an earlier need either.+- `runMrp` throws when the forecast-consumption settings cannot be read; the+ window decides what is persisted as `consumedQuantity`, so defaults are not a+ safe fallback.+- **A job order is measured in GOOD units** — `job.quantity` less+ `quantityReceivedToInventory`, from one read of the company's open jobs+ (the same four statuses as `openProductionOrders`), never the view's+ `quantityToReceive`, which is `productionQuantity` (quantity + scrap) less+ received. A change action is applied to `job.quantity`, so on the view's+ figure every job with a scrap allowance read as over-supplied, got "Only 80+ of 84 is required", and got it again after the Decrease was applied.+ `updatePlanningJob` restates `scrapQuantity` for the new quantity from the+ item's scrap rate, as `insertJob` derives it. (The projection itself still+ books `productionQuantity` as supply — a separate, older choice.)+- The `demandProjection.consumedQuantity` write touches only rows whose value+ changed (`IS DISTINCT FROM`) and leaves `updatedAt` / `updatedBy` alone:+ consumption is derived, and the audit columns name the planner who entered+ the forecast.## Planning UI@@ -201,19 +454,320 @@ All join through `itemReplenishment` to expose `replenishmentSystem`, `leadTime`- Purchasing: `apps/erp/app/routes/x+/purchasing+/planning.tsx`(`view: "purchasing"`) + `PurchasingPlanningTable` under`apps/erp/app/modules/purchasing/ui/Planning/`.+- **Weeks are one column, not 48.** Both grids render the per-period projection+ (`week1`…`weekN`) as a single **Stock Availability** strip+ (`modules/production/ui/Planning/PlanningWeekStrip.tsx`): a small column+ chart on a zero line — stock above it in a neutral tone, a shortfall hanging+ below it in red, a tick on the line for an exact zero, nothing when MRP wrote+ no projection. Red is the only hue, so a healthy row stays quiet and sign is+ carried by direction as well as colour (it replaced a flat red / grey / green+ strip that said nothing about depth and turned a short row into a wall of+ colour). Each row is scaled to its OWN range (`planningWeekGeometry`,+ `planning-week-geometry.ts`, unit-tested): heights compare along a row, not+ between rows. One tooltip per row follows the hovered week (the shared+ `TooltipContent` takes an `anchor` for this) and shows the week label, its+ date range and the projected quantity; the hovered week is marked by an+ overlay band that is cleared on `pointerleave` — it used to stay on the last+ week touched. The per-week numbers stay in the CSV as+ `exportOnlyColumn`s keyed `week1`…`weekN`, so an export is unchanged.+- **Suggested orders ARE the Order / Make actions.** The order drawer's+ Suggested Orders / Suggested Jobs, the row's Order / Make button quantity+ and a bulk order for rows never opened all read the item's OPEN new-supply+ actions (`openNewSupplyActions` + `plannedOrdersFromActions` /+ `productionOrdersFromActions`, `ui/Planning/planned-orders-from-actions.ts`,+ tested by `apps/erp/test/planned-orders-from-actions.test.ts`): one row per+ action, on the action's own week, in purchase units for a PO (rounded up by+ the chosen supplier part's factor). They used to be sized again in the+ browser from the weekly projections (`calculateOrders`), which missed what+ MRP does after sizing — moving expedited supply, folding a shortfall into+ an open order as an Increase, summing each week into one action — so the+ drawer showed daily 10s against weekly 50s and offered a new order for the+ shortfall an Increase already covered. A dismissed Order is not offered;+ a shortfall whose Increase was dismissed gets no Order until MRP writes one,+ and the planner adds it by hand with New. The rows refresh when MRP runs.+- **Latest Order Date** (both grids, after 1st Negative On Hand): the last day the+ row's next suggested order can be placed and still arrive on time — the+ grid RPC's `latestOrderDate`, the MIN order-by date of the item's open+ new-supply actions, so the cell, its sort and the drawer agree. Red once the+ day has passed (before the location's today); "-" when nothing needs+ ordering. The tooltip shows the required date (order-by date plus lead+ time) and the lead time; the CSV carries the ISO date. Cell:+ `ui/Planning/LatestOrderDate.tsx`.+- **Shared, not copied.** The two grids differ only in their own columns (item+ link, supplier, lead time, quantity to order, the Order button) and wiring.+ Everything else lives once in `production/ui/Planning/`: `usePlanningActions`+ (the worklist fetcher and toast, fenced and filtered actions, the batched+ submit, and the `actionHandlers` the action lines and drawers spread),+ `planningColumns` (the shared column definitions, typed to each grid's row)+ and `PlanningDrawerParts` (`PlanningPolicySummary` with a slot for the+ purchasing drawer's supplier rows, `BeyondFenceButton`, `periodIdFor`).+ Change the shared piece; a copy in one grid drifts, as the untranslated+ labels in one drawer did.+- **One "today": the location's.** Every planning surface that marks a date+ late — the Latest Order Date cell, the expanded action lines+ (`PlanningActionLines`) and the drawers — takes the loader's+ `locationToday` as a prop. None reads the browser's zone: a planner in+ another timezone saw an action red in one column and not in the next.- Both have a "Recalculate" button (`mrpFetcher.Form` POST to- `path.to.api.mrp(locationId)`) tooltip: *"MRP runs automatically every 3 hours,- but you can run it manually here."*+ `path.to.api.mrp(locationId)`) whose tooltip comes from+ `useMrpScheduleDescription` (`~/hooks`): *"MRP runs automatically every 3+ hours…"* or *"…every day at 2:00 PM…"* when the company set+ `companySettings.mrpRunTime`. The Inventory table's button uses the same hook.+- **Planning actions (the MRP worklist, spec §P1.7) live INSIDE each grid**, not+ in a separate list. Both routes load the location's persisted `planningAction`+ rows (`getPlanningActions`, Buy/Make by kind) and pass them to the grid, which+ renders an **Actions** column (one ICON chip per open type with a count and+ the type name in a tooltip, a muted dismissed chip; always one line so busy+ rows are no taller than the rest; static type filter), a pulsing dot on the+ row's Order / Make button (`planningActionDot`, `ui/Planning/planning-review.ts`:+ only open actions that add or advance supply — Order, Make, Expedite,+ Increase — light it: red when one is ASAP, green otherwise; an Increase+ lights it with nothing new to order. A Decrease, Defer or Cancel never+ lights it, and is never drawn late in the expanded row either+ (`isPlanningActionLate`) — its date is where the order sits, not a+ deadline), and an+ **expandable row** (`renderExpandedRow`/`canExpandRow`, gated to items with+ actions) listing the item's actions as child lines — type, target PO/job+ hyperlink, quantity, `DateTime` (red when past), reason, assignee — each with+ ONE button: **Apply** (open change action on an uncommitted target), **Review+ on PO/Job** (`requiresManualAction`), or **Order…/Make…** (opens the grid's+ order drawer; Order/Make rows are fulfilled by the existing Order button, never+ applied as a change). A per-line ⋯ holds Assign to Me and Dismiss/Reopen. The+ bulk menu gains **Apply Suggested Changes** (every applyable action on the+ selected items, ONE batched request). Shared UI:+ `modules/production/ui/Planning/PlanningActionLines.tsx`; every mutation posts+ to the existing `planning.update.tsx` cases (`apply`/`dismiss`/`reopen`/`assign`).+ **Cancel** on a job runs `cancelJob` (`production.server.ts`), the job status+ route's own path: picked material back, picking lists closed, then+ Cancelled. On a PO line it DELETES the line, in one statement that also+ requires a Draft / Planned PO and nothing received or invoiced; when that+ guard holds the row back the action goes back to Open as "Review on PO".+ Never `shortClosePurchaseOrderLine` — it recomputes the header status from+ the lines and turned an unsent Draft into "Completed".+ **Apply is set-based.** Purchasing: `applyPurchasingPlanningActions(db, …)`+ runs the whole batch in ONE Kysely transaction — the claim, one+ `UPDATE … FROM (VALUES …)` for dates, one for quantities, one `DELETE` for+ cancels, and the un-claim of refused rows — about five round trips for any+ batch size, all-or-nothing. Production: `applyProductionPlanningDateActions`+ does the same for Expedite / Defer (claim, the jobs, the jobs already on+ the target dates, one UPDATE of due date + priority via the pure+ `nextJobPriority`), then the route sends ONE `schedule-inputs-changed`+ event for the batch (a "reorder" event re-stamps the whole company whatever+ its job id). Increase / Decrease / Cancel on jobs call server functions+ with their own transactions, so they stay per job — grouped by job, three+ jobs at a time (`async.map`), each claimed right before its own change.+ The claim and release inside a transaction live in+ `modules/production/planning-action-claims.ts`, shared by both services;+ the release reopens the row, or deletes it when an MRP run has meanwhile+ written a fresh Open row for the same need (the natural-key index).+ Tests: `apps/erp/test/apply-purchasing-planning-actions.test.ts`,+ `apply-production-planning-date-actions.test.ts`.+ **Every Apply write carries its own Draft / Planned condition**+ (`updatePlanningJob`, `updatePurchaseOrderLineSchedule`, the Cancel delete),+ so a job released or a PO sent between the route's status read and the write+ is left alone and the action goes to review — a read-then-write gate let it+ through. A failed write gives its claim back through+ `releasePlanningActionClaim`, which deletes the claimed row instead when an+ MRP run has meanwhile written an Open row for the same need (the reopen hits+ the natural-key index, 23505); a failed release is reported, not swallowed.+ Job Cancel is the one exception: `cancelJob`'s cleanup steps run in their own+ transactions, so a release between the read and the cancel is not caught.+ **Permissions:** both `planning.update` routes run with the service role, so+ their `requirePermissions` is the only check — `create` for `order`,+ `update` for everything else, plus `purchasing_delete` (read from the claims)+ for a Cancel that deletes a PO line. An assignee or responsible employee is+ saved only after `isActiveCompanyEmployee` (`shared.server.ts`), and+ `planningAction` is read-only through the API (manifest rule: read is+ `anyOf("production_view", "purchasing_view")`, since both planning pages+ read it with the user's client; MRP and these routes write it with the+ service role).+ The Actions column filter (`filter=planningActions:eq:<type>`) and the+ Assignee column's people filter (`filter=planningAssignee:in:<userId>,…` —+ the same people list every other assignee filter uses; the column is hidden+ by default and shows the row's assignees when turned on) are not grid RPC+ columns: the loader strips them with `resolvePlanningActionScope`+ (`ui/Planning/planning-action-scope.ts`, pure, unit-tested) and passes them to+ the grid RPC as ARGUMENTS (`action_types`, `action_assignees`), which keeps the+ items with a matching OPEN action inside the item's planning horizon. The+ loader then reads the actions for the rows ON THE PAGE (`getPlanningActions`+ with `itemIds`, paged). An earlier version loaded the location's first 500+ actions and resolved item ids from them — it silently dropped items past the+ cap and could not see the horizon.+- **Reschedule tolerance.** `companySettings.rescheduleToleranceDays`+ (`INTEGER NOT NULL DEFAULT 7`, `20261006130000`) is read by+ `generatePlanningActions` as `toleranceDays` into `deriveChangeActions`: an+ open order gets an Expedite / Defer only when its date is STRICTLY more than+ the tolerance from the date it is needed, and a dismissed action stays+ dismissed while its date moves within the tolerance. Authored at Settings →+ Planning (`RescheduleToleranceCard`, intent `setTolerance`,+ `rescheduleToleranceValidator` in `settings.models.ts`, 0–365).+- **Planning ownership (the owner ladder).** `resolveResponsibleEmployee` /+ `loadResponsibleEmployeeResolver` (`packages/planning/src/mrp/responsible-employee.ts`):+ `itemPlanning.responsibleEmployee` → `itemPostingGroupResponsibility` (the+ item group AT the location) → `location.responsibleEmployee` →+ `companySettings.defaultResponsibleEmployee`, first non-null wins. The diff+ re-resolves an action's `assignee` on every run unless `assigneeOverridden`+ (set by Assign) — and the UPDATE re-checks that flag on the row itself, so a+ planner who assigns between the run's read and its write still wins.+- **Settings → Planning** (`x+/settings+/planning.tsx`, cards in+ `apps/erp/app/modules/settings/ui/Planning/`): `ResponsibleEmployeeCard`+ (intents `setCompanyDefault`, `setLocation`, `setItemGroup`; `setLocation`+ writes `location`, a resources table, so a user without `resources_update`+ matches no row under RLS and is told so rather than shown a success),+ `RescheduleToleranceCard` (`setTolerance`), `PlanningPurchaseOrderApprovalCard`+ (`setPlanningPurchaseOrderApproval` → `companySettings.skipApprovalForPlanningPurchaseOrders`,+ default on: a PO the planning Order button created — `purchaseOrder.createdFromPlanning`,+ cleared by any manual line change — finalizes without the approval rule), `PlanningHorizonCard`+ (`setPlanningHorizon`, `planningHorizonValidator`), `ForecastConsumptionCard`+ (`setForecastConsumption`, `forecastConsumptionValidator`, 0–52 weeks each)+ and `MrpScheduleCard` (`setMrpSchedule`, `mrpScheduleValidator`). An employee+ id is saved only after `isActiveCompanyEmployee`; a bad value answers 400.+- **Planning horizon (time fence).** `itemPlanning.planningHorizonDays` (per+ item + location, Part → Planning) else `companySettings.defaultPlanningHorizonDays`+ (Settings → Planning) else none. **0 means "no fence"** at either level+ (`NULLIF(COALESCE(item, company), 0)` in the grid RPCs): an item's 0 is how it+ opts out of a company default, which an empty field would inherit. It is not+ "zero days" — that put the fence on today and hid nearly everything. It is a READ-TIME LENS, never an engine input:+ `generatePlanningActions` writes actions for the whole window and stamps each+ with `horizonDate` — the earlier of the target order's current date and the+ suggested date, so a Defer counts from where its order sits today and an+ Expedite from when it is needed — and the grids surface only rows with+ `horizonDate <= today + days`. That is what lets a planner move ONE row's+ fence in the **Planning Horizon** column (`useTimeFenceOverrides`, page state,+ gone on reload, never written to the item) without an MRP run. Named+ `planningHorizonDays` on purpose: `planningTimeFenceDays` is reserved by the+ MRP v2 spec for the auto-firm fence, a different concept.+ - The fence comparison exists twice and must stay one inclusive `<=` on ISO+ dates: in SQL (`get_*_planning_grid`, the saved horizon, for the Actions+ filter) and in `ui/Planning/planning-fence.ts` (on screen, override+ included; unit-tested). Sort and filter therefore use the SAVED horizon —+ an on-screen override changes what a row shows, not which rows match.+ - Inside the fence: the Actions chips, the expanded row, **Apply Suggested+ Changes**, the row's Order/Make quantity, and a bulk **Order Parts /+ Create Jobs** on rows never opened in the drawer. The drawer opens on the+ suggested orders REQUIRED on or before the fence. A "N More After <date>"+ button EXTENDS the row's fence to the last suggested order rather than+ copying rows in — the fence is the one piece of state, so the order list+ and the grid row follow together. The drawer marks the fence on the chart+ and carries the same Planning Horizon control as the grid cell.+ - Moving a row's fence DROPS that item's entry in the grid's `ordersMap`+ (`onFenceChange`): the drawer's draft list is kept per item once opened,+ and a stale one would neither show the newly included orders nor offer+ them. That discards manual edits to the draft, by design.+- **The order drawer is two tables with two save models**+ (`ui/Planning/PlanningOrderGrids.tsx`, both on the shared `Grid`), because a+ row that does not exist yet cannot autosave:+ - **Suggested Orders / Suggested Jobs** (`SuggestedOrdersGrid`) — a DRAFT.+ Quantity and due date are click-to-edit; the edits live in the planning+ grid's `ordersMap` and nothing is written until Order / Make. The drafts+ survive a loader reload (Apply, Dismiss, Assign inside the drawer+ revalidate it) and are dropped only when the page scope changes (the+ search params), MRP recalculates, or an order is placed — clearing on+ every `data` change wiped the planner's edits mid-task. The Order By+ / Start By column is derived (due date less lead time).+ - **Open Orders / Open Jobs** (`OpenOrdersGrid`) — existing PO lines / jobs+ at the page's location (both drawer reads filter on `locationId`, and+ `updateLine` / `updateJob` refuse another location's record with 409).+ A cell edit SAVES that one field (optimistic, reverted with a toast on+ failure) through `planning.update`'s `updateLine` / `updateJob` action,+ which re-reads the record under the company and refuses a committed record+ with 409. Jobs: `updateJob` and Apply share `isJobEditableFromPlanning`+ (`production.models.ts`), an allowlist of Draft / Planned — anything else+ (on the floor, finished, closed, cancelled) is "Review on Job". POs:+ `updateLine`, Apply and the drawer's editable rows share+ `isPurchaseOrderEditableFromPlanning` (`purchasing.models.ts`), the same+ Draft / Planned allowlist — a PO in approval (Needs Approval, To Review,+ Rejected) or sent is "Review on PO", matching MRP's own+ `isCommittedPurchaseOrderStatus`. A quantity edit restates the line's tax+ pair (`taxPairForQuantity`): the extended price is generated, the tax+ amount is stored. A failed follow-up on a saved job edit (recalculating+ requirements, telling the scheduler) is reported as a warning, never a+ revert — the edit stands.+ Locked rows render as plain cells+ (`Grid isRowEditable`). Each row carries the planning action that targets+ it — type, suggested value, reason, Apply / Review — so there is no+ separate action table. Released jobs (Ready / In Progress / Paused) are+ listed read-only for that reason: an action needs its job's row to sit on.+ An action whose order is not in the list still gets a read-only row.+ - **The order's status is an icon, not a column.** `Status iconOnly`+ (`@carbon/react`, passed through `PurchasingStatus` / `JobStatus`) renders+ the status colour and icon in front of the PO / job number, with the name+ in its tooltip — it says why a row is Review rather than Apply without+ adding row height or a column the drawer has no width for. The drawer+ takes it from the open line / job (`OpenOrdersGrid renderStatusIcon`); the+ grid's expanded row (`PlanningActionLines`) and the drawer's read-only+ fallback rows take it from the action, which `getPlanningActions` enriches+ with `purchaseOrderStatus` / `jobStatus`.+- **`getPlanningActions` reads the item, the PO behind a line and the job as+ PostgREST embeds, and chunks the page's item ids (100 per request).** It used+ to look them up afterwards with `.in("id", <one id per action>)`; a page of+ busy parts (2,000+ actions) put 50 kB of ids in the URL, the gateway answered+ 431, and the loader's `?? []` turned that into a grid with no actions. The+ loaders now log and throw on a failed read instead — an empty Actions column+ must never be what a failure looks like. The id lists a bulk selection sends+ (Apply, Dismiss, Reopen, Assign, and Apply's job / PO line reads) have no+ page bound at all, so those go through Kysely as ONE statement each+ (`getPlanningActionsByIds`, `markPlanningActionsActioned`,+ `dismissPlanningActions`, `reopenDismissedPlanningActions`,+ `assignPlanningActions` take the `db` handle): the ids are bound+ parameters, never a URL. The set-based Apply claims and changes a batch in+ one transaction; the per-job path claims each action right BEFORE its own+ change, so a request that dies there strands at most the actions in flight.+ Every claim (`claimPlanningActions`, `markPlanningActionsActioned`) RETURNS+ the row's `suggestedQuantity` and `suggestedDate`, and Apply writes THOSE —+ an MRP run between the page's read and the claim can move an Open action in+ place, and the page's values would be the stale suggestion. A date apply+ (`applyProductionPlanningDateActions`, `updatePlanningJob`) also restates a+ "No Deadline" job as `Soft Deadline` (`deadlineTypeForPlanningDate`): the job+ form hides the due-date field for No Deadline, and `nextJobPriority` would+ rank the dated job with the undated weight.+ - Purchasing quantities are in PURCHASE units (the line's+ `purchaseQuantity`; the open-lines view reports inventory units), and an+ action's suggested quantity is converted and rounded up as Apply does. The+ chart still receives existing orders in inventory units.+ - A manual edit does NOT resolve the suggestion on that row: the action stays+ until the next MRP run re-evaluates the order.+ The earlier single list mixed both: an edit to an existing order sat unsaved+ until Order was pressed and was dropped by Close.+- **Grid RPCs are wrappers.** `get_purchasing_planning_grid` /+ `get_production_planning_grid` (latest: `20261006205037_planning-grid-order-quantity.sql`) select+ `p.*` from the base RPC and add `itemPostingGroupId` (**Item Group** column ++ filter), `planningHorizonDays`, `timeFenceDate`, `firstNegativeDate` (**1st+ Negative On Hand**: the start of the first week whose projection is below+ zero — weekly, because MRP buckets by week), `latestOrderDate` (the MIN of+ the item's open new-supply actions, which makes **Latest Order Date**+ sortable; the cell shows the same value) and `orderQuantity` (the SUM of the+ item's open Order / Make actions inside its saved fence, 0 when none — the+ grids' default sort, then the part number; there is no Qty to Order column,+ the row's Order / Make button shows the quantity).+ The base RPC's own `quantityToOrder` (`calculate_quantity_to_order`, a second+ sizing of the projection in SQL) is NOT shown or sorted on any more: it+ never sees what MRP does after sizing (Expedites, Increases, orders placed+ since the last run against a projection only a run refreshes), so it put+ items with nothing to order above real shortages. It stays in `p.*` for+ `generatePlanningActions`' Stock Only path. The base RPCs stay the one definition of the projection and are what+ `generatePlanningActions` reads. Adding a column to a base RPC means+ re-creating its wrapper with the same column — it fails loudly (return type+ mismatch) until then. Generated types mark every RPC column non-null; the new+ ones are not (`PlanningGridColumns` in `production/types.ts`).- **Create planned orders** — `planning.update.tsx` in each module:- production (`create: "production"`, role `employee`): inserts jobs +job methods, upserts `supplyForecast` (`'Production Order'`), then`recalculateJobRequirements()`.- purchasing (`create: "purchasing"`, role `employee`): one PO per supplier- per submit — reuses the supplier's open Draft/Planned `Purchase` PO whose- delivery location is the planning location (header lookup, not a- line-in-period match), else inserts one. Lines are matched on item +- `requiredDate`, so orders for different weeks stay as separate lines on- the same PO. Upserts `supplyForecast` (`'Purchase Order'`) per order period.+ per WEEK (`planningPurchaseOrderWeek`: Sunday-start, as the grid's+ periods; a late or undated order is in the current week). It reuses the+ oldest open Draft/Planned `Purchase` PO for the supplier, at the planning+ location, in the supplier's currency, whose lines are ALL in that week+ (`findPlanningPurchaseOrder`), else inserts one. A PO with lines in+ several weeks (raised before this rule) takes no more orders; matching+ on ANY line in the week let such a PO keep collecting weeks. Before this, every+ week went on one PO, so finalizing it to send the first week locked the+ later weeks against MRP's Defer / Decrease / Cancel. A PO with no lines is+ never reused. All candidate POs and their lines are read once per submit.+ An order whose item and `requiredDate` match an existing line adds to it,+ restating the tax pair (`taxPairForQuantity`). Upserts `supplyForecast`+ (`'Purchase Order'`) per order period.## Gotchas@@ -221,8 +775,10 @@ All join through `itemReplenishment` to expose `replenishmentSystem`, `leadTime`The engine itself is in-process Node (`runMrp` from `@carbon/planning`), NOTa Supabase edge function — the `mrp` Deno function was deleted.- MRP itself writes `demandForecast`/`demandActual`/`supplyActual`/- `demandForecastSource`; it does **not** write `supplyForecast` — that comes from- the user-driven `planning.update` routes (planned orders).-- The engine currently runs full MRP regardless of `type`/`id` scope- (effectively company-wide). <!-- UNVERIFIED: scope-narrowing TODO not re-confirmed in current code -->+ `demandForecastSource`/`planningAction`; it never inserts `supplyForecast` —+ that comes from the user-driven `planning.update` routes (planned orders) —+ but Phase 7 deletes every `supplyForecast` row at the company's locations.+- The engine runs full MRP regardless of `type`/`id` scope: `type` is only+ logged (`run started`), never used to narrow the reads, so every run is+ company-wide.- Don't rebuild the DB to test schema; ask the user (per AGENTS.md).diff --git a/.claude/rules/onboarding-company-templates.md b/.claude/rules/onboarding-company-templates.mdindex e225f199cc..8ac1dcbaa5 100644--- a/.claude/rules/onboarding-company-templates.md+++ b/.claude/rules/onboarding-company-templates.md@@ -187,7 +187,7 @@ error message per step.written as `metadata.planningError` (a new apply resets it to `null`); marker status isnever changed. On the `snapshot: false` path the marker is already cleared, so thefailure is only logged (re-writing it would resurrect the marker as `running`). The- 3-hourly MRP cron is the backstop — for MRP only.+ scheduled MRP run (every 3 hours, or the company's daily time) is the backstop — for MRP only.- **Dev CLI** — the spawned `plan:company` script (above). `plan-company.ts` loads`demo-planning.ts` through `createRequire` so tsx compiles the graph as CJS; as ESM,`@carbon/planning`'s named imports from `@carbon/database` fail to link. It exits 0 evendiff --git a/.claude/rules/purchasing-conversion-factors.md b/.claude/rules/purchasing-conversion-factors.mdindex 8a6fdc9d6a..3a37e8f171 100644--- a/.claude/rules/purchasing-conversion-factors.md+++ b/.claude/rules/purchasing-conversion-factors.md@@ -75,8 +75,9 @@ forward likewise (`update-purchased-prices` uses the planning `ln` alias).**Reverse direction (planning → purchase qty).** MRP/planning has an inventoryrequirement and computes the purchase quantity, rounding up:-`Math.ceil(inventoryQuantity / conversionFactor)` (when factor > 0) — see-`PurchasingPlanningOrderDrawer.tsx` and `items/ui/Item/ItemReorderPolicy.tsx`.+`round(inventoryQuantity / conversionFactor, 0, RoundingMode.Up)` (when factor+> 0) — see `PurchasingPlanningOrderDrawer.tsx` and+`production/ui/Planning/planned-orders-from-actions.ts`.**Display-only conversions** multiply purchase qty by the factor to show derivedinventory qty (e.g. `PurchaseOrderSummary.tsx`, `SupplierQuoteSummary.tsx`) anddiff --git a/.claude/rules/revision-system.md b/.claude/rules/revision-system.mdindex 296da7c2a7..d426da0b4b 100644--- a/.claude/rules/revision-system.md+++ b/.claude/rules/revision-system.md@@ -86,15 +86,18 @@ the type-scoped `revisions` array.- `itemReplenishment`: `lotSize` (Batch Size), `scrapPercentage`, `leadTime`,`preferredSupplierId`, and with it `purchasingUnitOfMeasureCode` +`conversionFactor` (both derived from the preferred supplier's supplier part).- - `itemPlanning`, per location: `reorderingPolicy` and every parameter the- planning form edits (accumulation period, safety stock, reorder point and- quantity, maximum inventory, min/max order quantity, order multiple). A policy- without its parameters is invalid, so they travel together.+ - `itemPlanning`, per location: `reorderingPolicy` and its sizing parameters+ (accumulation period, safety stock, reorder point and quantity, maximum+ inventory, min/max order quantity, order multiple). A policy without its+ parameters is invalid, so they travel together. The two other fields on the+ planning form, `planningHorizonDays` and `responsibleEmployee`, are NOT+ copied (`copyItemPlanningAndPurchasing`, `items.service.ts`).- `itemCost.itemPostingGroupId` (the item group).- `supplierPart` rows and their `supplierPartPrice` price breaks, paired by`supplierId` (unique per item).NOT copied: costs, `itemUnitSalePrice`, `requiresConfiguration` and the- blocked flags, `minimumReserveQuantity`, supersession, pick method, shelf life.+ blocked flags, `minimumReserveQuantity`, supersession, pick method, shelf life,+ `itemPlanning.planningHorizonDays`, `itemPlanning.responsibleEmployee`.- **Deleting an item deletes its price breaks first.** `supplierPart.itemId`cascades from `item`, but `supplierPartPrice → supplierPart` is`ON DELETE RESTRICT`, and every revision of an item with price breaks nowdiff --git a/.claude/rules/supersession-system.md b/.claude/rules/supersession-system.mdindex 37a8cde883..19855a4b02 100644--- a/.claude/rules/supersession-system.md+++ b/.claude/rules/supersession-system.md@@ -37,7 +37,7 @@ Do not assume one rule. Each answers something different, deliberately.| Consumer | Source | Question ||---|---|---|-| **MRP** (`mrp/index.ts`) | live, every run | what should we BUY? |+| **MRP** (`runMrp`, `@carbon/planning` — `packages/planning/src/mrp/mrp.ts`) | live, every run | what should we replenish (buy or make), and how should existing supply change? || **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? |diff --git a/.claude/rules/table-csv-export.md b/.claude/rules/table-csv-export.mdindex 5529affcf6..f3d60334e0 100644--- a/.claude/rules/table-csv-export.md+++ b/.claude/rules/table-csv-export.md@@ -33,8 +33,8 @@ once by `buildColumnMaps(columns, translateLabel)` inresolve an id to a name) instead of the raw accessor read. See "meta hooks".- `sortKeyToLabel: Record<string, string>` — server-sort key (`meta.sortBy ??accessorKey`) → translated label, used by the `Sort` picker. Only string-header- columns with an accessorKey are included, so JSX-header columns (e.g. MRP week- columns) never flood the picker.+ columns with an accessorKey are included, so JSX-header columns (e.g. the+ demand projection week columns) never flood the picker.`Download` also receives:diff --git a/.claude/rules/user-employee-job-relationships.md b/.claude/rules/user-employee-job-relationships.mdindex 684930bc0a..32735a6eb0 100644--- a/.claude/rules/user-employee-job-relationships.md+++ b/.claude/rules/user-employee-job-relationships.md@@ -96,6 +96,12 @@ is the separate `job` table from `20240909194622_jobs.sql`).`employee.active = false`, and invalidates the Redis claims cache. It does **not** clear`user.active` or scrub stored userId references (assignee columns, `workCenterEmployee`,notification-group settings arrays).+- Planning stores more user ids the deactivation does not scrub: `itemPlanning.responsibleEmployee`,+ `location.responsibleEmployee`, `companySettings.defaultResponsibleEmployee`,+ `itemPostingGroupResponsibility.responsibleEmployee` and `planningAction.assignee` (all+ `TEXT REFERENCES "user"("id")`, so the database accepts any user's id, including another+ company's). A route saves one only after `isActiveCompanyEmployee(client, companyId, userId)`+ (`apps/erp/app/modules/shared/shared.server.ts`), which fails closed on a read error.- Notification fan-out (`notify.ts` `resolve-recipients` in `packages/jobs`) filters resolvedrecipients against `userToCompany` for the notification's company — a missing membership row(i.e. a deactivated user) is dropped before any in-app/email/Slack delivery, regardless of howdiff --git a/apps/erp/app/components/Assignee.tsx b/apps/erp/app/components/Assignee.tsxindex a052f3d9d7..08ba5486ad 100644--- a/apps/erp/app/components/Assignee.tsx+++ b/apps/erp/app/components/Assignee.tsx@@ -43,6 +43,10 @@ export type AssigneeProps = Omit<placeholder?: string;variant?: AssigneeVariants;onChange?: (selected: string) => void;+ /** Saves the choice through the caller instead of the generic assign+ * route — for a record whose assignment has rules of its own (a planning+ * action marks a hand-set assignee so MRP never re-resolves it). */+ onAssign?: (selected: string) => void;};const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(@@ -56,6 +60,7 @@ const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(placeholder,variant = "button",onChange,+ onAssign,className,...props},@@ -69,6 +74,10 @@ const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(const permissions = usePermissions();const handleChange = (value: string) => {+ if (onAssign) {+ onAssign(value);+ return;+ }const formData = new FormData();formData.append("id", id);formData.append("assignee", value);diff --git a/apps/erp/app/components/Editable/EditableDate.tsx b/apps/erp/app/components/Editable/EditableDate.tsxnew file mode 100644index 0000000000..ac4dbfc1d9--- /dev/null+++ b/apps/erp/app/components/Editable/EditableDate.tsx@@ -0,0 +1,111 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { DatePicker } from "@carbon/react";+import { parseDate } from "@internationalized/date";+import { useLingui } from "@lingui/react/macro";+import type { PostgrestSingleResponse } from "@supabase/supabase-js";+import { useRef } from "react";+import type { EditableTableCellComponentProps } from "~/components/Editable";++/**+ * A calendar-date cell for `Grid` / inline-editing `Table`: the sibling of+ * `EditableNumber`, same contract. The value is an ISO `YYYY-MM-DD` string and+ * stays one — the date commits optimistically and runs `mutation`; a failed+ * mutation reverts the cell and marks it.+ *+ * Like `EditableNumber`, the cell commits when focus LEAVES it, and also when+ * the calendar closes (a picked day closes it). It used to commit on every+ * change of the field: once the field held a full date, each key press was a+ * change, so typing a year saved 0002, 0020 and 0202 first — each one a+ * request, and each job save a schedule refresh.+ *+ * An empty date is only committed when `clearable` is set: most date cells+ * (a due date, a required date) are not optional, and react-aria reports a+ * half-typed date as `null` too.+ */+const EditableDate = <T extends object>(+ mutation: (+ accessorKey: string,+ newValue: string,+ row: T+ ) => Promise<PostgrestSingleResponse<unknown>>,+ options?: { clearable?: boolean }+) => {+ const EditableDateEditor = ({+ value,+ row,+ accessorKey,+ onError,+ onUpdate+ }: EditableTableCellComponentProps<T>) => {+ const { t } = useLingui();+ // a timestamp column would carry a time part; a calendar date is its head+ const current =+ typeof value === "string" && value.length >= 10+ ? value.slice(0, 10)+ : null;++ // The field's latest value; `committed` is what the cell last saved, so+ // the blur that follows a closed calendar does not save the day twice.+ const latest = useRef<string | null>(current);+ const committed = useRef<string | null>(current);++ const commit = () => {+ const next = latest.current;+ if (next === committed.current) return;+ if (next === null && !options?.clearable) return;+ committed.current = next;++ onUpdate({ [accessorKey]: next });++ mutation(accessorKey, next ?? "", row)+ .then(({ error }) => {+ if (error) {+ onError();+ onUpdate({ [accessorKey]: value });+ }+ })+ .catch(() => {+ onError();+ onUpdate({ [accessorKey]: value });+ });+ };++ return (+ // The selected cell already draws the ring. The picker's own border and+ // focus halo on top of it read as a doubled, blurry edge, so the field+ // group goes edgeless here — as EditableNumber's input does.+ <div+ className="[&_[role=group]]:rounded-none [&_[role=group]]:border-transparent [&_[role=group]]:shadow-none [&_[role=group]:focus-within]:border-transparent [&_[role=group]:focus-within]:ring-0"+ // Focus moving between the date segments and the calendar button stays+ // inside; the calendar itself is portaled, so opening it commits what+ // was typed so far (a half-typed date is null and is not saved).+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {+ commit();+ }+ }}+ >+ <DatePicker+ aria-label={t`Date`}+ size="sm"+ autoFocus+ closeOnSelect+ defaultValue={current ? parseDate(current) : null}+ onChange={(next) => {+ latest.current = next ? next.toString() : null;+ }}+ onOpenChange={(isOpen) => {+ if (!isOpen) commit();+ }}+ />+ </div>+ );+ };++ return EditableDateEditor;+};++export default EditableDate;diff --git a/apps/erp/app/components/Editable/index.ts b/apps/erp/app/components/Editable/index.tsindex baa2ee113c..86bfe20e0c 100644--- a/apps/erp/app/components/Editable/index.ts+++ b/apps/erp/app/components/Editable/index.ts@@ -2,9 +2,10 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import EditableDate from "./EditableDate";import EditableList from "./EditableList";import EditableNumber from "./EditableNumber";import EditableText from "./EditableText";export * from "./types";-export { EditableList, EditableNumber, EditableText };+export { EditableDate, EditableList, EditableNumber, EditableText };diff --git a/apps/erp/app/components/Grid/Grid.tsx b/apps/erp/app/components/Grid/Grid.tsxindex 0e03214f4d..eb6d5ae4ba 100644--- a/apps/erp/app/components/Grid/Grid.tsx+++ b/apps/erp/app/components/Grid/Grid.tsx@@ -23,6 +23,9 @@ import {getCoreRowModel,useReactTable} from "@tanstack/react-table";+import type { Range } from "@tanstack/react-virtual";+import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual";+import type { ReactNode } from "react";import { useCallback, useEffect, useRef, useState } from "react";import { LuCirclePlus } from "react-icons/lu";import type {@@ -32,6 +35,14 @@ import type {import { Row } from "./components";import { getAccessorKey, updateNestedProperty } from "./utils";+// Used until a row is measured: a body cell is `h-11`.+const ESTIMATED_ROW_HEIGHT = 44;+// The header row sits above the rows inside the same scroller. Its `Tr` is+// `h-10`, but every `Th` is `h-11`, and a table row is as tall as its tallest+// cell.+const HEADER_HEIGHT = 44;+const OVERSCAN = 3;+interface GridProps<T extends object> {canEdit?: boolean;columns: ColumnDef<T>[];@@ -40,6 +51,21 @@ interface GridProps<T extends object> {defaultColumnOrder?: string[];defaultColumnVisibility?: Record<string, boolean>;editableComponents?: Record<string, EditableTableCellComponent<T>>;+ /**+ * Lock individual rows: a row this returns `false` for renders its editable+ * columns as plain, non-editable cells (no ring, no pencil, no editor), the+ * same as every cell does under `canEdit={false}`. For lists that mix rows a+ * user may still change with rows a status has locked. Defaults to every+ * row being editable.+ */+ isRowEditable?: (row: T) => boolean;+ /**+ * Cap the grid's height in pixels. The rows then scroll inside the grid under+ * a pinned header, and only the rows in view (plus the selected one) are+ * rendered — for lists that can run to hundreds of rows. Without it every+ * row is rendered and the grid is as tall as its rows.+ */+ maxHeight?: number;withNewRow?: boolean;withSimpleSorting?: boolean;@@ -54,6 +80,8 @@ const Grid = <T extends object>({contained = true,data,editableComponents,+ isRowEditable,+ maxHeight,defaultColumnOrder,defaultColumnVisibility,withSimpleSorting = true,@@ -170,13 +198,24 @@ const Grid = <T extends object>({[table, editableComponents]);+ // A cell is editable when its column has an editor AND its row is not locked.+ const isCellEditable = useCallback(+ (rowIndex: number, column: number) => {+ if (!isColumnEditable(column)) return false;+ if (!isRowEditable) return true;+ const row = table.getRowModel().rows[rowIndex];+ return row ? isRowEditable(row.original) : false;+ },+ [isColumnEditable, isRowEditable, table]+ );+const onCellClick = useCallback((row: number, column: number) => {// ignore row select checkbox columnif (column === -1) return;// Editable cells enter edit mode on a single click (the editable input// then auto-focuses and selects its text), instead of select-then-click.- if (isColumnEditable(column)) {+ if (isCellEditable(row, column)) {onSelectedCellChange({ row, column });setIsEditing(true);return;@@ -184,7 +223,7 @@ const Grid = <T extends object>({setIsEditing(false);onSelectedCellChange({ row, column });},- [isColumnEditable, onSelectedCellChange]+ [isCellEditable, onSelectedCellChange]);const onCellUpdate = useCallback(@@ -271,7 +310,7 @@ const Grid = <T extends object>({!isEditing &&code === "Enter" &&!shiftKey &&- isColumnEditable(selectedCell.column)+ isCellEditable(selectedCell.row, selectedCell.column)) {setIsEditing(true);return;@@ -302,7 +341,7 @@ const Grid = <T extends object>({// continues naturally. Otherwise (Enter) drop out of edit mode.if (isEditing) {const carryEdit = Boolean(- canEdit && code === "Tab" && isColumnEditable(x1)+ canEdit && code === "Tab" && isCellEditable(y1, x1));setIsEditing(carryEdit);}@@ -322,12 +361,12 @@ const Grid = <T extends object>({!["ShiftLeft", "ShiftRight"].includes(code) &&!isEditing &&selectedCell &&- isColumnEditable(selectedCell.column)+ isCellEditable(selectedCell.row, selectedCell.column)) {setIsEditing(true);}},- [canEdit, isColumnEditable, isEditing, selectedCell, table]+ [canEdit, isCellEditable, isEditing, selectedCell, table]);// reset the selected cell when the table data changes@@ -342,18 +381,145 @@ const Grid = <T extends object>({const rows = table.getRowModel().rows;+ /* Row virtualization (only with `maxHeight`) */+ const isVirtual = maxHeight !== undefined;++ // The selected row stays rendered when it scrolls out of view: it holds the+ // keyboard focus and, mid-edit, the open editor. Dropping it would lose both.+ const selectedRow = selectedCell?.row;+ const rangeExtractor = useCallback(+ (range: Range) => {+ const indexes = defaultRangeExtractor(range);+ if (+ selectedRow === undefined ||+ selectedRow >= range.count ||+ indexes.includes(selectedRow)+ ) {+ return indexes;+ }+ return [...indexes, selectedRow].sort((a, b) => a - b);+ },+ [selectedRow]+ );++ const rowVirtualizer = useVirtualizer({+ enabled: isVirtual,+ count: rows.length,+ getScrollElement: () => tableContainerRef.current,+ getItemKey: (index) => rows[index]?.id ?? index,+ estimateSize: () => ESTIMATED_ROW_HEIGHT,+ overscan: OVERSCAN,+ scrollMargin: HEADER_HEIGHT,+ rangeExtractor,+ // The scroller is not measured until after the first render; without this+ // that render would draw no rows at all.+ initialRect: { width: 0, height: maxHeight ?? 0 }+ });++ const renderRow = (row: (typeof rows)[number], virtualIndex?: number) => (+ <Row+ key={row.id}+ editableComponents={+ canEdit && (isRowEditable?.(row.original) ?? true)+ ? editableComponents+ : {}+ }+ isEditing={isEditing}+ selectedCell={selectedCell}+ row={row}+ rowIsSelected={selectedCell?.row === row.index}+ rowRef={isVirtual ? rowVirtualizer.measureElement : undefined}+ virtualIndex={virtualIndex}+ withRowBorder={isVirtual}+ onCellClick={onCellClick}+ onCellUpdate={onCellUpdate}+ onEditRow={onEditRow}+ />+ );++ // The rows in view, with an empty row standing in for each run of rows that+ // is not rendered, so the scrollbar and every row's position stay true.+ const renderVirtualRows = () => {+ const columnCount = table.getVisibleLeafColumns().length;+ const spacer = (key: string, height: number) => (+ <tr key={key} aria-hidden>+ <td colSpan={columnCount} style={{ height, padding: 0 }} />+ </tr>+ );++ const rendered: ReactNode[] = [];+ let offset = 0;+ for (const item of rowVirtualizer.getVirtualItems()) {+ const row = rows[item.index];+ if (!row) continue;+ const start = item.start - HEADER_HEIGHT;+ if (start > offset) {+ rendered.push(spacer(`before-${item.index}`, start - offset));+ }+ rendered.push(renderRow(row, item.index));+ offset = item.end - HEADER_HEIGHT;+ }+ const totalSize = rowVirtualizer.getTotalSize();+ if (totalSize > offset) rendered.push(spacer("after", totalSize - offset));+ return rendered;+ };++ // In a virtualized grid "New" sits under the scroller, always in view, so+ // adding a row never means scrolling to the end of a long list first. The+ // added row lands at the end, out of view, so the grid scrolls to it.+ const awaitedRowCount = useRef<number | null>(null);+ const onNewRowClick = () => {+ awaitedRowCount.current = rows.length + 1;+ onNewRow?.();+ };+ useEffect(() => {+ const awaited = awaitedRowCount.current;+ awaitedRowCount.current = null;+ if (awaited === rows.length) {+ rowVirtualizer.scrollToIndex(rows.length - 1, { align: "end" });+ }+ }, [rows.length, rowVirtualizer]);+return (- <VStack spacing={0} className="h-full w-full">+ <VStack+ spacing={0}+ className={cn(+ "h-full w-full",+ // The frame the table's own wrapper would otherwise draw: here it has+ // to go around the scroller and the "New" button under it.+ isVirtual && !contained && "overflow-hidden rounded-md border"+ )}+ ><divclassName={cn("w-full h-full overflow-x-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent",- contained ? "" : "relative"+ contained ? "" : "relative",+ isVirtual && "overflow-y-auto")}+ style={+ isVirtual ? { maxHeight, scrollPaddingTop: HEADER_HEIGHT } : undefined+ }ref={tableContainerRef}onKeyDown={onKeyDown}>- <Table full={contained} className={cn(!contained && "border w-full")}>- <Thead className="sticky top-0 z-10">+ <Table+ full={contained || isVirtual}+ className={cn(+ !contained && !isVirtual && "border w-full",+ // Automatic layout sizes columns from the rows that are rendered,+ // and virtualization swaps those rows while scrolling, so every+ // column changed width under the cursor. Fixed layout takes the+ // widths from the header (`header.getSize()`) alone.+ isVirtual && "table-fixed"+ )}+ >+ <Thead+ className={cn(+ "sticky top-0 z-10",+ // Rows scroll under the pinned header, so it must be opaque.+ isVirtual && "bg-card"+ )}+ >{table.getHeaderGroups().map((headerGroup) => (<Tr key={headerGroup.id} className="h-10">{headerGroup.headers.map((header) => {@@ -392,21 +558,9 @@ const Grid = <T extends object>({))}</Thead><Tbody>- {rows.map((row) => {- return (- <Row- key={row.id}- editableComponents={canEdit ? editableComponents : {}}- isEditing={isEditing}- selectedCell={selectedCell}- row={row}- rowIsSelected={selectedCell?.row === row.index}- onCellClick={onCellClick}- onCellUpdate={onCellUpdate}- onEditRow={onEditRow}- />- );- })}+ {isVirtual+ ? renderVirtualRows()+ : rows.map((row) => renderRow(row))}{rows.length === 0 && !onNewRow && (<Tr className="h-10 hover:bg-muted/50"><Td colSpan={24}>@@ -416,7 +570,7 @@ const Grid = <T extends object>({</Td></Tr>)}- {onNewRow && (+ {onNewRow && !isVirtual && (<TronClick={onNewRow}className="cursor-pointer h-10 hover:bg-muted/50 border-t"@@ -434,6 +588,18 @@ const Grid = <T extends object>({</Tbody></Table></div>+ {onNewRow && isVirtual && (+ <button+ type="button"+ onClick={onNewRowClick}+ className="flex h-11 w-full items-center space-x-2 border-t border-border px-6 text-sm hover:bg-muted/50"+ >+ <LuCirclePlus className="text-muted-foreground h-4 w-4" />+ <span>+ <Trans>New</Trans>+ </span>+ </button>+ )}</VStack>);};diff --git a/apps/erp/app/components/Grid/components/Row.tsx b/apps/erp/app/components/Grid/components/Row.tsxindex 87ad773c39..76ffeff185 100644--- a/apps/erp/app/components/Grid/components/Row.tsx+++ b/apps/erp/app/components/Grid/components/Row.tsx@@ -4,7 +4,7 @@import { cn, Tr } from "@carbon/react";import type { Row as RowType } from "@tanstack/react-table";-import type { MutableRefObject } from "react";+import type { Ref } from "react";import { memo } from "react";import type {EditableTableCellComponent,@@ -20,7 +20,16 @@ type RowProps<T> = {row: RowType<T>;rowIsClickable?: boolean;rowIsSelected: boolean;- rowRef?: MutableRefObject<HTMLTableRowElement | null>;+ rowRef?: Ref<HTMLTableRowElement>;+ /** The row's index in a virtualized grid, read back when it is measured. */+ virtualIndex?: number;+ /**+ * Draw a line between body rows. A virtualized grid scrolls its rows under a+ * pinned header, where rows with no separator read as one tall cell per+ * column. The header row already draws the line under itself, so the first+ * row adds none and nothing doubles up.+ */+ withRowBorder?: boolean;onCellClick: (row: number, column: number) => void;onCellUpdate: (row: number) => (updates: Record<string, unknown>) => void;onEditRow?: (row: T) => void;@@ -35,6 +44,8 @@ const Row = <T extends object>({rowIsSelected,rowRef,selectedCell,+ virtualIndex,+ withRowBorder = false,onCellClick,onCellUpdate}: RowProps<T>) => {@@ -44,7 +55,11 @@ const Row = <T extends object>({<Trkey={row.id}ref={rowRef}- className={cn(rowIsClickable && "cursor-pointer")}+ data-index={virtualIndex}+ className={cn(+ withRowBorder && "border-t border-border first:border-t-0",+ rowIsClickable && "cursor-pointer"+ )}>{row.getVisibleCells().map((cell, columnIndex) => {const isSelected =diff --git a/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx b/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsxindex 275699e3db..d2e23892bf 100644--- a/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx+++ b/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx@@ -27,6 +27,7 @@ import { useLocation, useMatches, useNavigation } from "react-router";import { useOptimisticLocation } from "~/hooks";import { useUIStore } from "~/stores/ui";import type { Handle } from "~/utils/handle";+import { useSlidingHoverCard } from "./useSlidingHoverCard";interface CollapsibleSidebarContextValue {hasSidebar: boolean;@@ -134,51 +135,17 @@ export function useSidebarLocation(isInside: (pathname: string) => boolean) {* background. A link opts in with `data-nav-item`.*/export function SidebarLinks({ children }: PropsWithChildren) {- const listRef = useRef<HTMLDivElement>(null);- const hoverCardRef = useRef<HTMLSpanElement>(null);-- // Written straight to the element: a hover must not re-render the list.- const moveHoverCard = (item: HTMLElement | null) => {- const card = hoverCardRef.current;- const list = listRef.current;- if (!card || !list) return;- if (!item) {- card.style.opacity = "0";- return;- }- const itemRect = item.getBoundingClientRect();- const listRect = list.getBoundingClientRect();- const left = itemRect.left - listRect.left + list.scrollLeft;- const top = itemRect.top - listRect.top + list.scrollTop;- // Entering the list: appear on the link rather than slide in from- // wherever the card was last.- card.style.transitionProperty = card.style.opacity === "1" ? "" : "opacity";- card.style.transform = `translate(${left}px, ${top}px)`;- card.style.width = `${itemRect.width}px`;- card.style.height = `${itemRect.height}px`;- card.style.opacity = "1";- };+ const { containerRef, cardRef, handlers } =+ useSlidingHoverCard<HTMLDivElement>();return (<div- ref={listRef}+ ref={containerRef}className="relative overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent h-full w-full pb-8"- // The gaps between links are not links: the card stays where it is- // while the pointer crosses one, and only leaves with the pointer.- onPointerOver={(event) => {- if (event.pointerType !== "mouse") return;- const item = (event.target as HTMLElement).closest<HTMLElement>(- "[data-nav-item]"- );- if (item) moveHoverCard(item);- }}- // A press navigates, expands a link's views or starts a reorder: the- // row under the card is about to change or move.- onPointerDown={() => moveHoverCard(null)}- onPointerLeave={() => moveHoverCard(null)}+ {...handlers}><span- ref={hoverCardRef}+ ref={cardRef}aria-hiddenclassName="pointer-events-none absolute left-0 top-0 rounded-md bg-active/60 opacity-0 transition-[transform,opacity] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none"/>diff --git a/apps/erp/app/components/Layout/Navigation/DetailsTopbar.tsx b/apps/erp/app/components/Layout/Navigation/DetailsTopbar.tsxindex 3488f98f73..00a7aa4124 100644--- a/apps/erp/app/components/Layout/Navigation/DetailsTopbar.tsx+++ b/apps/erp/app/components/Layout/Navigation/DetailsTopbar.tsx@@ -18,6 +18,7 @@ import { useMemo } from "react";import type { IconType } from "react-icons";import { useNavigate } from "react-router";import { useOptimisticLocation, useUrlParams } from "~/hooks";+import { useSlidingHoverCard } from "./useSlidingHoverCard";type DetailTopbarProps = {links: {@@ -40,6 +41,10 @@ const DetailTopbar = ({const navigate = useNavigate();const location = useOptimisticLocation();const [params] = useUrlParams();+ // The same travelling hover card as the sidebar: it slides between tabs+ // and sits under the active one, whose own background covers it.+ const { containerRef, cardRef, handlers } =+ useSlidingHoverCard<HTMLDivElement>();useShortcutKeyMap(useMemo(@@ -64,7 +69,16 @@ const DetailTopbar = ({);return (- <div className="inline-flex h-9 items-center justify-center rounded-[0.5rem] bg-muted p-1 text-muted-foreground shadow-[inset_0_1px_2px_rgba(0,0,0,0.15)] border-b border-border">+ <div+ ref={containerRef}+ className="relative inline-flex items-center justify-center rounded-[0.5rem] bg-muted p-0.5 text-muted-foreground border border-border"+ {...handlers}+ >+ <span+ ref={cardRef}+ aria-hidden+ className="pointer-events-none absolute left-0 top-0 rounded-[6px] bg-active opacity-0 transition-[transform,width,opacity] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none"+ />{links.map((route) => {const isActive = route.isActive? route.isActive(location.pathname)@@ -79,9 +93,12 @@ const DetailTopbar = ({<TooltipTrigger className="w-full"><PrefetchLinkto={linkTo}+ data-nav-item=""className={cn(- "inline-flex items-center justify-center whitespace-nowrap rounded-[6px] px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",- isActive && "bg-background text-foreground shadow-button-base"+ "relative inline-flex items-center justify-center whitespace-nowrap rounded-[6px] border border-transparent px-3 py-1 text-sm font-medium transition-[background-color,color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring",+ isActive+ ? "bg-background text-foreground shadow-button-base"+ : "hover:text-foreground")}>{route.icon && <route.icon className="mr-2" />}diff --git a/apps/erp/app/components/Layout/Navigation/useSlidingHoverCard.ts b/apps/erp/app/components/Layout/Navigation/useSlidingHoverCard.tsnew file mode 100644index 0000000000..b2ff83580b--- /dev/null+++ b/apps/erp/app/components/Layout/Navigation/useSlidingHoverCard.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { PointerEvent } from "react";+import { useCallback, useMemo, useRef } from "react";++/**+ * The hover card the icon rail has, for any list of links: one card for the+ * whole list, moved with a transform to the link under the pointer, so the+ * highlight travels between links instead of each one fading its own. A link+ * opts in with `data-nav-item`. Spread `handlers` on the container (which must+ * be `relative`) and render the card as an absolutely positioned span holding+ * `cardRef`, before the links; the links need `relative` to paint above it.+ */+export function useSlidingHoverCard<Container extends HTMLElement>() {+ const containerRef = useRef<Container>(null);+ const cardRef = useRef<HTMLSpanElement>(null);++ // Written straight to the element: a hover must not re-render the list.+ const moveCard = useCallback((item: HTMLElement | null) => {+ const card = cardRef.current;+ const container = containerRef.current;+ if (!card || !container) return;+ if (!item) {+ card.style.opacity = "0";+ return;+ }+ const itemRect = item.getBoundingClientRect();+ const containerRect = container.getBoundingClientRect();+ const left = itemRect.left - containerRect.left + container.scrollLeft;+ const top = itemRect.top - containerRect.top + container.scrollTop;+ // Entering the list: appear on the link rather than slide in from+ // wherever the card was last.+ card.style.transitionProperty = card.style.opacity === "1" ? "" : "opacity";+ card.style.transform = `translate(${left}px, ${top}px)`;+ card.style.width = `${itemRect.width}px`;+ card.style.height = `${itemRect.height}px`;+ card.style.opacity = "1";+ }, []);++ const handlers = useMemo(+ () => ({+ // The gaps between links are not links: the card stays where it is+ // while the pointer crosses one, and only leaves with the pointer.+ onPointerOver: (event: PointerEvent<Container>) => {+ if (event.pointerType !== "mouse") return;+ const item = (event.target as HTMLElement).closest<HTMLElement>(+ "[data-nav-item]"+ );+ if (item) moveCard(item);+ },+ // A press navigates, expands a link's views or starts a reorder: the+ // row under the card is about to change or move.+ onPointerDown: () => moveCard(null),+ onPointerLeave: () => moveCard(null)+ }),+ [moveCard]+ );++ return { containerRef, cardRef, handlers };+}diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsxindex 7b2602dc70..eacd51be6d 100644--- a/apps/erp/app/components/Table/Table.tsx+++ b/apps/erp/app/components/Table/Table.tsx@@ -150,6 +150,12 @@ interface TableProps<T extends object> {renderActions?: (selectedRows: T[]) => ReactNode;renderContextMenu?: (row: T) => JSX.Element | null;renderExpandedRow?: (row: T) => ReactNode;+ // Pin an expanded row's content (`sticky left-0`) to the scroll container's+ // visible width, so on a table several viewports wide (the 48-week planning+ // grids) it stays in view instead of sitting at the far left of the row and+ // scrolling away with it. Off by default: it changes how every other+ // expanded row scrolls.+ pinExpandedRows?: boolean;// When `renderExpandedRow` is set, gates which rows can expand (show a chevron// + toggle). Defaults to all rows. Use it so only parents with children get an// affordance, like a tree's `hasChildren`.@@ -309,11 +315,25 @@ const Table = <T extends object>({renderActions,renderContextMenu,renderExpandedRow,+ pinExpandedRows = false,canExpandRow,groupRowsBy}: TableProps<T>) => {const { t } = useLingui();const tableContainerRef = useRef<HTMLDivElement>(null);+ // Visible width of the scroll container, for `pinExpandedRows`.+ const [containerWidth, setContainerWidth] = useState(0);+ useEffect(() => {+ const el = tableContainerRef.current;+ if (!pinExpandedRows || !el || typeof ResizeObserver === "undefined") {+ return;+ }+ const update = () => setContainerWidth(el.clientWidth);+ update();+ const observer = new ResizeObserver(update);+ observer.observe(el);+ return () => observer.disconnect();+ }, [pinExpandedRows]);const { currentView, view } = useSavedViews();@@ -1439,7 +1459,20 @@ const Table = <T extends object>({colSpan={visibleColumns.length}className="p-0 bg-muted/20 border-b border-border">- {renderExpandedRow(row.original)}+ {pinExpandedRows ? (+ <div+ className="sticky left-0"+ style={+ containerWidth > 0+ ? { width: containerWidth }+ : undefined+ }+ >+ {renderExpandedRow(row.original)}+ </div>+ ) : (+ renderExpandedRow(row.original)+ )}</Td></Tr>)}diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.tsindex 5cb3b27ad1..c58698ce2e 100644--- a/apps/erp/app/hooks/index.ts+++ b/apps/erp/app/hooks/index.ts@@ -9,6 +9,7 @@ import {useRouteData,useUrlParams} from "@carbon/react";+import { useAfterFirstPaint } from "./useAfterFirstPaint";import {CompanySettingsProvider,useCompanySettings@@ -22,6 +23,7 @@ import {} from "./useCurrencies";import { useCurrencyFormatter } from "./useCurrencyFormatter";import { useDateFormatter } from "./useDateFormatter";+import { useDrawerItem, useLinkedDrawerItem } from "./useDrawerItem";import { useFileUpload } from "./useFileUpload";import { useFlags } from "./useFlags";import { useGooglePlaces } from "./useGooglePlaces";@@ -30,6 +32,7 @@ import { useImageUpload } from "./useImageUpload";import { useModelUpload } from "./useModelUpload";import { useAllModules, useModules, useSettingsModule } from "./useModules";import { useMovingCellRef } from "./useMovingCellRef";+import { useMrpScheduleDescription } from "./useMrpScheduleDescription";import { useNextItemId } from "./useNextItemId";import { useNotifications } from "./useNotifications";import { useOnboarding } from "./useOnboarding";@@ -50,12 +53,15 @@ import { useTrainingPanel } from "./useTrainingPanel";import { useUser } from "./useUser";export {+ useAfterFirstPaint,CompanySettingsProvider,useCompanySettings,useCompanyTimeZone,useCompanyToday,useCurrencyFormatter,useDateFormatter,+ useDrawerItem,+ useLinkedDrawerItem,useFlags,useGooglePlaces,useIdle,@@ -67,6 +73,7 @@ export {useSettingsModule,useModelUpload,useMovingCellRef,+ useMrpScheduleDescription,useNextItemId,useNotifications,useOnboarding,diff --git a/apps/erp/app/hooks/useAfterFirstPaint.ts b/apps/erp/app/hooks/useAfterFirstPaint.tsnew file mode 100644index 0000000000..f03b3e1c00--- /dev/null+++ b/apps/erp/app/hooks/useAfterFirstPaint.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { startTransition, useEffect, useState } from "react";++/**+ * False until the component's first frame is on screen, then true.+ *+ * For a surface that animates in (a drawer, a sheet) and holds something+ * expensive to build. Mounting it all at once blocks the main thread BEFORE the+ * first frame, so the click is followed by nothing and then the whole thing at+ * once. Render the cheap shell first, gate the heavy part on this, and the+ * surface starts moving immediately — a transform animation runs on the+ * compositor, so it keeps going while the rest is built.+ *+ * Two animation frames, not one: a `requestAnimationFrame` callback runs before+ * its frame is painted, so the first proves nothing; the second runs after the+ * shell's frame has been drawn. The flip is a transition, which lets React+ * yield between components instead of building the heavy part in one block.+ */+export function useAfterFirstPaint(): boolean {+ const [isPainted, setIsPainted] = useState(false);++ useEffect(() => {+ let second = 0;+ const first = requestAnimationFrame(() => {+ second = requestAnimationFrame(() => {+ startTransition(() => setIsPainted(true));+ });+ });+ return () => {+ cancelAnimationFrame(first);+ cancelAnimationFrame(second);+ };+ }, []);++ return isPainted;+}diff --git a/apps/erp/app/hooks/useCompanySettings.tsx b/apps/erp/app/hooks/useCompanySettings.tsxindex 808e11a454..0861e4ab5b 100644--- a/apps/erp/app/hooks/useCompanySettings.tsx+++ b/apps/erp/app/hooks/useCompanySettings.tsx@@ -26,6 +26,7 @@ type CompanySettings = Partial<| "allowLowercaseItemIds"| "digitalQuoteEnabled"| "digitalQuoteIncludesPurchaseOrders"+ | "mrpRunTime"| "showBomExplorerReadableId"| "showCurrencyTrailingZeros"| "showCustomerReadableId"diff --git a/apps/erp/app/hooks/useDrawerItem.ts b/apps/erp/app/hooks/useDrawerItem.tsnew file mode 100644index 0000000000..ef576dd7a8--- /dev/null+++ b/apps/erp/app/hooks/useDrawerItem.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useCallback, useEffect, useRef, useState } from "react";+import { useSearchParams } from "react-router";++/**+ * Selection state for a drawer that shows one record picked from a list.+ *+ * Rendering the drawer as `{item && <Drawer />}` and clearing `item` to close+ * it removes the drawer in the same render, so its closing animation never+ * plays. Here the item outlives the close: `isOpen` drives the drawer, `item`+ * keeps its content on screen while it slides out, and `key` changes on every+ * open so each open still starts from a fresh drawer (local state, fetchers),+ * exactly as it did when closing unmounted it.+ */+export function useDrawerItem<T>() {+ const [item, setItem] = useState<T | null>(null);+ const [isOpen, setIsOpen] = useState(false);+ const [key, setKey] = useState(0);++ const open = useCallback((next: T) => {+ setItem(next);+ setIsOpen(true);+ setKey((current) => current + 1);+ }, []);++ const close = useCallback(() => setIsOpen(false), []);++ return { item, setItem, isOpen, key, open, close };+}++/**+ * `useDrawerItem` with the open record's id in the address (`?<param>=<id>`),+ * so a link to the page opens the same drawer.+ *+ * Opening and closing from the page update the drawer at once and the address+ * alongside it: the address is a navigation, and waiting for its loader would+ * make every click on a row lag. The address only drives the drawer when it+ * moves on its own — a pasted link, Back, Forward. An id that is not in `rows`+ * (deleted, another location) is dropped from the address, and the page shows+ * no drawer.+ */+export function useLinkedDrawerItem<T extends { id: string }>({+ param,+ rows+}: {+ param: string;+ /** Where a linked id is looked up. */+ rows: T[];+}) {+ const drawer = useDrawerItem<T>();+ const [searchParams, setSearchParams] = useSearchParams();+ const linkedId = searchParams.get(param);++ const setLinkedId = useCallback(+ (id: string | null, replace = false) => {+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ if (id) next.set(param, id);+ else next.delete(param);+ return next;+ },+ { replace, preventScrollReset: true }+ );+ },+ [param, setSearchParams]+ );++ const { open: openDrawer, close: closeDrawer } = drawer;++ const open = useCallback(+ (item: T) => {+ openDrawer(item);+ setLinkedId(item.id);+ },+ [openDrawer, setLinkedId]+ );++ const close = useCallback(() => {+ closeDrawer();+ setLinkedId(null);+ }, [closeDrawer, setLinkedId]);++ // Read by the effect below without re-running it: it must act on a change+ // of the address only. Re-running on the drawer's own state would close a+ // drawer opened a moment ago whose navigation has not landed yet.+ const latest = useRef({ drawer, rows });+ latest.current = { drawer, rows };++ // biome-ignore lint/correctness/useExhaustiveDependencies: the address is the only trigger+ useEffect(() => {+ const { drawer: current, rows: currentRows } = latest.current;+ if (!linkedId) {+ if (current.isOpen) current.close();+ return;+ }+ if (current.isOpen && current.item?.id === linkedId) return;+ const row = currentRows.find((r) => r.id === linkedId);+ if (row) current.open(row);+ else setLinkedId(null, true);+ }, [linkedId]);++ return { ...drawer, open, close };+}diff --git a/apps/erp/app/hooks/useMrpScheduleDescription.ts b/apps/erp/app/hooks/useMrpScheduleDescription.tsnew file mode 100644index 0000000000..e6ae761311--- /dev/null+++ b/apps/erp/app/hooks/useMrpScheduleDescription.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { formatTimeOfDay } from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import { useCompanySettings } from "./useCompanySettings";+import { useCompanyTimeZone } from "./useCompanyTimeZone";++/**+ * The tooltip on every "Recalculate" button: when MRP runs on its own. Every+ * 3 hours unless the company set a daily time in Settings → Planning+ * (`companySettings.mrpRunTime`, on the company's own clock — named, since a+ * planner in another zone would otherwise read it as their own).+ */+export function useMrpScheduleDescription(): string {+ const { t } = useLingui();+ const { locale } = useLocale();+ const mrpRunTime = useCompanySettings()?.mrpRunTime;+ const timeZone = useCompanyTimeZone();++ if (!mrpRunTime) {+ return t`MRP runs automatically every 3 hours, but you can run it manually here.`;+ }++ const time = formatTimeOfDay(mrpRunTime, locale);+ return t`MRP runs automatically every day at ${time} (${timeZone}), but you can run it manually here.`;+}diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex c1ea059a3d..6591b9a609 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -12,6 +12,7 @@ import {fiscalYearAndPeriodFor,getDateNYearsAgo,isBalanced,+ isUniqueViolation,MONTH_NUMBER,round,toDisplayCredit,@@ -2224,7 +2225,7 @@ export async function upsertExchangeRateOverride(// Two concurrent first-time pins can both miss the update and race the// insert; the loser hits the (companyId, currencyCode) unique constraint.// Retry as an update so the second write wins instead of erroring.- if (insert.error?.code === "23505") {+ if (isUniqueViolation(insert.error)) {const retry = await client.from("exchangeRateOverride").update({@@ -5910,10 +5911,9 @@ export async function createOpeningBalanceJournal(// A unique violation on journal_one_posted_opening_balance_per_company means// a concurrent request already posted the company's opening balances — the// atomic backstop for the check-then-post race.- const message =- (posted.error as { code?: string }).code === "23505"- ? "An opening balance entry already exists — reverse it before entering new balances"- : posted.error.message;+ const message = isUniqueViolation(posted.error)+ ? "An opening balance entry already exists — reverse it before entering new balances"+ : posted.error.message;return { data: null, error: { message } };}diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex e69090e74c..09b8804f47 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -17,7 +17,7 @@ import { async, datetime, getErrorMessage } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";-import { getNextSequence } from "~/modules/settings";+import { getNextSequence } from "~/modules/settings/settings.service";import type { StorageItem } from "~/types";import type { GenericQueryFilters } from "~/utils/query";import {diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsxindex 0f56b31de0..a78a86b31d 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx@@ -55,7 +55,7 @@ import { useLocations } from "~/components/Form/Location";import StorageUnit from "~/components/Form/StorageUnit";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { useFilters } from "~/components/Table/components/Filter/useFilters";-import { useUrlParams } from "~/hooks";+import { useMrpScheduleDescription, useUrlParams } from "~/hooks";import {itemReorderingPolicies,itemReplenishmentSystems@@ -641,6 +641,7 @@ const InventoryTable = memo(};const mrpFetcher = useFetcher<typeof mrpAction>();+ const mrpScheduleDescription = useMrpScheduleDescription();return (<Table<InventoryItem>@@ -688,9 +689,7 @@ const InventoryTable = memo(<Trans>Recalculate</Trans></Button></TooltipTrigger>- <TooltipContent>- {t`MRP runs automatically every 3 hours, but you can run it manually here.`}- </TooltipContent>+ <TooltipContent>{mrpScheduleDescription}</TooltipContent></Tooltip></mrpFetcher.Form></div>diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 2bf11fa9e9..d29d6b7793 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -49,7 +49,7 @@ pnpm --filter @carbon/erp test| `makeMethod` | Versioned manufacturing method header (Draft/Active/Archived) || `methodMaterial` / `methodOperation` / `methodOperationStep` / `methodOperationParameter` / `methodOperationTool` | BOM lines, routing steps, and work instruction details || `itemCost` / `costLedger` | Standard/average costs and cost history |-| `itemReplenishment` / `itemPlanning` | Manufacturing settings (lot size, lead time, scrap %) and planning params |+| `itemReplenishment` / `itemPlanning` | Manufacturing settings (lot size, lead time, scrap %) and planning params — per location: the reorder policy and its sizing parameters, `planningHorizonDays` (the item's time fence on the planning pages; empty = inherit the company default, 0 = no fence) and `responsibleEmployee` (the leaf rung of the MRP action owner ladder), all on `itemPlanningValidator` / `ItemPlanningForm`. `ItemReorderPolicy` sizes the tab's suggested orders with `computePlanningOrders` (`@carbon/utils`), the same sizing MRP uses; `api+/items.$id.$locationId.forecast.ts` nets `demandProjection.consumedQuantity` so the chart matches the planning grids || `itemPostingGroup` | Maps item categories to GL accounts || `unitOfMeasure` | UoM definitions || `configurationParameter` / `configurationRule` / `configurationParameterGroup` | Product configurator |diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex ba87d0e46b..6141dc1b19 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -641,7 +641,15 @@ export const itemPlanningValidator = zmaximumInventoryQuantity: zfd.numeric(z.number().min(0)).optional(),minimumOrderQuantity: zfd.numeric(z.number().min(0)).optional(),maximumOrderQuantity: zfd.numeric(z.number().min(0)).optional(),- orderMultiple: zfd.numeric(z.number().min(1)).optional()+ orderMultiple: zfd.numeric(z.number().min(1)).optional(),+ // The planning horizon (time fence) in days from today: the planning grids+ // surface only the actions and suggested orders that fall inside it. Empty+ // = inherit the company default, else no fence; 0 = no fence for this item+ // even when the company has a default.+ planningHorizonDays: zfd.numeric(z.number().int().min(0).optional()),+ // the ownership ladder's leaf override (spec §P1.3): this item at this+ // location; empty = inherit item group → location → company default+ responsibleEmployee: zfd.text(z.string().optional())// critical: zfd.checkbox(),}).refine(diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 6950194f8f..b131986ad9 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -13,7 +13,7 @@ import type {import { storage } from "@carbon/files";import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";-import { datetime, withPathIds } from "@carbon/utils";+import { datetime, isUniqueViolation, withPathIds } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";@@ -274,9 +274,11 @@ async function copyItemPlanningAndPurchasing(.execute();// A reorder policy is only meaningful with its parameters (Maximum- // Quantity needs a reorder point and a maximum, and so on), so the whole- // planning form is copied, location by location. A location the source has- // no planning row for keeps the defaults.+ // Quantity needs a reorder point and a maximum, and so on), so the policy+ // and its sizing parameters are copied together, location by location.+ // The planning horizon and the responsible employee are not copied: a new+ // revision inherits the company defaults for both. A location the source+ // has no planning row for keeps the defaults.await trx.updateTable("itemPlanning as target").from("itemPlanning as source")@@ -7329,7 +7331,7 @@ export async function createChangeNoticeDraftMethod(}// 23505 = unique_violation (makeMethod_unique_itemId_version); a parallel// CO grabbed this number first — recompute the next free version + retry.- if (res.error?.code === "23505") {+ if (isUniqueViolation(res.error)) {const latest = await getActiveMakeMethodId(client, itemId, companyId);nextVersion = (latest?.maxVersion ?? nextVersion) + 1;continue;diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsxindex eba99dc66b..3050c44910 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx@@ -58,9 +58,9 @@ import { DateTime, Empty, Hyperlink } from "~/components";import type { DemandForecastSourceRow } from "~/modules/items/items.service";import type { loader as forecastLoader } from "~/routes/api+/items.$id.$locationId.forecast";import { path } from "~/utils/path";-import type { PlannedOrder } from "../../../purchasing/purchasing.models";import { DemandForecastSourcesPopover } from "./DemandForecastSourcesPopover";import { PlannedOrderDetailsPopover } from "./PlannedOrderDetailsPopover";+import type { ChartPlannedOrder } from "./planningSupplyDemand";import {demandSourceTypes,mergePlannedOrders,@@ -154,14 +154,19 @@ export const ItemPlanningChart = ({locationId,plannedOrders = [],safetyStock,- conversionFactor = 1+ conversionFactor = 1,+ timeFenceDate = null}: {compact?: boolean;itemId: string;locationId: string;- plannedOrders?: PlannedOrder[];+ plannedOrders?: ChartPlannedOrder[];safetyStock?: number;conversionFactor?: number;+ /** The planning horizon's cutoff (ISO date). Marked on the chart as a+ * vertical line on the week it falls in; omitted when there is no fence or+ * it lies outside the charted weeks. */+ timeFenceDate?: string | null;}) => {const { t } = useLingui();const forecastFetcher = useLoaderQuery<typeof forecastLoader>(@@ -195,7 +200,8 @@ export const ItemPlanningChart = ({const empty = {data: [] as ChartDataPoint[],stockoutDate: null as string | null,- belowSafetyDate: null as string | null+ belowSafetyDate: null as string | null,+ timeFenceWeek: null as string | null};if (!forecastFetcher.data?.demand ||@@ -250,11 +256,17 @@ export const ItemPlanningChart = ({}if (groupedData[periodId]) {- // Convert purchase quantity to inventory quantity for display- // Inventory Quantity = Purchase Quantity × Conversion Factor- const purchaseQuantityDelta =+ // A DRAFT order is in purchase units: convert its quantity to+ // inventory units (× conversionFactor). An EXISTING order arrives+ // already converted, with `existingQuantity` in inventory units too+ // (see the purchasing drawer's chartOrders and mergePlannedOrders) —+ // converting it again drew an edit from 5 to 6 boxes of 10 as +100.+ const quantityDelta =(order.quantity ?? 0) - (order.existingQuantity ?? 0);- const inventoryQuantityDelta = purchaseQuantityDelta * conversionFactor;+ const inventoryQuantityDelta =+ order.existingId || order.existingLineId+ ? quantityDelta+ : quantityDelta * conversionFactor;// biome-ignore lint/complexity/useLiteralKeys: suppressed due to migrationgroupedData[periodId]["Planned"] += inventoryQuantityDelta;@@ -336,8 +348,23 @@ export const ItemPlanningChart = ({return period;});- return { data, stockoutDate, belowSafetyDate };+ // The charted week the time fence falls in: the last week starting on or+ // before it. ISO dates order as strings. A fence before the first week or+ // past the last one has no bar to sit on.+ let timeFenceWeek: string | null = null;+ const lastEndDate = periods.reduce(+ (latest, period) => (period.endDate > latest ? period.endDate : latest),+ ""+ );+ if (timeFenceDate && timeFenceDate <= lastEndDate) {+ for (const period of data) {+ if (period.startDate <= timeFenceDate) timeFenceWeek = period.startDate;+ }+ }++ return { data, stockoutDate, belowSafetyDate, timeFenceWeek };}, [+ timeFenceDate,forecastFetcher.data,plannedOrders,conversionFactor,@@ -714,6 +741,23 @@ export const ItemPlanningChart = ({}}/>)}+ {chartData.timeFenceWeek && (+ <ReferenceLine+ x={chartData.timeFenceWeek}+ stroke={chartColors.zero}+ strokeDasharray="2 4"+ label={{+ value: t`Planning horizon`,+ // Recharts mirrors the names on a vertical line:+ // "insideTopLeft" is the side AWAY from the y-axis,+ // so the label never lands on the tick numbers.+ position: "insideTopLeft",+ fill: chartColors.zero,+ fontSize: 11,+ fontWeight: 600+ }}+ />+ )}{chartData.stockoutDate && isShown("projection") && (<ReferenceDotx={chartData.stockoutDate}@@ -1284,7 +1328,7 @@ interface PlanningItem {// Planned-row metadata (only set on rows with sourceType === "Planned").// Carries enough info for PlannedOrderDetailsPopover to render order facts,// policy reasoning, and the linked PO section.- plannedOrder?: PlannedOrder;+ plannedOrder?: ChartPlannedOrder;}const sourceTypeIcons: Record<SourceType, JSX.Element> = {diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsxindex 9b048f1b34..ae4b2264d5 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx@@ -18,6 +18,7 @@ import { useState } from "react";import type { z } from "zod";import {CustomFormFields,+ Employee,Hidden,Number,Select as SelectForm,@@ -33,7 +34,15 @@ import {import { ItemReorderPolicy } from "./ItemReorderPolicy";type ItemPlanningFormProps = {- initialValues: z.infer<typeof itemPlanningValidator>;+ // the DB row carries responsibleEmployee / planningHorizonDays as nullable;+ // the validator treats them as optional — accept both+ initialValues: Omit<+ z.infer<typeof itemPlanningValidator>,+ "responsibleEmployee" | "planningHorizonDays"+ > & {+ responsibleEmployee?: string | null;+ planningHorizonDays?: number | null;+ };locations: ListItem[];type: "Part" | "Material" | "Tool" | "Consumable";};@@ -172,6 +181,19 @@ const ItemPlanningForm = ({)}{/* <Boolean name="critical" label={t`Critical`} /> */}+ <Number+ name="planningHorizonDays"+ label={t`Planning Horizon (Days)`}+ termId="item-planning-horizon"+ minValue={0}+ />++ <Employee+ name="responsibleEmployee"+ label={t`Responsible Employee`}+ type="assignee"+ />+<CustomFormFields table="itemPlanning" /></div></CardContent>diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsxindex 587e95b832..1cb22f74fe 100644--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx@@ -4,18 +4,7 @@import type { Database } from "@carbon/database";import { Status } from "@carbon/react";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";import { Trans } from "@lingui/react/macro";-import { z } from "zod";-import type {- ProductionOrder,- ProductionPlanningItem-} from "~/modules/production";-import type {- PlannedOrder,- PurchasingPlanningItem-} from "~/modules/purchasing";-import type { Item } from "~/stores";import type { ItemReorderingPolicy } from "../../types";export function ItemReorderPolicy({@@ -76,469 +65,3 @@ export function getReorderPolicyDescription(itemPlanning: {return `When stock is below ${reorderPoint}, order up to ${maximumInventoryQuantity} units`;}}--type BaseOrderParams = {- itemPlanning: ProductionPlanningItem | PurchasingPlanningItem;- periods: { startDate: string; id: string }[];-};--// Cache for memoizing calculateOrders results-const ordersCache = new Map<- string,- {- startDate: string;- dueDate: string;- quantity: number;- periodId: string;- isASAP: boolean;- }[]->();--// Generate cache key from itemPlanning and periods-function getCacheKey(- itemPlanning: ProductionPlanningItem | PurchasingPlanningItem,- periods: { startDate: string; id: string }[]-): string {- // Include all relevant properties that affect order calculation- const periodIds = periods.map((p) => p.id).join(",");- const weekValues = Array.from({ length: 48 }, (_, i) => {- const key = `week${i + 1}` as keyof typeof itemPlanning;- return itemPlanning[key] ?? 0;- }).join(",");-- return `${itemPlanning.id}_${itemPlanning.reorderingPolicy}_${itemPlanning.reorderPoint}_${itemPlanning.reorderQuantity}_${itemPlanning.maximumInventoryQuantity}_${itemPlanning.demandAccumulationPeriod}_${itemPlanning.demandAccumulationSafetyStock}_${itemPlanning.leadTime}_${itemPlanning.lotSize}_${itemPlanning.minimumOrderQuantity}_${itemPlanning.maximumOrderQuantity}_${itemPlanning.orderMultiple}_${itemPlanning.supersessionMode}_${itemPlanning.minimumReserveQuantity}_${itemPlanning.quantityOnHand}_${itemPlanning.quantityToOrder}_${periodIds}_${weekValues}`;-}--function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {- startDate: string;- dueDate: string;- quantity: number;- periodId: string;- isASAP: boolean;- policyName?: string;- triggerValues?: {- projectedStock?: number;- safetyStock?: number;- reorderPoint?: number;- reorderQuantity?: number;- lotSize?: number;- leadTime?: number;- };-}[] {- // Check cache first- const cacheKey = getCacheKey(itemPlanning, periods);- const cached = ordersCache.get(cacheKey);- if (cached) {- return cached;- }-- // Stock Only supersession overrides every reordering policy: replenish only to- // the minimum service-stock floor, ignoring demand. The server already computes- // this in get_*_planning (reserve − on-hand − incoming supply), so we reuse its- // quantityToOrder rather than recomputing — keeping the drawer and the table in- // exact agreement (and correctly accounting for what's already on order).- if (itemPlanning.supersessionMode === "Stock Only") {- const reserveOrders: {- startDate: string;- dueDate: string;- quantity: number;- periodId: string;- isASAP: boolean;- policyName?: string;- triggerValues?: {- projectedStock?: number;- safetyStock?: number;- reorderPoint?: number;- reorderQuantity?: number;- lotSize?: number;- leadTime?: number;- };- }[] = [];- const reserveShortfall = Math.max(0, itemPlanning.quantityToOrder ?? 0);- if (reserveShortfall > 0 && periods.length > 0) {- const dueDate = parseDate(periods[0].startDate);- const startDate = dueDate.subtract({ days: itemPlanning.leadTime ?? 0 });- reserveOrders.push({- startDate: startDate.toString(),- dueDate: dueDate.toString(),- quantity: reserveShortfall,- periodId: periods[0].id,- isASAP: startDate.compare(today(getLocalTimeZone())) < 0,- policyName: "Stock Only",- triggerValues: {- projectedStock: itemPlanning.quantityOnHand ?? 0,- reorderPoint: itemPlanning.minimumReserveQuantity ?? 0,- leadTime: itemPlanning.leadTime ?? 0- }- });- }- ordersCache.set(cacheKey, reserveOrders);- return reserveOrders;- }-- if (itemPlanning.reorderingPolicy === "Manual Reorder") {- const emptyOrders: {- startDate: string;- dueDate: string;- quantity: number;- periodId: string;- isASAP: boolean;- policyName?: string;- triggerValues?: {- projectedStock?: number;- safetyStock?: number;- reorderPoint?: number;- reorderQuantity?: number;- lotSize?: number;- leadTime?: number;- };- }[] = [];- ordersCache.set(cacheKey, emptyOrders);- return emptyOrders;- }-- const orders: {- startDate: string;- dueDate: string;- quantity: number;- periodId: string;- isASAP: boolean;- policyName?: string;- triggerValues?: {- projectedStock?: number;- safetyStock?: number;- reorderPoint?: number;- reorderQuantity?: number;- lotSize?: number;- leadTime?: number;- };- }[] = [];-- const {- demandAccumulationPeriod,- demandAccumulationSafetyStock,- leadTime,- lotSize,- maximumInventoryQuantity,- maximumOrderQuantity,- minimumOrderQuantity,- orderMultiple,- reorderPoint,- reorderQuantity- } = itemPlanning;-- const todaysDate = today(getLocalTimeZone());- let orderedQuantity = 0;-- switch (itemPlanning.reorderingPolicy) {- case "Demand-Based Reorder":- // Process periods in chunks of demandAccumulationPeriod.- //- // End-of-window sizing: only fire an order when the LAST period in- // the window dips below safety stock, and size it to lift the- // end-of-window projection back to safety. Mirrors the SQL- // `calculate_quantity_to_order` DBR branch exactly so this client- // calculator and the server-side `quantityToOrder` column agree.- //- // Trade-off: this hides mid-window dips that recover (e.g. PO lands- // late in the window). Acceptable here because the server uses the- // same convention and the planning UI relies on the two being in- // sync.- for (let i = 0; i < periods.length; i += demandAccumulationPeriod) {- const windowEnd = Math.min(- i + demandAccumulationPeriod,- periods.length- );-- // Track first dip (for the order's trigger date) AND walk- // end-of-window projection (for sizing). The end-of-window value- // survives because we overwrite on every iteration — same as the- // SQL function.- let firstDipIndex = -1;- let endOfWindowProjection = 0;- for (let j = i; j < windowEnd; j++) {- const periodKey = `week${j + 1}` as "week1";- const periodProjection = (itemPlanning[periodKey] as number) || 0;- const effective = periodProjection + orderedQuantity;- if (- firstDipIndex === -1 &&- effective < demandAccumulationSafetyStock- ) {- firstDipIndex = j;- }- endOfWindowProjection = effective;- }-- // Skip the window unless end-of-window is below safety.- if (endOfWindowProjection >= demandAccumulationSafetyStock) continue;- // Defensive: if end < safety we should have found a dip, but- // fall back to window start so we never emit an undated order.- if (firstDipIndex === -1) firstDipIndex = i;-- const currentPeriod = periods[firstDipIndex];-- {- let totalOrderQuantity = Math.max(- 0,- demandAccumulationSafetyStock - endOfWindowProjection- );-- // Apply lot sizing rules- if (maximumOrderQuantity > 0) {- totalOrderQuantity = Math.min(- totalOrderQuantity,- maximumOrderQuantity- );- }- totalOrderQuantity = Math.max(- totalOrderQuantity,- minimumOrderQuantity- );-- if (orderMultiple > 0) {- totalOrderQuantity =- Math.ceil(totalOrderQuantity / orderMultiple) * orderMultiple;- }-- // If we have a lot size and need to split orders- if (lotSize > 0 && totalOrderQuantity > lotSize) {- const numberOfBatches = Math.ceil(totalOrderQuantity / lotSize);- const daysInPeriod = 7; // Assuming weekly periods-- for (let batch = 0; batch < numberOfBatches; batch++) {- const batchQuantity = Math.min(- lotSize,- totalOrderQuantity - batch * lotSize- );-- // Spread due dates evenly across the period- const dueDateOffset = Math.floor(- (batch * daysInPeriod) / numberOfBatches- );- const dueDate = parseDate(currentPeriod.startDate).add({- days: dueDateOffset- });- const startDate = dueDate.subtract({ days: leadTime });-- orders.push({- startDate: startDate.toString(),- dueDate: dueDate.toString(),- quantity: batchQuantity,- periodId: currentPeriod.id,- isASAP: startDate.compare(todaysDate) < 0,- policyName: "Demand-Based Reorder",- triggerValues: {- projectedStock: endOfWindowProjection,- safetyStock: demandAccumulationSafetyStock,- lotSize,- leadTime- }- });- }- } else {- // Single order for the period- const orderQuantity =- lotSize > 0- ? Math.min(totalOrderQuantity, lotSize)- : totalOrderQuantity;-- const dueDate = parseDate(currentPeriod.startDate);- const startDate = dueDate.subtract({ days: leadTime });-- orders.push({- startDate: startDate.toString(),- dueDate: dueDate.toString(),- quantity: orderQuantity,- periodId: currentPeriod.id,- isASAP: startDate.compare(todaysDate) < 0,- policyName: "Demand-Based Reorder",- triggerValues: {- projectedStock: endOfWindowProjection,- safetyStock: demandAccumulationSafetyStock,- lotSize,- leadTime- }- });- }-- orderedQuantity += totalOrderQuantity;- }- }-- ordersCache.set(cacheKey, orders);- return orders;- case "Fixed Reorder Quantity":- for (let i = 0; i < periods.length; i++) {- const period = periods[i];- const periodKey = `week${i + 1}` as "week1";- const projectedQuantity = (itemPlanning[periodKey] as number) || 0;-- // Check if we need to order based on reorder point- let remainingQuantityNeeded =- reorderPoint - (projectedQuantity + orderedQuantity);-- let day = 0;- let maxIterations = 100; // Safety counter to prevent infinite loops- while (remainingQuantityNeeded > 0 && day < 5 && maxIterations-- > 0) {- const dueDate = parseDate(period.startDate).add({ days: day });- const startDate = dueDate.subtract({- days: leadTime- });-- // If reorder quantity is 0, order the same quantity as the reorder point- const orderQuantity =- reorderQuantity > 0 ? reorderQuantity : reorderPoint;-- orders.push({- startDate: startDate.toString(),- dueDate: dueDate.toString(),- quantity: orderQuantity,- periodId: period.id,- isASAP: startDate.compare(todaysDate) < 0,- policyName: "Fixed Reorder Quantity",- triggerValues: {- projectedStock: projectedQuantity + orderedQuantity,- reorderPoint,- reorderQuantity,- leadTime- }- });- day++;- orderedQuantity += orderQuantity;- remainingQuantityNeeded =- reorderPoint - (projectedQuantity + orderedQuantity);- }- }-- ordersCache.set(cacheKey, orders);- return orders;- case "Maximum Quantity":- for (let i = 0; i < periods.length; i++) {- const period = periods[i];- const periodKey = `week${i + 1}` as "week1";- const projectedQuantity = (itemPlanning[periodKey] as number) || 0;-- // Check if we need to order based on reorder point- let remainingQuantityNeeded =- reorderPoint - (projectedQuantity + orderedQuantity);-- let day = 0;- let maxIterations = 100; // Safety counter to prevent infinite loops- while (remainingQuantityNeeded > 0 && day < 5 && maxIterations-- > 0) {- const dueDate = parseDate(period.startDate).add({ days: day });- const startDate = dueDate.subtract({- days: leadTime- });-- // Calculate required quantity up to maximum inventory- const requiredQuantity =- maximumInventoryQuantity - (projectedQuantity + orderedQuantity);-- // If reorder quantity is 0, use reorder point as the base order quantity- let orderQuantity =- reorderQuantity > 0- ? Math.max(minimumOrderQuantity, requiredQuantity)- : reorderPoint;-- // Ensure orderQuantity is positive to prevent infinite loop- if (orderQuantity <= 0) {- break;- }-- // Round to nearest multiple if specified- if (orderMultiple && orderMultiple > 1) {- orderQuantity =- Math.ceil(orderQuantity / orderMultiple) * orderMultiple;- }-- // Only apply lot size if it's greater than 0- if (lotSize > 0) {- orderQuantity = Math.ceil(orderQuantity / lotSize) * lotSize;- }-- // Apply maximum order quantity only if it's greater than 0- if (maximumOrderQuantity > 0) {- orderQuantity = Math.min(orderQuantity, maximumOrderQuantity);- }-- orders.push({- startDate: startDate.toString(),- dueDate: dueDate.toString(),- quantity: orderQuantity,- periodId: period.id,- isASAP:- startDate.compare(todaysDate) < 0 &&- projectedQuantity + orderedQuantity < 0,- policyName: "Maximum Quantity",- triggerValues: {- projectedStock: projectedQuantity + orderedQuantity,- reorderPoint,- leadTime,- reorderQuantity- }- });- day++;- orderedQuantity += orderQuantity;- remainingQuantityNeeded =- reorderPoint - (projectedQuantity + orderedQuantity);- }- }- ordersCache.set(cacheKey, orders);- return orders;- default:- ordersCache.set(cacheKey, orders);- return orders;- }-}--// Export function to clear the cache if needed (e.g., after MRP runs)-export function clearOrdersCache() {- ordersCache.clear();-}--export function getProductionOrdersFromPlanning(- itemPlanning: ProductionPlanningItem,- periods: { startDate: string; id: string }[]-): ProductionOrder[] {- return calculateOrders({ itemPlanning, periods });-}--const supplierPartValidator = z.array(- z.object({- id: z.string(),- supplierId: z.string(),- supplierUnitOfMeasureCode: z.string(),- conversionFactor: z.number(),- unitPrice: z.number()- })-);--export function getPurchaseOrdersFromPlanning(- itemPlanning: PurchasingPlanningItem,- periods: { startDate: string; id: string }[],- items: Item[],- supplierId?: string-): PlannedOrder[] {- const suppliers = supplierPartValidator.safeParse(itemPlanning.suppliers);- const supplier = suppliers.data?.find(- (supplier) => supplier.supplierId === supplierId- );-- const item = items.find((item) => item.id === itemPlanning.id);-- // Get the conversion factor from the selected supplier- const conversionFactor = supplier?.conversionFactor ?? 1;-- return calculateOrders({ itemPlanning, periods }).map((order) => ({- ...order,- // Convert inventory quantity to purchase quantity by dividing by conversion factor- quantity:- conversionFactor > 0- ? Math.ceil(order.quantity / conversionFactor)- : order.quantity,- supplierId: supplier?.supplierId ?? itemPlanning.preferredSupplierId,- itemReadableId: item?.readableIdWithRevision,- description: item?.name,- unitOfMeasureCode: item?.unitOfMeasureCode- }));-}diff --git a/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsx b/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsxindex f69a7ef682..9a821728a2 100644--- a/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsx+++ b/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsx@@ -18,15 +18,15 @@ import { LuInfo } from "react-icons/lu";import { Link } from "react-router";import { DateTime } from "~/components";import { useCurrencyFormatter } from "~/hooks";-import type { PlannedOrder } from "~/modules/purchasing/purchasing.models";import { PurchasingStatus } from "~/modules/purchasing/ui/PurchaseOrder";import { useSuppliers } from "~/stores";import { path } from "~/utils/path";import { ItemReorderPolicy } from "./ItemReorderPolicy";import { getItemLifecycleStatus } from "./ItemSupersessionForm";+import type { ChartPlannedOrder } from "./planningSupplyDemand";type Props = {- order: PlannedOrder;+ order: ChartPlannedOrder;conversionFactor: number;children: ReactNode;};@@ -300,7 +300,7 @@ export function PlannedOrderDetailsPopover({<Trans>Status</Trans></dt><dd>- {/* @ts-expect-error - status is a string because we have a general type for purchase orders and purchaseOrderLines */}+ {/* @ts-expect-error - a ChartPlannedOrder carries a job OR a purchase order status as text */}<PurchasingStatus status={order.existingStatus} /></dd></>diff --git a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.tsindex f0f9c43aee..d0076b6695 100644--- a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts+++ b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts@@ -4,6 +4,15 @@import type { PlannedOrder } from "../../../purchasing/purchasing.models";+/**+ * An order the planning chart draws: purchasing's `PlannedOrder` or+ * production's `ProductionOrder`. Each carries its own document's status enum+ * (purchase order / job), so the chart reads the status as text.+ */+export type ChartPlannedOrder = Omit<PlannedOrder, "existingStatus"> & {+ existingStatus?: string;+};+export const supplySourceTypes = ["Purchase Order","Production Order"@@ -24,13 +33,13 @@ export type SupplyDemandRow = {documentReadableId: string | null;};-export function existingRowId(order: PlannedOrder) {+export function existingRowId(order: ChartPlannedOrder) {return order.existingLineId ?? order.existingId;}export function mergePlannedOrders<T extends SupplyDemandRow>(rows: T[],- plannedOrders: PlannedOrder[],+ plannedOrders: ChartPlannedOrder[],conversionFactor: number,quantityOnHand: number) {diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 6fa88d0c4a..32bb984f4c 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -77,7 +77,8 @@ pnpm --filter @carbon/erp test| `assemblyInstructionStepTool` | Tools used at a step (`stepId` → `itemId` of a tool-type item + `quantity`, UNIQUE `(stepId, itemId)`) — `itemId` is the same target `jobOperationTool.toolId` references, so the BOP sync maps rows 1:1 || `assemblyComponentMapping` / `assemblyUnit` / `assemblyPlanJob` | Geometry↔BOM item mapping, authored planner units (model-scoped "plan as one component" overrides), and geometry-service plan/convert job tracking. Planning is LAZY — conversion does not chain a plan run; the first "Generate Steps" click (or an explicit re-plan) starts it, pre-creating a Queued `assemblyPlanJob` row the worker adopts via `planJobId`. The clicking tab polls and auto-generates the steps when the plan lands || `maintenanceDispatch` / `maintenanceSchedule` | Equipment maintenance tracking |-| `demandForecast` / `demandProjection` | Demand planning data |+| `demandForecast` / `demandProjection` | Demand planning data; `demandProjection.consumedQuantity` is MRP-written (forecast consumption), never user-edited |+| `planningAction` | The MRP worklist: one row per suggestion (`type` Order / Make / Expedite / Defer / Cancel / Increase / Decrease / Release, `status` Open / Dismissed / Actioned, `suggestedQuantity`, `suggestedDate`, `horizonDate`, `latestOrderDate`, `isASAP`, `requiresManualAction`, target `jobId` / `purchaseOrderLineId`, `supplierId`, `assignee` + `assigneeOverridden`, the attribution `policyName` / `reason` / `triggerValues`, and the natural key `itemId` / `locationId` / `periodId`). Diff-written by `generatePlanningActions` after every run; read-only through the API (read `production_view` or `purchasing_view`) || `scrapReason` / `maintenanceFailureMode` | Reference data for production and maintenance |## Key Service Functions@@ -104,7 +105,10 @@ pnpm --filter @carbon/erp test- `getPeopleCapacityOperations` — open `jobOperation` hours for the Capacity view (excludes Done/Canceled ops and Draft/Planned/Completed/Cancelled/Closed jobs — released load only)- `getCapacityReservationsForResources` — live reservations across jobs (resource timeline + Capacity view's Scheduled series)- `getCompletionJobs` — the Outbound report (`x+/scheduling+/outbound.tsx`, Production → Scheduling → Outbound), RPC `get_completion_jobs` (migration `20260930150428`, SECURITY INVOKER): open (`Planned`/`Ready`/`In Progress`/`Paused`) jobs at a location that fill a sales order, with the ship-to (`salesOrder.customerLocationId`, or the shipment's customer location on a drop shipment), ship-via, promised date and top-level operations. `completionDate` = the projected completion's day in the location's timezone, else the due date; the service orders by it (paged with `fetchAllRecords`) and the table groups on it via `groupRowsBy`-- `getProductionPlanning` — MRP-driven production planning (RPC `get_production_planning`)+- `getProductionPlanning` — MRP-driven production planning (RPC `get_production_planning_grid`, latest migration `20261006205037`: wraps `get_production_planning` and adds the item group, the planning-horizon fence date, the first negative week, the latest order date and `orderQuantity` — the open Make actions inside the fence, which the default sort uses (the Order / Make button shows the quantity; there is no Qty to Order column), not the base RPC's `quantityToOrder`; `asOf` is the location's today, and `actionTypes` / `actionAssignees` filter on OPEN planning actions inside each item's fence, in the database)+- `nextJobPriority(siblings, deadlineType)` — pure: a job's fractional priority among the jobs already on its date, by deadline type; `calculateJobPriority` reads the siblings and calls it, the planning date apply places a batch with it. `deadlineTypeForPlanningDate(deadlineType)` — the type a job carries once planning gives it a date (No Deadline → Soft Deadline)+- `cancelJob` (`production.server.ts`) — the one cancel path, used by `x+/job+/$jobId.status.tsx` and planning's Cancel action: returns the job's unconsumed picked material, cancels its open picking-list lines, then sets Cancelled and clears the assignee; stops at the first failure, before the status changes. Planning edits a job only while `isJobEditableFromPlanning` (`production.models.ts`: Draft / Planned)+- `getPlanningActions` / `getPlanningActionsByIds` — the persisted MRP worklist (`planningAction`, written by `generatePlanningActions` in `@carbon/planning` after every MRP run; statuses `Open` / `Dismissed` / `Actioned`). `dismissPlanningActions` / `reopenDismissedPlanningActions` (Dismissed ↔ Open; both return the ids they changed, which the routes report), `markPlanningActionsActioned` (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and `reopenPlanningActions` (its rollback, Actioned → Open), `assignPlanningActions` (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). `settleNewSupplyPlanningActions` is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (`Order`) or jobs (`Make`) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (`getPlanningActionsByIds`) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: `applyProductionPlanningDateActions(db, …)` moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure `nextJobPriority` — a "No Deadline" job becomes `Soft Deadline`, `deadlineTypeForPlanningDate`, since the job form hides the due date for No Deadline), and the route sends one `schedule-inputs-changed` event for the batch; Increase / Decrease / Cancel call server functions with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in `planning-action-claims.ts` (`claimPlanningActions` / `releasePlanningActionClaims`), shared with purchasing's `applyPurchasingPlanningActions`. Bad input to either planning route answers 400, a failed read or write 500. `releasePlanningActionClaim` gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and `updatePlanningJob` is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates `scrapQuantity` from the item's scrap rate. `planningAction` is read-only through the API; its writers use the service role. Applied from `x+/production+/planning.update.tsx` and `x+/purchasing+/planning.update.tsx`; UI in `ui/Planning/`: `ProductionPlanningTable` + `ProductionPlanningOrderDrawer`, `planningColumns.tsx` (the column set shared with purchasing: the Stock Availability week strip via `PlanningWeekStrip` + `planning-week-geometry.ts`, `LatestOrderDate`, `PlanningFence` + `planning-fence.ts`), `PlanningActionLines` (the expanded row), `PlanningOrderGrids` + `PlanningDrawerParts` (the drawer's suggested / open-order grids, `periodIdFor`, the "N More After" button), `usePlanningActions` (the dismiss / reopen / assign / apply fetcher), and `planning-action-scope.ts` (`resolvePlanningActionScope`, `actionsOfTypes`, `PLANNING_ACTIONS_COLUMN`, `PLANNING_ASSIGNEE_COLUMN`, `PLANNING_DRAWER_PARAM` — pure, re-exported from `production.models.ts` so vitest can import it), `planned-orders-from-actions.ts` (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — `openNewSupplyActions`, `plannedOrdersFromActions`, `productionOrdersFromActions`, `supplierConversionFactor` — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), `planning-increase.ts` (pure: `chartedOrderQuantity` charts an order at its open Increase), and `planning-review.ts` (pure: `planningActionNeedsReview` — Review vs Apply from the order's LIVE status, `purchaseOrderStatus` / `jobStatus` from `getPlanningActions`, not MRP's run-time `requiresManualAction` stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and `purchaseOrderPlanningMenu`, which order commands a row's ⋯ offers; `PlanningActionHandlers.purchaseOrderMenuItems` carries them, purchasing only). Both planning grids put the open order drawer's item in the address (`?item=<itemId>`, `useLinkedDrawerItem` in `~/hooks/useDrawerItem`), so a link reopens it; the loader reads that row on its own (`drawerItem`) when it is not on the page. Tests: `planning-action-writes.test.ts`, `apps/erp/test/apply-production-planning-date-actions.test.ts`, `planning-action-scope.test.ts`, `planning-fence.test.ts`, `planning-increase.test.ts`, `planning-review.test.ts`, `planned-orders-from-actions.test.ts`, `planning-week-geometry.test.ts`- `upsertMaintenanceDispatch` / `upsertMaintenanceSchedule` — maintenance management- `updateAssemblyStepHiddenComponents` — autosave for a step's hidden list (route `x+/assembly+/$id.steps.hidden.$stepId.tsx`). The rule "a step never hides its own parts" lives in ONE place, the `assembly_step_strip_own_hidden_components` BEFORE trigger (migration `20260925063121`), which strips + dedupes on every insert/update of either array — no service strips it by hand.- `getAssemblyInstruction(s)` / `upsertAssemblyInstructionStep` / `getAssemblyInstructionStepMaterials` — assembly instruction authoring; the step upsert derives `instructionText` from the tiptap `description` (viewer/MES consume the plain text)diff --git a/apps/erp/app/modules/production/planning-action-claims.ts b/apps/erp/app/modules/production/planning-action-claims.tsnew file mode 100644index 0000000000..98c4313721--- /dev/null+++ b/apps/erp/app/modules/production/planning-action-claims.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { sql, type Transaction } from "kysely";++// The claim half of a set-based Apply, shared by the purchasing and the+// production apply (purchasing.service.ts / production.service.ts). Both run+// inside the caller's transaction, so a claim, its write and its release+// commit together or not at all.++type Handle = Kysely<KyselyDatabase> | Transaction<KyselyDatabase>;++/**+ * Flip every Open action of the batch to Actioned and return the ids that+ * flipped. One that does not flip was applied by someone else since the page+ * loaded, and the caller leaves its target alone — a stale page never+ * overwrites a later manual edit. The conditional update is the lock.+ */+export type ClaimedPlanningAction = {+ suggestedDate: string | null;+ suggestedQuantity: number | null;+};++/**+ * The claim RETURNS the suggestion as it is at the moment of the claim. The+ * caller read the actions a request earlier, and an MRP run in between may+ * have moved an Open action's quantity or date in place; applying the values+ * from the page would write the stale suggestion. Apply what was claimed.+ */+export async function claimPlanningActions(+ trx: Handle,+ args: { ids: string[]; companyId: string; userId: string; now: string }+): Promise<Map<string, ClaimedPlanningAction>> {+ if (args.ids.length === 0) return new Map();+ const rows = await trx+ .updateTable("planningAction")+ .set({ status: "Actioned", updatedBy: args.userId, updatedAt: args.now })+ .where("id", "in", args.ids)+ .where("companyId", "=", args.companyId)+ .where("status", "=", "Open")+ .returning(["id", "suggestedDate", "suggestedQuantity"])+ .execute();+ return new Map(+ rows.map((row) => [+ row.id,+ {+ suggestedDate: row.suggestedDate ?? null,+ suggestedQuantity:+ row.suggestedQuantity === null || row.suggestedQuantity === undefined+ ? null+ : Number(row.suggestedQuantity)+ }+ ])+ );+}++/**+ * Give claimed actions back: to Open, so the planner can try again — or+ * deleted, when an MRP run has meanwhile written a fresh Open row for the same+ * need (the reopen would hit the natural-key unique index; that fresh row+ * replaces this one). The same two steps `releasePlanningActionClaim` takes+ * outside a transaction.+ */+export async function releasePlanningActionClaims(+ trx: Handle,+ args: { ids: string[]; companyId: string; userId: string; now: string }+): Promise<void> {+ if (args.ids.length === 0) return;+ const reopened = await sql<{ id: string }>`+ UPDATE "planningAction" AS a+ SET "status" = 'Open', "updatedBy" = ${args.userId}, "updatedAt" = ${args.now}+ WHERE a."id" IN (${sql.join(args.ids.map((id) => sql`${id}`))})+ AND a."companyId" = ${args.companyId}+ AND a."status" = 'Actioned'+ AND NOT EXISTS (+ SELECT 1 FROM "planningAction" o+ WHERE o."companyId" = a."companyId"+ AND o."itemId" = a."itemId"+ AND o."locationId" = a."locationId"+ AND o."type" = a."type"+ AND COALESCE(o."purchaseOrderLineId", o."jobId", o."periodId")+ = COALESCE(a."purchaseOrderLineId", a."jobId", a."periodId")+ AND o."status" <> 'Actioned'+ AND o."id" <> a."id"+ )+ RETURNING a."id"+ `.execute(trx);+ const reopenedIds = new Set(reopened.rows.map((row) => row.id));+ const toDelete = args.ids.filter((id) => !reopenedIds.has(id));+ if (toDelete.length > 0) {+ await trx+ .deleteFrom("planningAction")+ .where("id", "in", toDelete)+ .where("companyId", "=", args.companyId)+ .where("status", "=", "Actioned")+ .execute();+ }+}diff --git a/apps/erp/app/modules/production/planning-action-writes.test.ts b/apps/erp/app/modules/production/planning-action-writes.test.tsnew file mode 100644index 0000000000..19a3ec4a1a--- /dev/null+++ b/apps/erp/app/modules/production/planning-action-writes.test.ts@@ -0,0 +1,267 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { KyselyDatabase } from "@carbon/database/client";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";+import { describe, expect, it, vi } from "vitest";+import type { PlanningActionKind } from "./production.service";++// Same module-graph stubs as production.service.test.ts: the functions under+// test need neither the glossary nor the Lingui macro.+vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>+ Array.isArray(strings)+ ? strings.reduce(+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),+ ""+ )+ : String(strings)+}));++const {+ assignPlanningActions,+ dismissPlanningActions,+ getPlanningActionsByIds,+ markPlanningActionsActioned,+ reopenDismissedPlanningActions,+ settleNewSupplyPlanningActions+} = await import("./production.service");++// The Postgres wire is the boundary: every statement is recorded as compiled+// SQL with its parameters, and the rows the database would have changed come+// back as the result.+class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ constructor(private readonly rows: unknown[] = []) {+ super();+ }+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ this.sent.push(query);+ return { rows: this.rows as R[] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+}++function database(changedIds: string[] = []) {+ const driver = new RecordingDriver(changedIds.map((id) => ({ id })));+ const db = new Kysely<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ });+ return { db, driver };+}++const args = {+ ids: ["a1", "a2", "a3"],+ companyId: "c1",+ userId: "u1",+ kind: "Make" as PlanningActionKind+};++// The routes reported the ids they were SENT ("Dismissed 5") while the update+// skipped rows that had changed since the page loaded.+describe("planning action worklist writes return the rows they changed", () => {+ it("dismiss changes only Open rows and returns their ids", async () => {+ const { db, driver } = database(["a1"]);+ const result = await dismissPlanningActions(db, args);+ expect(result).toEqual({ data: [{ id: "a1" }], error: null });+ const [statement] = driver.sent;+ expect(statement?.sql).toMatch(/^update "planningAction"/);+ expect(statement?.sql).toContain('"status" = $');+ expect(statement?.sql).toContain('returning "id"');+ expect(statement?.parameters).toContain("Open");+ expect(statement?.parameters).toContain("c1");+ });++ it("reopen changes only Dismissed rows and returns their ids", async () => {+ const { db, driver } = database(["a2"]);+ const result = await reopenDismissedPlanningActions(db, args);+ expect(result).toEqual({ data: [{ id: "a2" }], error: null });+ expect(driver.sent[0]?.parameters).toContain("Dismissed");+ });++ // Assign had no status condition: it re-owned actions already applied.+ it("assign never changes an applied action", async () => {+ const { db, driver } = database(["a1", "a3"]);+ const result = await assignPlanningActions(db, {+ ...args,+ assignee: "u2"+ });+ expect(result).toEqual({ data: [{ id: "a1" }, { id: "a3" }], error: null });+ const [statement] = driver.sent;+ expect(statement?.sql).toContain('"status" in ($');+ expect(statement?.parameters).toEqual(+ expect.arrayContaining(["Open", "Dismissed", "c1"])+ );+ expect(statement?.parameters).not.toContain("Actioned");+ });++ // The claim is the lock of the apply path: only Open rows flip, in ONE+ // statement, and the caller gets back exactly the rows it now holds.+ it("claim flips only Open rows to Actioned in one statement", async () => {+ const { db, driver } = database(["a1"]);+ const result = await markPlanningActionsActioned(db, args);+ expect(result).toEqual({ data: [{ id: "a1" }], error: null });+ expect(driver.sent).toHaveLength(1);+ expect(driver.sent[0]?.parameters).toEqual(+ expect.arrayContaining(["Actioned", "Open", "c1", "a1", "a2", "a3"])+ );+ });++ // The writes run past row-level security, so the page's permission was the+ // only check: a purchasing user could dismiss production's actions by id.+ it.each([+ ["dismiss", dismissPlanningActions],+ ["reopen", reopenDismissedPlanningActions],+ [+ "assign",+ (db: Kysely<KyselyDatabase>, a: typeof args) =>+ assignPlanningActions(db, { ...a, assignee: "u2" })+ ]+ ] as const)("%s writes only its own page's actions", async (_, write) => {+ const make = database(["a1"]);+ await write(make.db, args);+ expect(make.driver.sent[0]?.sql).toContain('"jobId" is not null');+ expect(make.driver.sent[0]?.sql).not.toContain('"purchaseOrderLineId"');+ expect(make.driver.sent[0]?.parameters).toContain("Make");++ const buy = database(["a1"]);+ await write(buy.db, { ...args, kind: "Buy" });+ expect(buy.driver.sent[0]?.sql).toContain(+ '"purchaseOrderLineId" is not null'+ );+ expect(buy.driver.sent[0]?.sql).not.toContain('"jobId"');+ expect(buy.driver.sent[0]?.parameters).toContain("Order");+ });++ it("sends nothing for an empty id list", async () => {+ const { db, driver } = database();+ const result = await dismissPlanningActions(db, { ...args, ids: [] });+ expect(result).toEqual({ data: [], error: null });+ expect(driver.sent).toHaveLength(0);+ });+});++// Apply read each action on its own; a batch of N is now one statement — and+// the ids travel as parameters, never in a PostgREST URL, so a bulk Apply on a+// page of busy items (hundreds of ids) cannot overrun the gateway.+describe("getPlanningActionsByIds", () => {+ it("reads the whole batch in one company-scoped statement", async () => {+ const ids = Array.from({ length: 500 }, (_, i) => `a${i}`);+ const { db, driver } = database();+ const result = await getPlanningActionsByIds(db, { ids, companyId: "c1" });+ expect(result).toEqual({ data: [], error: null });+ expect(driver.sent).toHaveLength(1);+ const [statement] = driver.sent;+ expect(statement?.sql).toMatch(/^select \* from "planningAction"/);+ expect(statement?.sql).toContain('"id" in (');+ expect(statement?.parameters).toContain("c1");+ expect(statement?.parameters).toEqual(expect.arrayContaining(ids));+ });++ it("reports a failed read instead of throwing", async () => {+ const { db } = database();+ const failing = db.withPlugin({+ transformQuery: (args) => args.node,+ transformResult: async () => {+ throw new Error("connection refused");+ }+ });+ const result = await getPlanningActionsByIds(failing, {+ ids: ["a1"],+ companyId: "c1"+ });+ expect(result).toEqual({+ data: null,+ error: { message: "connection refused" }+ });+ });+});++// The page's Order button raised PO lines and jobs but never touched the+// suggestions they answered, which stayed Open on the page until the next MRP+// run re-derived the worklist.+describe("settleNewSupplyPlanningActions", () => {+ const settle = {+ companyId: "c1",+ locationId: "l1",+ userId: "u1",+ type: "Order" as const+ };++ it("settles each ordered (item, week) in one statement", async () => {+ const { db, driver } = database(["a1", "a2"]);+ const result = await settleNewSupplyPlanningActions(db, {+ ...settle,+ ordered: [+ { itemId: "i1", periodId: "p1" },+ { itemId: "i1", periodId: "p1" },+ { itemId: "i2", periodId: "p2" }+ ]+ });+ expect(result).toEqual({ data: [{ id: "a1" }, { id: "a2" }], error: null });+ expect(driver.sent).toHaveLength(1);+ const [statement] = driver.sent;+ expect(statement?.sql).toMatch(/^update "planningAction"/);+ // pairs, never a cross product: ordering i1 in p1 and i2 in p2 must not+ // settle i1's p2 suggestion+ expect(statement?.sql).toContain(+ '("itemId" = $9 and "periodId" = $10) or ("itemId" = $11 and "periodId" = $12)'+ );+ expect(statement?.parameters).toEqual([+ "Actioned",+ "u1",+ expect.any(String),+ "c1",+ "l1",+ "Order",+ "Open",+ "Dismissed",+ "i1",+ "p1",+ "i2",+ "p2"+ ]);+ });++ it("sends nothing when no order was placed", async () => {+ const { db, driver } = database();+ const result = await settleNewSupplyPlanningActions(db, {+ ...settle,+ ordered: []+ });+ expect(result).toEqual({ data: [], error: null });+ expect(driver.sent).toHaveLength(0);+ });+});diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex e08a5129a8..fac4ecef81 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -68,6 +68,43 @@ export const jobStatus = ["Due Today" // deprecated] as const;+export const planningActionType = [+ "Order",+ "Make",+ "Expedite",+ "Defer",+ "Cancel",+ "Increase",+ "Decrease",+ "Release"+] as const;++export const planningActionStatus = ["Open", "Dismissed", "Actioned"] as const;++// Pure (no lingui / JSX) so the ERP vitest suite can import it directly — the+// models barrel drags the glossary's lingui macros, which vitest does not+// transform (see apps/erp/test/job-complete-logic.test.ts).+export {+ actionsOfTypes,+ PLANNING_ACTIONS_COLUMN,+ PLANNING_ASSIGNEE_COLUMN,+ PLANNING_DRAWER_PARAM,+ resolvePlanningActionScope+} from "./ui/Planning/planning-action-scope";++/**+ * The job statuses planning may change: Apply on a planning action and the+ * order drawer's inline edits. An allowlist on purpose — a job past Planned is+ * on the floor, finished, closed or cancelled, and is reviewed on the job.+ */+export const PLANNING_EDITABLE_JOB_STATUSES = ["Draft", "Planned"] as const;++export function isJobEditableFromPlanning(+ status: Database["public"]["Enums"]["jobStatus"] | null | undefined+): boolean {+ return PLANNING_EDITABLE_JOB_STATUSES.some((editable) => editable === status);+}+export const JOB_LOCKED_STATUSES = ["Completed","Closed",@@ -985,7 +1022,7 @@ export const productionOrderValidator = z.object({existingId: zfd.text(z.string().optional()),existingQuantity: zfd.numeric(z.number().optional()),existingReadableId: zfd.text(z.string().optional()),- existingStatus: zfd.text(z.string().optional()),+ existingStatus: zfd.text(z.enum(jobStatus).optional()),isASAP: z.boolean().optional()});diff --git a/apps/erp/app/modules/production/production.server.test.ts b/apps/erp/app/modules/production/production.server.test.tsnew file mode 100644index 0000000000..fad20bdc0f--- /dev/null+++ b/apps/erp/app/modules/production/production.server.test.ts@@ -0,0 +1,199 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: vi.fn(() => ({}))+}));+vi.mock("@carbon/env", () => ({+ ASSEMBLER_SERVICE_URL: ""+}));+vi.mock("@carbon/server-functions", () => ({+ serverFns: { system: () => ({}), as: () => ({}) }+}));+vi.mock("~/modules/inventory/inventory.service", () => ({+ cancelOpenPickingListsForJob: vi.fn()+}));+// production.models reaches the module barrels (and through them a Supabase+// client built at import); cancelJob needs nothing from it.+vi.mock("./production.models", () => ({+ isJobLocked: vi.fn(() => false)+}));+vi.mock("./production.service", () => ({+ getJobReleaseReadiness: vi.fn(),+ recalculateJobRequirements: vi.fn(),+ returnPickedRemaindersForJob: vi.fn(),+ runMRP: vi.fn(),+ updateJobStatus: vi.fn()+}));++import { cancelOpenPickingListsForJob } from "~/modules/inventory/inventory.service";+import { cancelJob } from "./production.server";+import {+ returnPickedRemaindersForJob,+ updateJobStatus+} from "./production.service";++// cancelJob is the one cancel path (the job status route and planning's+// Cancel action both call it). Its contract is the ORDER of its three steps+// and that it stops at the first failure, before the status changes.+describe("cancelJob", () => {+ const events: string[] = [];+ const args = {+ client: {} as never,+ db: {} as never,+ jobId: "job-1",+ companyId: "company-1",+ userId: "user-1"+ };++ beforeEach(() => {+ vi.clearAllMocks();+ events.length = 0;+ vi.mocked(returnPickedRemaindersForJob).mockImplementation((async () => {+ events.push("returnPickedRemainders");+ return { error: null };+ }) as never);+ vi.mocked(cancelOpenPickingListsForJob).mockImplementation((async () => {+ events.push("cancelOpenPickingLists");+ return { error: null };+ }) as never);+ vi.mocked(updateJobStatus).mockImplementation((async () => {+ events.push("updateJobStatus");+ return { data: null, error: null, updated: true };+ }) as never);+ });++ it("returns picked material, then cancels the picking lists, then sets Cancelled", async () => {+ await expect(cancelJob(args)).resolves.toBeNull();++ expect(events).toEqual([+ "returnPickedRemainders",+ "cancelOpenPickingLists",+ "updateJobStatus"+ ]);+ expect(returnPickedRemaindersForJob).toHaveBeenCalledWith(+ expect.anything(),+ args.db,+ { jobId: "job-1", userId: "user-1", companyId: "company-1" }+ );+ expect(cancelOpenPickingListsForJob).toHaveBeenCalledWith(args.db, {+ jobId: "job-1",+ companyId: "company-1",+ userId: "user-1"+ });+ expect(updateJobStatus).toHaveBeenCalledWith(args.client, {+ id: "job-1",+ companyId: "company-1",+ status: "Cancelled",+ assignee: null,+ updatedBy: "user-1"+ });+ });++ it("stops before the picking lists when returning material fails", async () => {+ vi.mocked(returnPickedRemaindersForJob).mockResolvedValueOnce({+ error: new Error("sweep failed")+ } as never);++ const failed = await cancelJob(args);++ expect(failed?.message).toBe(+ "Cancel aborted: returning picked material failed"+ );+ expect(cancelOpenPickingListsForJob).not.toHaveBeenCalled();+ expect(updateJobStatus).not.toHaveBeenCalled();+ });++ it("stops before the status when the picking lists cannot be closed", async () => {+ vi.mocked(cancelOpenPickingListsForJob).mockResolvedValueOnce({+ error: new Error("lists failed")+ } as never);++ const failed = await cancelJob(args);++ expect(failed?.message).toBe(+ "Cancel aborted: its picking lists could not be closed"+ );+ expect(returnPickedRemaindersForJob).toHaveBeenCalledOnce();+ expect(updateJobStatus).not.toHaveBeenCalled();+ });++ it("reports a failed status update", async () => {+ vi.mocked(updateJobStatus).mockImplementationOnce((async () => {+ events.push("updateJobStatus");+ return { data: null, error: new Error("update failed"), updated: false };+ }) as never);++ const failed = await cancelJob(args);++ expect(failed?.message).toBe("Failed to update job status");+ expect(events).toEqual([+ "returnPickedRemainders",+ "cancelOpenPickingLists",+ "updateJobStatus"+ ]);+ });++ // Planning's Cancel read the status earlier. A job released since must not+ // have its picks returned: cancelJob checks the status before anything else.+ describe("with fromStatuses", () => {+ const jobWithStatus = (status: string) =>+ ({+ from: () => ({+ select: () => ({+ eq: () => ({+ eq: () => ({+ maybeSingle: async () => ({ data: { status }, error: null })+ })+ })+ })+ })+ }) as never;++ it("refuses a job no longer in those statuses and changes nothing", async () => {+ const failed = await cancelJob({+ ...args,+ client: jobWithStatus("Ready"),+ fromStatuses: ["Draft", "Planned"]+ });++ expect(failed?.refused).toBe(true);+ expect(events).toEqual([]);+ });++ it("cancels a job still in them, guarding the status write too", async () => {+ const client = jobWithStatus("Planned");+ await expect(+ cancelJob({ ...args, client, fromStatuses: ["Draft", "Planned"] })+ ).resolves.toBeNull();++ expect(events).toEqual([+ "returnPickedRemainders",+ "cancelOpenPickingLists",+ "updateJobStatus"+ ]);+ expect(updateJobStatus).toHaveBeenCalledWith(+ client,+ expect.objectContaining({ fromStatuses: ["Draft", "Planned"] })+ );+ });++ it("refuses when the job moves on between the check and the write", async () => {+ vi.mocked(updateJobStatus).mockImplementationOnce((async () => {+ events.push("updateJobStatus");+ return { data: [], error: null, updated: false };+ }) as never);++ const failed = await cancelJob({+ ...args,+ client: jobWithStatus("Planned"),+ fromStatuses: ["Draft", "Planned"]+ });++ expect(failed?.refused).toBe(true);+ });+ });+});diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 619a0db0cd..8bd483c75d 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -11,10 +11,12 @@ import { serverFns } from "@carbon/server-functions";import { datetime, getErrorMessage } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { sql } from "kysely";+import { cancelOpenPickingListsForJob } from "~/modules/inventory/inventory.service";import { isJobLocked } from "./production.models";import {getJobReleaseReadiness,recalculateJobRequirements,+ returnPickedRemaindersForJob,runMRP,updateJobStatus} from "./production.service";@@ -197,6 +199,99 @@ export async function releaseJobs({};}+// Cancel a job. The one cancel path: the job status route and the planning+// Cancel action both call it, so neither can skip a step. In order:+// 1. return the picked material the job did not consume,+// 2. cancel its lines on every open picking list,+// 3. set the job Cancelled and clear its assignee.+// It stops at the first failure, before the status changes, so a retry starts+// from the same place. Returns null on success, else the failure with the+// message to show the user.+//+// `fromStatuses` limits the cancel to jobs still in one of them, checked+// before step 1 and again in the status UPDATE. Planning's Cancel passes+// Draft / Planned: it read the status earlier, and a job released since must+// not lose its picks. A job outside them is `refused`, with nothing changed.+export async function cancelJob({+ client,+ db,+ jobId,+ companyId,+ userId,+ fromStatuses+}: {+ client: SupabaseClient<Database>;+ db: Kysely<KyselyDatabase>;+ jobId: string;+ companyId: string;+ userId: string;+ fromStatuses?: Database["public"]["Enums"]["jobStatus"][];+}): Promise<{ error: unknown; message: string; refused?: boolean } | null> {+ if (fromStatuses) {+ const current = await client+ .from("job")+ .select("status")+ .eq("id", jobId)+ .eq("companyId", companyId)+ .maybeSingle();+ if (current.error) {+ return { error: current.error, message: "Failed to read the job" };+ }+ if (!current.data || !fromStatuses.includes(current.data.status)) {+ return {+ error: null,+ message: "The job's status changed; cancel it on the job",+ refused: true+ };+ }+ }++ const sweep = await returnPickedRemaindersForJob(getCarbonServiceRole(), db, {+ jobId,+ userId,+ companyId+ });+ if (sweep.error) {+ return {+ error: sweep.error,+ message: "Cancel aborted: returning picked material failed"+ };+ }++ const picks = await cancelOpenPickingListsForJob(db, {+ jobId,+ companyId,+ userId+ });+ if (picks.error) {+ return {+ error: picks.error,+ message: "Cancel aborted: its picking lists could not be closed"+ };+ }++ const update = await updateJobStatus(client, {+ id: jobId,+ companyId,+ status: "Cancelled",+ assignee: null,+ updatedBy: userId,+ ...(fromStatuses ? { fromStatuses } : {})+ });+ if (update.error) {+ return { error: update.error, message: "Failed to update job status" };+ }+ if (!update.updated) {+ return {+ error: null,+ message: "The job's status changed; cancel it on the job",+ refused: true+ };+ }++ return null;+}+// Releasing a batch releases its Draft/Planned member jobs through the same// path as the job page: every one is validated first and ANY problem refuses the// whole batch before anything changes. `purchaseOrdersBySupplierId` is thediff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex df24e7a4fd..82278f3dc3 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -20,6 +20,7 @@ import {datetime,getErrorMessage,groupBy,+ isUniqueViolation,nameSimilarity,scrapAllowance,tiptapToText,@@ -66,6 +67,10 @@ import type {} from "../shared";import { normalizeOperationSourceIds } from "../shared";import { updateSortOrder } from "../shared/sort-order";+import {+ claimPlanningActions,+ releasePlanningActionClaims+} from "./planning-action-claims";import type {assemblyInstructionStatuses,assemblyStepStatuses,@@ -100,6 +105,7 @@ import {JOB_LOCKED_STATUSES,JOB_SUPPLY_STATUS_PRIORITY,motionSchema,+ PLANNING_EDITABLE_JOB_STATUSES,PO_STATUS_PRIORITY,stepPlanWarningsSchema,WEEKDAYS_MONDAY_FIRST@@ -456,16 +462,6 @@ export async function calculateJobPriority(): Promise<number> {const { jobId, dueDate, deadlineType, companyId, locationId } = params;- // Define deadline type priority order (lower number = higher priority)- const deadlineTypePriority: Record<string, number> = {- ASAP: 0,- "Hard Deadline": 1,- "Soft Deadline": 2,- "No Deadline": 3- };-- const currentJobPriority = deadlineTypePriority[deadlineType];-// Query all jobs with the same dueDate (or null if dueDate is null)let query = client.from("job")@@ -487,45 +483,65 @@ export async function calculateJobPriority(const { data: existingJobs } = await query;- if (!existingJobs || existingJobs.length === 0) {- // No existing jobs with this due date, start at priority 0- return 0;- }+ return nextJobPriority(existingJobs ?? [], deadlineType);+}++type DeadlineType = Database["public"]["Enums"]["deadlineType"];- // Find the position where this job should be inserted based on deadlineType- let insertBeforeIndex = existingJobs.length; // Default to end of list+const DEADLINE_TYPE_PRIORITY: Record<DeadlineType, number> = {+ ASAP: 0,+ "Hard Deadline": 1,+ "Soft Deadline": 2,+ "No Deadline": 3+};++/**+ * The priority of a job placed among `siblings` — the jobs that share its due+ * date (or lack of one) at its location, in priority order. Fractional+ * indexing: before the first job whose deadline type ranks lower than this+ * one's, else at the end. Pure, so a batch can place several jobs on one date+ * in turn by appending each result to the siblings it passes for the next.+ */+/**+ * The deadline type a job carries once planning gives it a due date. The job+ * form hides the due-date field for "No Deadline" (`deadlineRequiresDueDate`),+ * so a date written under that type is one the planner can neither see nor+ * edit on the job, and `nextJobPriority` would rank it with the undated+ * weight. The Order path sets Soft Deadline the same way.+ */+export function deadlineTypeForPlanningDate(+ deadlineType: DeadlineType+): DeadlineType {+ return deadlineType === "No Deadline" ? "Soft Deadline" : deadlineType;+}- for (let i = 0; i < existingJobs.length; i++) {- const existingJobPriority =- deadlineTypePriority[existingJobs[i].deadlineType];+export function nextJobPriority(+ siblings: { priority: number | null; deadlineType: DeadlineType }[],+ deadlineType: DeadlineType+): number {+ if (siblings.length === 0) return 0;- // If the current job has higher priority (lower number) than this existing job,- // we should insert before this job- if (currentJobPriority < existingJobPriority) {+ const currentJobPriority = DEADLINE_TYPE_PRIORITY[deadlineType];+ let insertBeforeIndex = siblings.length;+ for (let i = 0; i < siblings.length; i++) {+ if (+ currentJobPriority < DEADLINE_TYPE_PRIORITY[siblings[i]!.deadlineType]+ ) {insertBeforeIndex = i;break;}}- // Calculate the priority value using fractional indexing- let newPriority: number;-if (insertBeforeIndex === 0) {- // Insert at the beginning - use half of the first job's priority- const firstPriority = existingJobs[0].priority ?? 0;- newPriority = firstPriority > 0 ? firstPriority / 2 : -1;- } else if (insertBeforeIndex === existingJobs.length) {- // Insert at the end - add 1 to the last job's priority- const lastPriority = existingJobs[existingJobs.length - 1].priority ?? 0;- newPriority = lastPriority + 1;- } else {- // Insert between two jobs - average their priorities- const beforePriority = existingJobs[insertBeforeIndex - 1].priority ?? 0;- const afterPriority = existingJobs[insertBeforeIndex].priority ?? 0;- newPriority = (beforePriority + afterPriority) / 2;+ const firstPriority = siblings[0]!.priority ?? 0;+ return firstPriority > 0 ? firstPriority / 2 : -1;}-- return newPriority;+ if (insertBeforeIndex === siblings.length) {+ return (siblings[siblings.length - 1]!.priority ?? 0) + 1;+ }+ const beforePriority = siblings[insertBeforeIndex - 1]!.priority ?? 0;+ const afterPriority = siblings[insertBeforeIndex]!.priority ?? 0;+ return (beforePriority + afterPriority) / 2;}/** @mcp delete */@@ -2288,14 +2304,31 @@ export async function getProductionPlanning(periods: string[],args: GenericQueryFilters & {search: string | null;- }-) {+ /** Today on the location's calendar (ISO date): the day each item's+ * planning horizon is counted from. */+ asOf: string;+ /** Keep only items with an OPEN planning action of one of these types+ * inside the item's planning horizon (the grid's Actions filter). */+ actionTypes?: string[];+ /** Keep only items with such an action assigned to this user ("Assigned+ * to me"). Combined with `actionTypes` on the SAME action. */+ actionAssignees?: string[];+ }+) {+ // The grid RPC wraps get_production_planning: same rows and projection, plus the+ // item group, the planning horizon / time fence date, the first week the+ // projection goes negative and the latest order date — and it evaluates the+ // action filter in the database, so it is complete at any volume and paging+ // stays correct.let query = client.rpc(- "get_production_planning",+ "get_production_planning_grid",{location_id: locationId,company_id: companyId,- periods+ periods,+ as_of: args.asOf,+ action_types: args.actionTypes,+ action_assignees: args.actionAssignees},{count: LIST_COUNT@@ -2308,8 +2341,12 @@ export async function getProductionPlanning();}+ // What the row's Order / Make button offers (the grid RPC's orderQuantity,+ // from MRP's open new-supply actions), then the part number so a page is+ // stable when many rows have nothing to order.query = setGenericQueryFilters(query, args, [- { column: "quantityToOrder", ascending: false }+ { column: "orderQuantity", ascending: false },+ { column: "readableIdWithRevision", ascending: true }]);return query;@@ -3845,27 +3882,7 @@ export async function updateJob(): Promise<{ data: { id: string } | null; error: PostgrestError | null }> {const { id, updatedBy, ...updates } = input;- let priority = updates.priority;- if (- (updates.dueDate !== undefined || updates.deadlineType !== undefined) &&- priority === undefined- ) {- const existing = await client- .from("job")- .select("dueDate, deadlineType, companyId, locationId")- .eq("id", id)- .single();-- if (existing.data) {- priority = await calculateJobPriority(client, {- jobId: id,- dueDate: updates.dueDate ?? existing.data.dueDate,- deadlineType: updates.deadlineType ?? existing.data.deadlineType,- companyId: existing.data.companyId,- locationId: existing.data.locationId- });- }- }+ const priority = await priorityForDateChange(client, id, updates);return client.from("job")@@ -3882,6 +3899,154 @@ export async function updateJob(.single();}+/**+ * The job's priority when its due date or deadline type changes, so a date+ * change re-ranks the job; undefined when neither changes or the caller sets+ * the priority itself.+ */+async function priorityForDateChange(+ client: SupabaseClient<Database>,+ id: string,+ updates: {+ dueDate?: string | null;+ deadlineType?: (typeof deadlineTypes)[number];+ priority?: number;+ }+): Promise<number | undefined> {+ if (+ (updates.dueDate === undefined && updates.deadlineType === undefined) ||+ updates.priority !== undefined+ ) {+ return updates.priority;+ }++ const existing = await client+ .from("job")+ .select("dueDate, deadlineType, companyId, locationId")+ .eq("id", id)+ .single();+ if (!existing.data) return undefined;++ return calculateJobPriority(client, {+ jobId: id,+ dueDate: updates.dueDate ?? existing.data.dueDate,+ deadlineType: updates.deadlineType ?? existing.data.deadlineType,+ companyId: existing.data.companyId,+ locationId: existing.data.locationId+ });+}++/**+ * The scrap allowance a job needs for a new quantity, from its item's scrap+ * rate — the same derivation `insertJob` makes. `job.quantity` is the good+ * units; `scrapQuantity` rides on top of it (`productionQuantity` is their+ * generated sum), so a quantity change that leaves the old allowance in place+ * builds the wrong number of units.+ */+async function scrapQuantityForPlanningQuantity(+ client: SupabaseClient<Database>,+ job: { id: string; companyId: string },+ quantity: number+): Promise<{ scrapQuantity: number; error: PostgrestError | null }> {+ const existing = await client+ .from("job")+ .select("itemId")+ .eq("id", job.id)+ .eq("companyId", job.companyId)+ .single();+ if (existing.error) return { scrapQuantity: 0, error: existing.error };++ const replenishment = await client+ .from("itemReplenishment")+ .select("scrapPercentage")+ .eq("itemId", existing.data.itemId)+ .eq("companyId", job.companyId)+ .maybeSingle();+ if (replenishment.error) {+ return { scrapQuantity: 0, error: replenishment.error };+ }+ return {+ scrapQuantity: scrapAllowance(+ quantity,+ replenishment.data?.scrapPercentage ?? 0+ ),+ error: null+ };+}++/**+ * Change a job's quantity or due date from planning (Apply, the order drawer).+ * The Draft / Planned condition is part of the UPDATE, so a job released+ * after the caller read it is left alone rather than edited: `updated` is+ * false, and the caller sends the planner to the job instead.+ *+ * A quantity change restates `scrapQuantity` for the new quantity. The+ * planning Decrease / Increase quantities are good units, so the job's own+ * scrap allowance must follow them — left alone, a Decrease to 80 kept the+ * allowance of the old quantity and the next run offered the Decrease again.+ */+export async function updatePlanningJob(+ client: SupabaseClient<Database>,+ input: {+ id: string;+ companyId: string;+ updatedBy: string;+ quantity?: number;+ dueDate?: string;+ }+): Promise<{ updated: boolean; error: PostgrestError | null }> {+ const { id, companyId, updatedBy, ...changes } = input;+ const updates: typeof changes & { deadlineType?: DeadlineType } = {+ ...changes+ };+ if (updates.dueDate !== undefined) {+ const existing = await client+ .from("job")+ .select("deadlineType")+ .eq("id", id)+ .eq("companyId", companyId)+ .single();+ if (existing.error) return { updated: false, error: existing.error };+ const deadlineType = deadlineTypeForPlanningDate(+ existing.data.deadlineType+ );+ if (deadlineType !== existing.data.deadlineType) {+ updates.deadlineType = deadlineType;+ }+ }+ const priority = await priorityForDateChange(client, id, updates);++ let scrap: { scrapQuantity: number } | undefined;+ if (updates.quantity !== undefined) {+ const derived = await scrapQuantityForPlanningQuantity(+ client,+ { id, companyId },+ updates.quantity+ );+ if (derived.error) return { updated: false, error: derived.error };+ scrap = { scrapQuantity: derived.scrapQuantity };+ }++ const result = await client+ .from("job")+ .update({+ ...updates,+ ...scrap,+ ...(priority !== undefined && { priority }),+ updatedBy,+ updatedAt: datetime.timestamp()+ })+ .eq("id", id)+ .eq("companyId", companyId)+ .in("status", [...PLANNING_EDITABLE_JOB_STATUSES])+ .select("id");++ return {+ updated: (result.data ?? []).length > 0,+ error: result.error+ };+}+/*** @deprecated Use insertJob for new jobs, updateJob for existing jobs* @mcp upsert@@ -10538,6 +10703,571 @@ export async function completeOperation(return backflush;}+// ── Planning actions (spec §P1) ────────────────────────────────────────────+// Persisted MRP action messages (Order/Make/Expedite/Defer/Cancel/Increase/+// Decrease). Written diff-write by generatePlanningActions (@carbon/planning);+// these are the app-side reads and worklist mutations.++// Item ids per request. `.in()` writes every id into the URL, and the gateway+// rejects a request line it cannot buffer (HTTP 431) — 100 ids is about 3 kB.+const PLANNING_ACTION_ITEM_CHUNK = 100;++/**+ * The open and dismissed planning actions of the given items at a location —+ * the rows behind a planning grid PAGE. The grid decides which items are on the+ * page (its RPC owns the Actions filter); this loads their actions in full, so+ * there is no cap to fall off the end of.+ *+ * The item, the purchase order behind a line and the job come back as embeds+ * of the same read. Looking them up afterwards by `.in("id", …)` put one id per+ * ACTION in the URL: a page of busy items (2,000+ actions) overran the gateway+ * and the whole read failed, leaving the grid with no actions at all.+ */+/** Which planning page owns an action — purchasing ("Buy") or production ("Make"). */+export type PlanningActionKind = "Buy" | "Make";++export async function getPlanningActions(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ locationId: string;+ kind: PlanningActionKind;+ itemIds: string[];+ }+) {+ const { companyId, locationId, kind, itemIds: pageItemIds } = args;++ if (pageItemIds.length === 0) {+ return { data: [], count: 0, error: null };+ }++ const chunks = await Promise.all(+ chunkArray(pageItemIds, PLANNING_ACTION_ITEM_CHUNK).map((itemIds) =>+ // Paged: a page of busy items can hold more actions than PostgREST's+ // max_rows, and a bare select would silently drop the tail.+ fetchAllRecords(() => {+ const query = client+ .from("planningAction")+ .select(+ "*, item(readableIdWithRevision, name), purchaseOrderLine(purchaseOrderId, promisedDate, purchaseOrder(purchaseOrderId, status, orderDate, purchaseOrderDelivery(receiptPromisedDate))), job(jobId, status)"+ )+ .eq("companyId", companyId)+ .eq("locationId", locationId)+ .neq("status", "Actioned")+ .in("itemId", itemIds);++ // Buy worklist = new purchase suggestions + change actions on PO lines;+ // Make worklist = new job suggestions + change actions on jobs.+ return (+ kind === "Buy"+ ? query.or("type.eq.Order,purchaseOrderLineId.not.is.null")+ : query.or("type.eq.Make,jobId.not.is.null")+ )+ .order("suggestedDate", { ascending: true })+ .order("id", { ascending: true });+ })+ )+ );++ // One failed chunk fails the read: a grid missing some parts' actions looks+ // exactly like a grid where those parts need nothing.+ const failed = chunks.find((chunk) => chunk.error);+ if (failed?.error) {+ return { data: null, count: 0, error: failed.error };+ }++ const enriched = chunks+ .flatMap((chunk) => chunk.data ?? [])+ .map(({ item, purchaseOrderLine, job, ...row }) => ({+ ...row,+ itemReadableId: item?.readableIdWithRevision ?? null,+ itemName: item?.name ?? null,+ // navigation target: the PARENT purchase order id — the stored value is+ // the LINE id and would 404 in path.to.purchaseOrder+ purchaseOrderId: purchaseOrderLine?.purchaseOrderId ?? null,+ purchaseOrderReadableId:+ purchaseOrderLine?.purchaseOrder?.purchaseOrderId ?? null,+ // why the row offers Review instead of Apply: shown as an icon beside+ // the document number, and read LIVE to choose Apply or Review — MRP's+ // `requiresManualAction` is as of the run, so a PO reopened since would+ // otherwise stay on Review until the next one+ purchaseOrderStatus: purchaseOrderLine?.purchaseOrder?.status ?? null,+ // a released PO can be reopened as a revision (see+ // canCreatePurchaseOrderRevision)+ purchaseOrderDate: purchaseOrderLine?.purchaseOrder?.orderDate ?? null,+ // the supplier's promise, which Apply's required date cannot move+ purchaseOrderLinePromisedDate:+ purchaseOrderLine?.promisedDate ??+ purchaseOrderLine?.purchaseOrder?.purchaseOrderDelivery+ ?.receiptPromisedDate ??+ null,+ jobReadableId: job?.jobId ?? null,+ jobStatus: job?.status ?? null+ }))+ // the chunks are each in order; the page as a whole is not+ .sort(+ (a, b) =>+ a.suggestedDate.localeCompare(b.suggestedDate) ||+ a.id.localeCompare(b.id)+ );++ return {+ data: enriched,+ count: enriched.length,+ error: null+ };+}++// The worklist writes below take an id LIST and go through Kysely, one+// statement each. Over PostgREST every id goes into the URL: a bulk Apply on a+// page of busy items sent hundreds, the gateway answered 431, and the whole+// batch failed before anything was claimed. A read over PostgREST also stops+// at max_rows (1000) and would report every id after that as "not found".+// One statement is also what makes the claim below a lock: every row of the+// batch flips in one transaction or none does.+type PlanningActionIdListResult<Row> =+ | { data: Row[]; error: null }+ | { data: null; error: { message: string } };++async function planningActionIdList<Row>(+ ids: string[],+ run: () => Promise<Row[]>+): Promise<PlanningActionIdListResult<Row>> {+ if (ids.length === 0) return { data: [], error: null };+ try {+ return { data: await run(), error: null };+ } catch (err) {+ return {+ data: null,+ error: { message: err instanceof Error ? err.message : String(err) }+ };+ }+}++/**+ * The worklist a page may write, the same split `getPlanningActions` reads:+ * Buy = new purchase suggestions and changes on PO lines, Make = new job+ * suggestions and changes on jobs. The writes below go through Kysely, past+ * row-level security, so without it a user with purchasing rights could+ * dismiss or reassign production's actions by posting their ids.+ */+function inPlanningWorklist(kind: PlanningActionKind) {+ return (eb: ExpressionBuilder<KyselyDatabase, "planningAction">) =>+ kind === "Buy"+ ? eb.or([+ eb("type", "=", "Order"),+ eb("purchaseOrderLineId", "is not", null)+ ])+ : eb.or([eb("type", "=", "Make"), eb("jobId", "is not", null)]);+}++export async function dismissPlanningActions(+ db: Kysely<KyselyDatabase>,+ args: {+ ids: string[];+ companyId: string;+ userId: string;+ kind: PlanningActionKind;+ }+) {+ // Open-only: Actioned is terminal, and a stale worklist id must never flip+ // an Actioned row to Dismissed (which would make it visible again and+ // eligible for the generator's Dismissed-reopen branch).+ return planningActionIdList(args.ids, () =>+ db+ .updateTable("planningAction")+ .set({+ status: "Dismissed",+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "in", args.ids)+ .where("companyId", "=", args.companyId)+ .where("status", "=", "Open")+ .where(inPlanningWorklist(args.kind))+ .returning("id")+ .execute()+ );+}++/**+ * Conditional claim, not a blind update: only Open rows flip to Actioned, and+ * the claimed ids are returned. Callers applying a mutation MUST claim first+ * and treat an empty result as "someone else already applied this" — that+ * affected-row check is the concurrency lock for the whole apply path.+ */+export async function markPlanningActionsActioned(+ db: Kysely<KyselyDatabase>,+ args: { ids: string[]; companyId: string; userId: string }+) {+ return planningActionIdList(args.ids, () =>+ db+ .updateTable("planningAction")+ .set({+ status: "Actioned",+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "in", args.ids)+ .where("companyId", "=", args.companyId)+ .where("status", "=", "Open")+ // The suggestion as it is at the claim — see claimPlanningActions.+ .returning(["id", "suggestedQuantity", "suggestedDate"])+ .execute()+ );+}++/**+ * Settle the new-supply suggestions a planning Order just raised. The page's+ * Order button creates PO lines (Buy) or jobs (Make) from the suggested+ * orders, which carry no action id; each one is the week of an Order / Make+ * action (both come from `computePlanningOrders`, and the natural key holds+ * one such action per item, location and week). Without this, the action+ * stayed Open beside the order that answered it until the next MRP run.+ * Dismissed is settled too: the need it suppressed has now been ordered.+ * Pairs are matched as pairs, so a bulk order never settles one item's week+ * because another item was ordered in it.+ */+export async function settleNewSupplyPlanningActions(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ locationId: string;+ userId: string;+ type: "Order" | "Make";+ ordered: { itemId: string; periodId: string }[];+ }+) {+ const byKey = new Map(+ args.ordered.map((pair) => [`${pair.itemId}\u0000${pair.periodId}`, pair])+ );+ const ordered = [...byKey.values()];+ return planningActionIdList([...byKey.keys()], () =>+ db+ .updateTable("planningAction")+ .set({+ status: "Actioned",+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("companyId", "=", args.companyId)+ .where("locationId", "=", args.locationId)+ .where("type", "=", args.type)+ .where("status", "in", ["Open", "Dismissed"])+ .where((eb) =>+ eb.or(+ ordered.map((pair) =>+ eb.and([+ eb("itemId", "=", pair.itemId),+ eb("periodId", "=", pair.periodId)+ ])+ )+ )+ )+ .returning("id")+ .execute()+ );+}++/** Compensation for a failed apply: release a claimed (Actioned) row back to Open. */+export async function reopenPlanningActions(+ client: SupabaseClient<Database>,+ args: { ids: string[]; companyId: string; userId: string }+) {+ return client+ .from("planningAction")+ .update({ status: "Open" as const, updatedBy: args.userId })+ .in("id", args.ids)+ .eq("companyId", args.companyId)+ .eq("status", "Actioned");+}++/**+ * Give up an apply's claim on one action: back to Open, so the planner can try+ * again. If an MRP run since the claim already wrote an Open row for the same+ * need, the reopen hits the natural-key unique index (23505); that new row+ * replaces this one, so the claimed row is deleted instead. Returns the error+ * the caller must report — never ignore it, or the action stays Actioned with+ * nothing applied.+ */+export async function releasePlanningActionClaim(+ client: SupabaseClient<Database>,+ args: { id: string; companyId: string; userId: string }+): Promise<{ error: string | null }> {+ const reopened = await reopenPlanningActions(client, {+ ids: [args.id],+ companyId: args.companyId,+ userId: args.userId+ });+ if (!reopened.error) return { error: null };+ if (!isUniqueViolation(reopened.error)) {+ return { error: reopened.error.message };+ }++ const removed = await client+ .from("planningAction")+ .delete()+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .eq("status", "Actioned");+ return { error: removed.error?.message ?? null };+}++/**+ * The worklist's "Reopen" on a Dismissed row. Dismissed-only: `reopenPlanningActions`+ * above is the apply path's claim rollback (Actioned → Open) and must stay+ * separate so a stale worklist id can never un-claim a row another apply holds.+ */+export async function reopenDismissedPlanningActions(+ db: Kysely<KyselyDatabase>,+ args: {+ ids: string[];+ companyId: string;+ userId: string;+ kind: PlanningActionKind;+ }+) {+ return planningActionIdList(args.ids, () =>+ db+ .updateTable("planningAction")+ .set({+ status: "Open",+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "in", args.ids)+ .where("companyId", "=", args.companyId)+ .where("status", "=", "Dismissed")+ .where(inPlanningWorklist(args.kind))+ .returning("id")+ .execute()+ );+}++/**+ * Assigning through this function (not the generic api/assign route) both sets+ * the assignee AND marks it human-overridden so the next MRP diff-write never+ * re-resolves it from the responsibleEmployee ladder. An applied (Actioned)+ * action is finished and keeps its owner. Like dismiss and reopen, it returns+ * the ids it changed: the route reports those, not the ids it was sent.+ */+export async function assignPlanningActions(+ db: Kysely<KyselyDatabase>,+ args: {+ ids: string[];+ companyId: string;+ assignee: string | null;+ userId: string;+ kind: PlanningActionKind;+ }+) {+ return planningActionIdList(args.ids, () =>+ db+ .updateTable("planningAction")+ .set({+ assignee: args.assignee || null,+ assigneeOverridden: true,+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "in", args.ids)+ .where("companyId", "=", args.companyId)+ .where("status", "in", ["Open", "Dismissed"])+ .where(inPlanningWorklist(args.kind))+ .returning("id")+ .execute()+ );+}++export type ProductionPlanningDateAction = {+ planningActionId: string;+ jobId: string;+ /** the new due date, ISO */+ suggestedDate: string;+};++export type ProductionPlanningDateApplyResult = {+ /** changed and marked Actioned */+ applied: string[];+ /** marked Actioned by another apply since the page loaded; nothing changed */+ alreadyApplied: string[];+ /** the job left Draft / Planned since it was read: the action stays Open */+ refused: { id: string; jobId: string }[];+};++/**+ * Apply a batch of Expedite / Defer actions to their jobs in ONE transaction,+ * set-based: the claim, two reads (the jobs, and the jobs that share their+ * new due dates) and one UPDATE for every date and priority. It used to be a+ * job read, a sibling read, an update and a scheduler event per action.+ *+ * Priority follows `updateJob`'s rule (`nextJobPriority`): a moved job is+ * ranked among the jobs already on its new date. Several jobs moved to one+ * date in the same batch are placed one after the other, each seeing the ones+ * placed before it, as the sequential writes did.+ *+ * The Draft / Planned condition is part of the UPDATE: a job released after+ * it was read is left alone, its action goes back to Open, and the caller+ * sends the planner to the job. The caller tells the scheduler ONCE after the+ * batch — a "reorder" event re-stamps the whole company whatever its job id.+ */+export async function applyProductionPlanningDateActions(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ actions: ProductionPlanningDateAction[];+ }+): Promise<ProductionPlanningDateApplyResult> {+ const { companyId, userId, actions } = args;+ const result: ProductionPlanningDateApplyResult = {+ applied: [],+ alreadyApplied: [],+ refused: []+ };+ if (actions.length === 0) return result;+ const now = datetime.timestamp();++ await db.transaction().execute(async (trx) => {+ const claimed = await claimPlanningActions(trx, {+ ids: actions.map((a) => a.planningActionId),+ companyId,+ userId,+ now+ });+ // The date comes from the claim, not from the page's read (see+ // claimPlanningActions); the page's value is only the fallback for a row+ // that somehow carries none.+ const held = actions.flatMap((a) => {+ const claim = claimed.get(a.planningActionId);+ if (!claim) return [];+ return [{ ...a, suggestedDate: claim.suggestedDate ?? a.suggestedDate }];+ });+ for (const action of actions) {+ if (!claimed.has(action.planningActionId)) {+ result.alreadyApplied.push(action.planningActionId);+ }+ }+ if (held.length === 0) return;++ const jobIds = [...new Set(held.map((a) => a.jobId))];+ const jobs = await trx+ .selectFrom("job")+ .select(["id", "locationId", "deadlineType"])+ .where("id", "in", jobIds)+ .where("companyId", "=", companyId)+ .execute();+ const jobById = new Map(jobs.map((job) => [job.id, job]));++ // The jobs already on each target date, per location — the siblings a+ // moved job is ranked among. One read for every date in the batch.+ const targetDates = [...new Set(held.map((a) => a.suggestedDate))];+ const siblingRows = await trx+ .selectFrom("job")+ .select(["id", "locationId", "dueDate", "priority", "deadlineType"])+ .where("companyId", "=", companyId)+ .where("dueDate", "in", targetDates)+ .where("id", "not in", jobIds)+ .orderBy("priority", "asc")+ .execute();+ const siblingsByKey = new Map<+ string,+ { priority: number | null; deadlineType: DeadlineType }[]+ >();+ for (const row of siblingRows) {+ const key = `${row.locationId}\u001f${row.dueDate}`;+ const list = siblingsByKey.get(key) ?? [];+ list.push({ priority: row.priority, deadlineType: row.deadlineType });+ siblingsByKey.set(key, list);+ }++ const values: {+ jobId: string;+ dueDate: string;+ deadlineType: DeadlineType;+ priority: number;+ }[] = [];+ for (const action of held) {+ const job = jobById.get(action.jobId);+ if (!job) continue; // refused below: no row changed+ const deadlineType = deadlineTypeForPlanningDate(job.deadlineType);+ const key = `${job.locationId}\u001f${action.suggestedDate}`;+ const siblings = siblingsByKey.get(key) ?? [];+ const priority = nextJobPriority(siblings, deadlineType);+ siblings.push({ priority, deadlineType });+ siblings.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));+ siblingsByKey.set(key, siblings);+ values.push({+ jobId: action.jobId,+ dueDate: action.suggestedDate,+ deadlineType,+ priority+ });+ }++ const changedJobs = new Set<string>();+ if (values.length > 0) {+ const rows = await sql<{ id: string }>`+ UPDATE "job" AS j+ SET "dueDate" = v."dueDate"::date,+ "deadlineType" = v."deadlineType"::"deadlineType",+ "priority" = v."priority"::numeric,+ "updatedBy" = ${userId},+ "updatedAt" = ${now}+ FROM (VALUES ${sql.join(+ values.map(+ (v) =>+ sql`(${v.jobId}, ${v.dueDate}, ${v.deadlineType}, ${v.priority})`+ )+ )}) AS v("id", "dueDate", "deadlineType", "priority")+ WHERE j."id" = v."id"+ AND j."companyId" = ${companyId}+ AND j."status" IN (${sql.join(+ PLANNING_EDITABLE_JOB_STATUSES.map((status) => sql`${status}`)+ )})+ RETURNING j."id"+ `.execute(trx);+ for (const row of rows.rows) changedJobs.add(row.id);+ }++ const refusedIds: string[] = [];+ for (const action of held) {+ if (changedJobs.has(action.jobId)) {+ result.applied.push(action.planningActionId);+ } else {+ refusedIds.push(action.planningActionId);+ result.refused.push({+ id: action.planningActionId,+ jobId: action.jobId+ });+ }+ }+ await releasePlanningActionClaims(trx, {+ ids: refusedIds,+ companyId,+ userId,+ now+ });+ });++ return result;+}++/** The actions an Apply was sent, in one read (an Apply used to read each). */+export async function getPlanningActionsByIds(+ db: Kysely<KyselyDatabase>,+ args: { ids: string[]; companyId: string }+) {+ return planningActionIdList(args.ids, () =>+ db+ .selectFrom("planningAction")+ .selectAll()+ .where("id", "in", args.ids)+ .where("companyId", "=", args.companyId)+ .execute()+ );+}+/*** Create a presigned upload URL for a job document. First step of the two-step* upload flow: PUT the file bytes to the returned `signedUrl`, then calldiff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.tsindex b8984b904e..2d8997bb91 100644--- a/apps/erp/app/modules/production/types.ts+++ b/apps/erp/app/modules/production/types.ts@@ -34,6 +34,7 @@ import type {getMaintenanceSchedule,getMaintenanceScheduleItems,getMaintenanceSchedules,+ getPlanningActions,getProcedure,getProcedureParameters,getProcedureSteps,@@ -193,8 +194,40 @@ export type Procedure = NonNullable<Awaited<ReturnType<typeof getProcedure>>["data"]>;-export type ProductionPlanningItem = NonNullable<- Awaited<ReturnType<typeof getProductionPlanning>>["data"]+/**+ * The columns the planning grid RPCs add to the base planning row. Generated+ * function return types mark every column non-null; these are not — an item+ * with no group, no planning horizon, no negative week or nothing to order+ * comes back NULL.+ */+export type PlanningGridColumns = {+ itemPostingGroupId: string | null;+ /** The item's saved planning horizon in days (item, else company default);+ * null when there is none — a saved 0 means "no fence" and reads as null. */+ planningHorizonDays: number | null;+ /** Today + the saved horizon; null when the item has no fence. */+ timeFenceDate: string | null;+ /** Start of the first week whose projected on-hand is below zero. */+ firstNegativeDate: string | null;+ /** Earliest order-by date among the item's open new-supply actions. */+ latestOrderDate: string | null;+ /** The quantity of the item's open new-supply actions (Order / Make) inside+ * its fence — what the Order / Make button offers, and the default sort.+ * The base RPC's `quantityToOrder` is a second sizing that misses what MRP+ * did after sizing. */+ orderQuantity: number;+};++export type ProductionPlanningItem = Omit<+ NonNullable<+ Awaited<ReturnType<typeof getProductionPlanning>>["data"]+ >[number],+ keyof PlanningGridColumns+> &+ PlanningGridColumns;++export type PlanningAction = NonNullable<+ Awaited<ReturnType<typeof getPlanningActions>>["data"]>[number];export type ScrapReason = NonNullable<diff --git a/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx b/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsxindex cf04e83c21..36a1b7a5d9 100644--- a/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx+++ b/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx@@ -37,7 +37,7 @@ import {} from "recharts";import type { z } from "zod";import { Hidden, Item, Location, Number, Submit } from "~/components/Form";-import { usePermissions } from "~/hooks";+import { usePermissions, useQuantityFormatter } from "~/hooks";import { path } from "~/utils/path";import { demandProjectionValidator } from "../../production.models";@@ -48,6 +48,7 @@ type LoaderData = {type DemandProjectionsFormProps = {initialValues?: z.infer<typeof demandProjectionValidator>;+ consumedValues?: Record<number, number>;isEditing?: boolean;onClose: () => void;};@@ -71,12 +72,14 @@ const toFinite = (value: unknown): number => {const DemandProjectionsForm = ({initialValues: propInitialValues,+ consumedValues,isEditing = false,onClose}: DemandProjectionsFormProps) => {const permissions = usePermissions();const { t, i18n } = useLingui();const numberFormatter = useNumberFormatter();+ const formatQuantity = useQuantityFormatter();const fetcher = useFetcher<{ id: string }>();const loaderData = useLoaderData<LoaderData>();const periods = loaderData?.periods ?? [];@@ -264,16 +267,23 @@ const DemandProjectionsForm = ({{ length: quarter.end - quarter.start },(_, offset) => {const index = quarter.start + offset;+ const consumed = consumedValues?.[index];return (- <Number- key={index}- name={`week${index}`}- label={weekLabels[index]}- minValue={0}- onChange={(value) =>- handleWeekChange(index, value)- }- />+ <div key={index} className="flex flex-col gap-1">+ <Number+ name={`week${index}`}+ label={weekLabels[index]}+ minValue={0}+ onChange={(value) =>+ handleWeekChange(index, value)+ }+ />+ {consumed !== undefined && (+ <span className="text-xs text-muted-foreground">+ {t`${formatQuantity(consumed)} consumed`}+ </span>+ )}+ </div>);})}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx b/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsxindex c27995f28a..fef4124fec 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx@@ -11,19 +11,28 @@ export { JOB_STATUS_COLOR_MAP } from "@carbon/utils";type JobStatusProps = {status?: (typeof jobStatus)[number] | null;className?: string;+ /** The status as its icon alone, with the name in a tooltip. */+ iconOnly?: boolean;};-function JobStatus({ status, className }: JobStatusProps) {+function JobStatus({ status, className, iconOnly }: JobStatusProps) {if (!status) return null;const color = JOB_STATUS_COLOR_MAP[status];if (!color) return null;const displayText = status === "Ready" ? "Released" : status;- const tooltip = status === "Ready" ? status : undefined;+ // The pill reads "Released" and its tooltip gives the stored name. With the+ // icon alone, the tooltip is the label, so it has to say "Released".+ const tooltip = status === "Ready" && !iconOnly ? status : undefined;return (- <Status color={color} className={className} tooltip={tooltip}>+ <Status+ color={color}+ className={className}+ tooltip={tooltip}+ iconOnly={iconOnly}+ >{displayText}</Status>);diff --git a/apps/erp/app/modules/production/ui/Planning/LatestOrderDate.tsx b/apps/erp/app/modules/production/ui/Planning/LatestOrderDate.tsxnew file mode 100644index 0000000000..5b32d4ee35--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/LatestOrderDate.tsx@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { cn, Tooltip, TooltipContent, TooltipTrigger } from "@carbon/react";+import { formatDate } from "@carbon/utils";+import { parseDate } from "@internationalized/date";+import { Plural, Trans } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import { memo } from "react";+import type { ProductionPlanningItem } from "~/modules/production";+import type { PurchasingPlanningItem } from "~/modules/purchasing";++type PlanningRow = ProductionPlanningItem | PurchasingPlanningItem;++/** CSV value for the Latest Order Date column: the ISO date, or blank. */+export function latestOrderDateExportValue(row: PlanningRow) {+ return row.latestOrderDate ?? null;+}++/**+ * The last day the row's next suggested order can be placed and still arrive+ * on time: the earliest order-by date among the item's open new-supply+ * actions, which the grid RPC returns as `latestOrderDate` and sorts by. Red+ * once that day has passed — the order is already late. The tooltip shows the+ * date the supply is required (the order-by date plus the lead time MRP took+ * off it) and the lead time.+ */+export const LatestOrderDateCell = memo(function LatestOrderDateCell({+ itemPlanning,+ todayIso+}: {+ itemPlanning: PlanningRow;+ /** Today on the location's calendar — what "past due" is measured from. */+ todayIso: string;+}) {+ const { locale } = useLocale();+ const latestOrderDate = itemPlanning.latestOrderDate;+ if (!latestOrderDate) return <span>-</span>;++ const leadTime = itemPlanning.leadTime ?? 0;+ const requiredDate = parseDate(latestOrderDate)+ .add({ days: leadTime })+ .toString();+ // ISO dates: string order is chronological+ const isPastDue = latestOrderDate < todayIso;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ className={cn(+ "whitespace-nowrap tabular-nums",+ isPastDue && "text-red-500 font-bold"+ )}+ >+ {formatDate(latestOrderDate, undefined, locale)}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ <div className="grid grid-cols-[auto_auto] gap-x-3 gap-y-0.5">+ <span className="text-muted-foreground">+ <Trans>Required Date</Trans>+ </span>+ <span className="tabular-nums text-right">+ {formatDate(requiredDate, undefined, locale)}+ </span>+ <span className="text-muted-foreground">+ <Trans>Lead Time</Trans>+ </span>+ <span className="tabular-nums text-right">+ <Plural value={leadTime} one="# day" other="# days" />+ </span>+ {isPastDue && (+ <span className="col-span-2 text-red-500 font-medium">+ <Trans>Past due</Trans>+ </span>+ )}+ </div>+ </TooltipContent>+ </Tooltip>+ );+});diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningActionLines.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningActionLines.tsxnew file mode 100644index 0000000000..f1c1bab116--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/PlanningActionLines.tsx@@ -0,0 +1,716 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Badge,+ Button,+ cn,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ HStack,+ IconButton,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useMemo } from "react";+import {+ LuBan,+ LuChevronsDown,+ LuChevronsUp,+ LuCirclePlay,+ LuEllipsisVertical,+ LuEyeOff,+ LuMinus,+ LuPlus,+ LuRotateCcw,+ LuSend,+ LuShoppingCart,+ LuUserCheck,+ LuX+} from "react-icons/lu";+import { Link } from "react-router";+import { Assignee, DateTime } from "~/components";+import { useQuantityFormatter } from "~/hooks";+import type { PlanningAction } from "~/modules/production";+import type { planningActionType } from "~/modules/production/production.models";+import PurchasingStatus from "~/modules/purchasing/ui/PurchaseOrder/PurchasingStatus";+import { path } from "~/utils/path";+import JobStatus from "../Jobs/JobStatus";+import {+ isPlanningActionLate,+ type PlanningPurchaseOrder,+ planningActionNeedsReview+} from "./planning-review";++// The MRP action worklist (spec §P1.7) rendered INSIDE the planning grid: one+// persisted planningAction per line, shown in the expanded row of the item it+// belongs to. The grid row is the item; the action is the dated decision.++export type PlanningActionType = (typeof planningActionType)[number];++const NEW_SUPPLY_TYPES: ReadonlySet<string> = new Set(["Order", "Make"]);++/** Order/Make rows are fulfilled through the grid's Order button + drawer. */+export function isNewSupplyAction(action: PlanningAction) {+ return NEW_SUPPLY_TYPES.has(action.type);+}++/** One-click Apply: an Open change action whose target is still uncommitted+ * — read from the order's live status, not MRP's stamp (see planning-review).+ * A Release is done on the order itself, never applied from here. */+export function isApplyablePlanningAction(action: PlanningAction) {+ return (+ action.status === "Open" &&+ action.type !== "Release" &&+ !planningActionNeedsReview(action) &&+ !isNewSupplyAction(action)+ );+}++/** The purchase order a planning action targets, for its order menu. */+export function planningActionPurchaseOrder(+ action: PlanningAction+): PlanningPurchaseOrder | null {+ if (!action.purchaseOrderId) return null;+ return {+ id: action.purchaseOrderId,+ readableId: action.purchaseOrderReadableId,+ status: action.purchaseOrderStatus,+ orderDate: action.purchaseOrderDate+ };+}++const TYPE_ICONS: Record<PlanningActionType, ReactNode> = {+ Order: <LuShoppingCart />,+ Make: <LuCirclePlay />,+ Expedite: <LuChevronsUp />,+ Defer: <LuChevronsDown />,+ Increase: <LuPlus />,+ Decrease: <LuMinus />,+ Cancel: <LuBan />,+ Release: <LuSend />+};++const TYPE_ORDER: PlanningActionType[] = [+ "Expedite",+ "Cancel",+ "Decrease",+ "Increase",+ "Release",+ "Defer",+ "Order",+ "Make"+];++export function usePlanningActionTypeLabels(): Record<+ PlanningActionType,+ string+> {+ const { t } = useLingui();+ return useMemo(+ () => ({+ Order: t`Order`,+ Make: t`Make`,+ Expedite: t`Expedite`,+ Defer: t`Defer`,+ Increase: t`Increase`,+ Decrease: t`Decrease`,+ Cancel: t`Cancel`,+ Release: t`Release`+ }),+ [t]+ );+}++/** The labelled badge. The label is its CHILD, not looked up inside, because+ * the table's filter reads an option's text out of the element's children+ * (`reactNodeToString`) — for the active-filter pill and the option search. */+function LabelledTypeBadge({+ type,+ count,+ children+}: {+ type: PlanningActionType;+ count?: number;+ children: string;+}) {+ return (+ <Badge variant="secondary" className="gap-1 shrink-0 whitespace-nowrap">+ <span className="inline-flex shrink-0 [&>svg]:size-3">+ {TYPE_ICONS[type]}+ </span>+ <span>{children}</span>+ {count !== undefined && count > 1 && (+ <span className="tabular-nums text-muted-foreground">·{count}</span>+ )}+ </Badge>+ );+}++export function PlanningActionTypeBadge({+ type,+ count,+ compact = false+}: {+ type: PlanningActionType;+ count?: number;+ /** Icon and count only; the label moves to a tooltip. */+ compact?: boolean;+}) {+ const labels = usePlanningActionTypeLabels();+ const hasCount = count !== undefined && count > 1;++ if (compact) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge+ variant="secondary"+ className="gap-1 shrink-0 px-1.5"+ aria-label={labels[type]}+ >+ <span className="inline-flex shrink-0 [&>svg]:size-3">+ {TYPE_ICONS[type]}+ </span>+ {hasCount && <span className="tabular-nums">{count}</span>}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ {labels[type]}+ {hasCount && (+ <span className="tabular-nums text-muted-foreground">+ {" "}+ ·{count}+ </span>+ )}+ </TooltipContent>+ </Tooltip>+ );+ }++ return (+ <LabelledTypeBadge type={type} count={count}>+ {labels[type]}+ </LabelledTypeBadge>+ );+}++/** Static filter options for the Actions column: one per type the worklist+ * can hold, rendered as the same badge the cell shows. Only types that+ * belong to this grid's kind are offered. */+export function usePlanningActionTypeOptions(kind: "Buy" | "Make") {+ const labels = usePlanningActionTypeLabels();+ return useMemo(() => {+ const types = TYPE_ORDER.filter((type) =>+ kind === "Buy" ? type !== "Make" : type !== "Order"+ );+ return types.map((type) => ({+ value: type,+ label: <LabelledTypeBadge type={type}>{labels[type]}</LabelledTypeBadge>+ }));+ }, [kind, labels]);+}++export { planningActionDot } from "./planning-review";++/** The grid's Actions cell: one ICON chip per open action type (with a count+ * when the item has several; the name is in its tooltip) and a muted chip for+ * dismissed rows so they stay reachable from the expanded row. Icons only, so the cell is always ONE line — a+ * labelled badge per type wrapped and made every busy row taller than its+ * neighbours. The expanded row shows each action with its full badge. */+export function PlanningActionsCell({+ actions+}: {+ actions: PlanningAction[];+}) {+ const open = actions.filter((a) => a.status === "Open");+ const dismissed = actions.length - open.length;+ if (open.length === 0 && dismissed === 0) return null;++ const counts = new Map<PlanningActionType, number>();+ for (const action of open) {+ counts.set(action.type, (counts.get(action.type) ?? 0) + 1);+ }+ const types = TYPE_ORDER.filter((type) => counts.has(type));++ return (+ <HStack spacing={1} className="flex-nowrap whitespace-nowrap">+ {types.map((type) => (+ <PlanningActionTypeBadge+ key={type}+ type={type}+ count={counts.get(type)}+ compact+ />+ ))}+ {dismissed > 0 && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge+ variant="outline"+ className="gap-1 shrink-0 px-1.5 text-muted-foreground"+ >+ <LuEyeOff className="size-3" />+ <span className="tabular-nums">{dismissed}</span>+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ <Trans>{dismissed} dismissed</Trans>+ </TooltipContent>+ </Tooltip>+ )}+ </HStack>+ );+}++/** CSV value for the Actions column. */+export function planningActionsExportValue(actions: PlanningAction[]) {+ const open = actions.filter((a) => a.status === "Open");+ if (open.length === 0) return null;+ return open.map((a) => a.type).join(", ");+}++/** The document an action changes: its purchase order LINE when it names one+ * (the line, not the order, is what the action resizes or moves), else the+ * purchase order, else the job. */+export function reviewPathFor(action: PlanningAction) {+ if (action.purchaseOrderId) {+ return action.purchaseOrderLineId+ ? path.to.purchaseOrderLine(+ action.purchaseOrderId,+ action.purchaseOrderLineId+ )+ : path.to.purchaseOrder(action.purchaseOrderId);+ }+ if (action.jobId) return path.to.job(action.jobId);+ return null;+}++/** Open before dismissed, then by suggested date (YYYY-MM-DD sorts+ * chronologically as a string), then by the type order above. */+function sortPlanningActions(actions: PlanningAction[]) {+ return [...actions].sort((a, b) => {+ if (a.status !== b.status) return a.status === "Open" ? -1 : 1;+ if (a.suggestedDate !== b.suggestedDate)+ return a.suggestedDate < b.suggestedDate ? -1 : 1;+ return TYPE_ORDER.indexOf(a.type) - TYPE_ORDER.indexOf(b.type);+ });+}++export type PlanningActionHandlers = {+ currentUserId: string;+ canUpdate: boolean;+ isBusy: boolean;+ onApply: (ids: string[]) => void;+ onDismiss: (ids: string[]) => void;+ onReopen: (ids: string[]) => void;+ onAssignToMe: (ids: string[]) => void;+ /** Sets the assignee; an empty string unassigns. */+ onAssign: (ids: string[], assignee: string) => void;+ /** The purchasing page's commands on the order itself (Reopen, Reopen as+ * Revision, Finalize), added to the row's ⋯ menu. Null when there are+ * none; production passes nothing. */+ purchaseOrderMenuItems?: (order: PlanningPurchaseOrder) => ReactNode;+ /** Releases a Release action's order from the page (purchasing: the PO's+ * Finalize modal; production: the job release). Absent, the button links+ * to the order instead. */+ onRelease?: (action: PlanningAction) => void;+};++/** The trailing controls of one action, wherever it is listed: ONE button+ * (Apply, Review on the committed order, or Order…/Make… for new supply) and+ * the ⋯ menu with Assign to Me and Dismiss / Reopen. */+export function PlanningActionRowActions({+ action,+ currentUserId,+ canUpdate,+ isBusy,+ onApply,+ onDismiss,+ onReopen,+ onAssignToMe,+ onOrder,+ purchaseOrderMenuItems,+ onRelease,+ purchaseOrder+}: PlanningActionHandlers & {+ action: PlanningAction;+ /** Opens the order drawer for a new-supply action. A host that lists change+ * actions only (the order drawer itself) omits it. */+ onOrder?: () => void;+ /** The order as the host read it; the action's own enrichment otherwise. */+ purchaseOrder?: PlanningPurchaseOrder | null;+}) {+ const { t } = useLingui();+ const isDismissed = action.status === "Dismissed";+ const reviewPath = planningActionNeedsReview(action)+ ? reviewPathFor(action)+ : null;+ const order = purchaseOrder ?? planningActionPurchaseOrder(action);+ const orderMenuItems =+ order && purchaseOrderMenuItems ? purchaseOrderMenuItems(order) : null;+ const isMine = action.assignee === currentUserId;++ return (+ <div className="flex items-center justify-end gap-1">+ {isDismissed ? (+ <span className="text-xs text-muted-foreground">+ <Trans>Dismissed</Trans>+ </span>+ ) : action.type === "Release" ? (+ // released through the order's own path — from here when the page+ // offers it, else on the order+ onRelease ? (+ <Button+ size="sm"+ variant="secondary"+ isDisabled={!canUpdate || isBusy}+ onClick={() => onRelease(action)}+ >+ <Trans>Release</Trans>+ </Button>+ ) : (+ reviewPathFor(action) && (+ <Button asChild size="sm" variant="secondary">+ <Link to={reviewPathFor(action)!}>+ <Trans>Release</Trans>+ </Link>+ </Button>+ )+ )+ ) : reviewPath ? (+ <Button asChild size="sm" variant="secondary">+ <Link to={reviewPath}>+ <Trans>Review</Trans>+ </Link>+ </Button>+ ) : isNewSupplyAction(action) ? (+ onOrder && (+ <Button+ size="sm"+ variant="secondary"+ isDisabled={!canUpdate || isBusy}+ onClick={onOrder}+ >+ {action.type === "Make" ? t`Make` : t`Order`}+ </Button>+ )+ ) : (+ <Button+ size="sm"+ variant="secondary"+ isDisabled={!canUpdate || isBusy}+ onClick={() => onApply([action.id])}+ >+ <Trans>Apply</Trans>+ </Button>+ )}++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ size="sm"+ variant="ghost"+ aria-label={t`More options`}+ icon={<LuEllipsisVertical />}+ isDisabled={!canUpdate}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={isMine || isBusy}+ onSelect={() => onAssignToMe([action.id])}+ >+ <DropdownMenuIcon icon={<LuUserCheck />} />+ <Trans>Assign to Me</Trans>+ </DropdownMenuItem>+ {isDismissed ? (+ <DropdownMenuItem+ disabled={isBusy}+ onSelect={() => onReopen([action.id])}+ >+ <DropdownMenuIcon icon={<LuRotateCcw />} />+ <Trans>Reopen</Trans>+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ disabled={isBusy}+ onSelect={() => onDismiss([action.id])}+ >+ <DropdownMenuIcon icon={<LuX />} />+ <Trans>Dismiss</Trans>+ </DropdownMenuItem>+ )}+ {orderMenuItems && (+ <>+ <DropdownMenuSeparator />+ {orderMenuItems}+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++/**+ * The action's type badge, with MRP's reason as the badge's own tooltip. A+ * sentence per row is a column no width comfortably fits, and a separate info+ * icon beside every badge was a second thing to aim at for the same answer —+ * so the badge is the hover target. It is focusable, so the reason is+ * reachable from the keyboard too.+ */+export function PlanningActionTypeWithReason({+ action+}: {+ action: PlanningAction;+}) {+ const reason = action.reason ?? action.policyName ?? "";+ const badge = <PlanningActionTypeBadge type={action.type} />;++ if (!reason) return badge;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ // focusable: the tooltip is the only place the reason is shown+ tabIndex={0}+ className="inline-flex shrink-0 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {badge}+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-[360px] whitespace-normal">+ {reason}+ {action.reason && action.policyName && (+ <div className="text-muted-foreground">{action.policyName}</div>+ )}+ </TooltipContent>+ </Tooltip>+ );+}++type PlanningActionLinesProps = PlanningActionHandlers & {+ actions: PlanningAction[];+ /** Today on the location's calendar — an action dated before it is late. */+ todayIso: string;+ /** Opens the grid's order drawer for this item (Order / Make rows). */+ onOrder: () => void;+};++/** The order an action changes, as it reads in a sentence: its status icon+ * (why the row is Review rather than Apply, named on hover) and its number. */+function PlanningActionTarget({ action }: { action: PlanningAction }) {+ const documentId =+ action.purchaseOrderReadableId ?? action.jobReadableId ?? null;+ const documentPath = reviewPathFor(action);+ return (+ <span className="inline-flex items-center gap-1 align-middle">+ <PurchasingStatus iconOnly status={action.purchaseOrderStatus} />+ <JobStatus iconOnly status={action.jobStatus} />+ {documentId && documentPath ? (+ <Link to={documentPath} className="hover:underline">+ {documentId}+ </Link>+ ) : (+ <span>{documentId ?? "—"}</span>+ )}+ </span>+ );+}++/** One action as a sentence: "Order 530 for Oct 4, 2026", "Expedite purchase+ * order PO00129 to Oct 4, 2026". The type's icon leads it and carries MRP's+ * reason as its tooltip. */+function PlanningActionSentence({+ action,+ isLate+}: {+ action: PlanningAction;+ isLate: boolean;+}) {+ const formatQuantity = useQuantityFormatter();+ const labels = usePlanningActionTypeLabels();+ const reason = action.reason ?? action.policyName ?? "";++ const quantity = formatQuantity(action.suggestedQuantity);+ const amount = <span className="tabular-nums">{quantity}</span>;+ const date = (+ <span className={cn(isLate && "text-red-500")}>+ <DateTime value={action.suggestedDate} variant="date" />+ </span>+ );+ const target = <PlanningActionTarget action={action} />;+ const isJob = action.jobId !== null;++ let sentence: ReactNode;+ switch (action.type) {+ case "Order":+ sentence = (+ <Trans>+ Order {amount} for {date}+ </Trans>+ );+ break;+ case "Make":+ sentence = (+ <Trans>+ Make {amount} for {date}+ </Trans>+ );+ break;+ case "Expedite":+ sentence = isJob ? (+ <Trans>+ Expedite job {target} to {date}+ </Trans>+ ) : (+ <Trans>+ Expedite purchase order {target} to {date}+ </Trans>+ );+ break;+ case "Defer":+ sentence = isJob ? (+ <Trans>+ Defer job {target} to {date}+ </Trans>+ ) : (+ <Trans>+ Defer purchase order {target} to {date}+ </Trans>+ );+ break;+ case "Increase":+ sentence = isJob ? (+ <Trans>+ Increase job {target} to {amount}+ </Trans>+ ) : (+ <Trans>+ Increase purchase order {target} to {amount}+ </Trans>+ );+ break;+ case "Decrease":+ sentence = isJob ? (+ <Trans>+ Decrease job {target} to {amount}+ </Trans>+ ) : (+ <Trans>+ Decrease purchase order {target} to {amount}+ </Trans>+ );+ break;+ case "Cancel":+ sentence = isJob ? (+ <Trans>Cancel job {target}</Trans>+ ) : (+ <Trans>Cancel purchase order {target}</Trans>+ );+ break;+ case "Release":+ sentence = isJob ? (+ <Trans>+ Release job {target} by {date}+ </Trans>+ ) : (+ <Trans>+ Release purchase order {target} by {date}+ </Trans>+ );+ break;+ }++ const icon = (+ <span+ // focusable: the tooltip is the only place the reason is shown+ tabIndex={0}+ role="img"+ aria-label={labels[action.type]}+ className="inline-flex shrink-0 rounded-sm text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:size-4"+ >+ {TYPE_ICONS[action.type]}+ </span>+ );++ return (+ <div className="flex min-w-0 items-center gap-2.5">+ <Tooltip>+ <TooltipTrigger asChild>{icon}</TooltipTrigger>+ <TooltipContent className="max-w-[360px] whitespace-normal">+ {labels[action.type]}+ {reason && <div className="text-muted-foreground">{reason}</div>}+ {action.reason && action.policyName && (+ <div className="text-muted-foreground">{action.policyName}</div>+ )}+ </TooltipContent>+ </Tooltip>+ <span className="truncate text-sm text-foreground">{sentence}</span>+ </div>+ );+}++/** Expanded-row content: the item's planning actions as child lines. Each is+ * two columns — the action as a sentence on the left, and its assignee and+ * controls pushed to the right. */+export function PlanningActionLines({+ actions,+ todayIso,+ onOrder,+ ...handlers+}: PlanningActionLinesProps) {+ const sorted = useMemo(() => sortPlanningActions(actions), [actions]);++ if (sorted.length === 0) return null;++ return (+ <ul className="flex w-full flex-col divide-y divide-border py-1 pl-[52px] pr-2">+ {sorted.map((action) => {+ const isDismissed = action.status === "Dismissed";+ // A Decrease / Defer / Cancel is never late (see isPlanningActionLate)+ const isLate = isPlanningActionLate(action, todayIso);++ return (+ <li+ key={action.id}+ className={cn(+ "flex min-h-11 items-center justify-between gap-4 py-1",+ isDismissed && "opacity-60"+ )}+ >+ <PlanningActionSentence action={action} isLate={isLate} />+ <div className="flex shrink-0 items-center gap-2">+ <Assignee+ id={action.id}+ table="planningAction"+ size="sm"+ value={action.assignee ?? ""}+ isReadOnly={!handlers.canUpdate || handlers.isBusy}+ className="max-w-[200px] truncate"+ onAssign={(assignee) =>+ handlers.onAssign([action.id], assignee)+ }+ />+ <PlanningActionRowActions+ action={action}+ {...handlers}+ onOrder={onOrder}+ />+ </div>+ </li>+ );+ })}+ </ul>+ );+}diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsxnew file mode 100644index 0000000000..fea65f80ef--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/PlanningDrawerParts.tsx@@ -0,0 +1,195 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Button,+ HStack,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ VStack+} from "@carbon/react";+import { Plural, Trans } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { LuCalendarRange } from "react-icons/lu";+import { useQuantityFormatter } from "~/hooks";+import { ItemReorderPolicy } from "~/modules/items/ui/Item/ItemReorderPolicy";+import type { ProductionPlanningItem } from "~/modules/production";+import { TimeFenceCell } from "~/modules/production/ui/Planning/PlanningFence";++// What the production and purchasing order drawers share. They used to keep+// a copy each, and the copies had already drifted (one drawer's labels were+// translated, the other's were not).++type Period = { id: string; startDate: string; endDate: string };++/** The planning period a date falls in: the first for a missing or past date,+ * the last for one beyond the planning window. ISO dates compare as text. */+export function periodIdFor(+ periods: Period[],+ date: string | null | undefined+) {+ if (!date || date < periods[0].startDate) return periods[0].id;+ return (+ periods.find((p) => date >= p.startDate && date <= p.endDate)?.id ??+ periods[periods.length - 1].id+ );+}++type PolicyFields = Pick<+ ProductionPlanningItem,+ | "reorderingPolicy"+ | "reorderPoint"+ | "reorderQuantity"+ | "maximumInventoryQuantity"+ | "demandAccumulationPeriod"+ | "demandAccumulationSafetyStock"+ | "lotSize"+ | "minimumOrderQuantity"+ | "maximumOrderQuantity"+>;++export function PlanningSummaryRow({+ label,+ children+}: {+ label: ReactNode;+ children: ReactNode;+}) {+ return (+ <HStack className="justify-between w-full">+ <span className="text-muted-foreground">{label}</span>+ {children}+ </HStack>+ );+}++/**+ * The drawer's policy card: the reorder policy, the row's time fence, then+ * `children` (the purchasing drawer's supplier and unit rows), then the+ * parameters of the policy in force.+ */+export function PlanningPolicySummary({+ item,+ fenceDate,+ isFenceOverridden,+ onFenceChange,+ children+}: {+ item: PolicyFields;+ fenceDate: string | null;+ isFenceOverridden: boolean;+ onFenceChange: (date: string | null) => void;+ children?: ReactNode;+}) {+ const formatQuantity = useQuantityFormatter();+ return (+ // A line between every row, whichever rows the policy shows.+ <VStack+ spacing={0}+ className="text-sm border rounded-lg px-4 py-2 divide-y divide-border [&>*]:py-2"+ >+ <PlanningSummaryRow label={<Trans>Reorder Policy:</Trans>}>+ <ItemReorderPolicy reorderingPolicy={item.reorderingPolicy} />+ </PlanningSummaryRow>+ <PlanningSummaryRow label={<Trans>Planning Horizon:</Trans>}>+ <div className="flex-none">+ <TimeFenceCell+ fenceDate={fenceDate}+ isOverridden={isFenceOverridden}+ onChange={onFenceChange}+ />+ </div>+ </PlanningSummaryRow>+ {children}+ {item.reorderingPolicy === "Maximum Quantity" && (+ <>+ <PlanningSummaryRow label={<Trans>Reorder Point:</Trans>}>+ <span>{formatQuantity(item.reorderPoint)}</span>+ </PlanningSummaryRow>+ <PlanningSummaryRow label={<Trans>Maximum Inventory:</Trans>}>+ <span>{formatQuantity(item.maximumInventoryQuantity)}</span>+ </PlanningSummaryRow>+ </>+ )}+ {item.reorderingPolicy === "Demand-Based Reorder" && (+ <>+ <PlanningSummaryRow label={<Trans>Accumulation Period:</Trans>}>+ <span>+ <Plural+ value={item.demandAccumulationPeriod}+ one="# week"+ other="# weeks"+ />+ </span>+ </PlanningSummaryRow>+ <PlanningSummaryRow label={<Trans>Safety Stock:</Trans>}>+ <span>{formatQuantity(item.demandAccumulationSafetyStock)}</span>+ </PlanningSummaryRow>+ </>+ )}+ {item.reorderingPolicy === "Fixed Reorder Quantity" && (+ <>+ <PlanningSummaryRow label={<Trans>Reorder Point:</Trans>}>+ <span>{formatQuantity(item.reorderPoint)}</span>+ </PlanningSummaryRow>+ <PlanningSummaryRow label={<Trans>Reorder Quantity:</Trans>}>+ <span>{formatQuantity(item.reorderQuantity)}</span>+ </PlanningSummaryRow>+ </>+ )}+ {item.lotSize > 0 && (+ <PlanningSummaryRow label={<Trans>Lot Size:</Trans>}>+ <span>{formatQuantity(item.lotSize)}</span>+ </PlanningSummaryRow>+ )}+ {item.minimumOrderQuantity > 0 && (+ <PlanningSummaryRow label={<Trans>Minimum Order:</Trans>}>+ <span>{formatQuantity(item.minimumOrderQuantity)}</span>+ </PlanningSummaryRow>+ )}+ {item.maximumOrderQuantity > 0 && (+ <PlanningSummaryRow label={<Trans>Maximum Order:</Trans>}>+ <span>{formatQuantity(item.maximumOrderQuantity)}</span>+ </PlanningSummaryRow>+ )}+ </VStack>+ );+}++/** "3 More After Oct 12": takes in the suggested orders beyond the fence. */+export function BeyondFenceButton({+ count,+ fenceLabel,+ onClick+}: {+ count: number;+ fenceLabel: string | null;+ onClick: () => void;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ leftIcon={<LuCalendarRange />}+ onClick={onClick}+ >+ <Plural+ value={count}+ one={`# More After ${fenceLabel}`}+ other={`# More After ${fenceLabel}`}+ />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <Trans>+ Suggested orders required after this item's planning horizon. Extend+ the horizon to include them.+ </Trans>+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningFence.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningFence.tsxnew file mode 100644index 0000000000..c746666ecd--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/PlanningFence.tsx@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ cn,+ DatePicker,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@carbon/react";+import { formatDate } from "@carbon/utils";+import { parseDate } from "@internationalized/date";+import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import { memo, useCallback, useMemo, useState } from "react";+import { effectiveFenceDate } from "./planning-fence";++// The planning horizon (time fence) on the planning grids. A row surfaces only+// the actions and suggested orders that fall on or before its fence date —+// today plus the item's saved planning horizon. A planner can move one row's+// fence on screen to look further out (or closer in); that lives in page state+// only, never on the item, and is gone after a reload.++export type FenceRow = { id: string; timeFenceDate: string | null };++/**+ * Per-row fence overrides, keyed by item id. `fenceDateFor` is the row's+ * effective fence: the override when there is one, else the saved horizon.+ * A `null` override is a cleared fence: the row shows every week. Picking the+ * saved date again, or a reload, returns the row to its saved horizon.+ */+export function useTimeFenceOverrides() {+ const [overrides, setOverrides] = useState<Record<string, string | null>>({});++ const setFenceDate = useCallback((itemId: string, date: string | null) => {+ setOverrides((prev) => {+ if (itemId in prev && prev[itemId] === date) return prev;+ return { ...prev, [itemId]: date };+ });+ }, []);++ return useMemo(+ () => ({+ setFenceDate,+ fenceDateFor: (row: FenceRow) =>+ effectiveFenceDate(row.timeFenceDate, overrides[row.id]),+ isOverridden: (row: FenceRow) =>+ row.id in overrides && overrides[row.id] !== (row.timeFenceDate ?? null)+ }),+ [overrides, setFenceDate]+ );+}++/**+ * The grid's Planning Horizon cell: the row's fence date with a calendar to+ * move it. Clearing the picker removes the fence for this view.+ */+export const TimeFenceCell = memo(function TimeFenceCell({+ fenceDate,+ isOverridden,+ onChange+}: {+ fenceDate: string | null;+ isOverridden: boolean;+ /** `null` = no fence for this view. */+ onChange: (date: string | null) => void;+}) {+ const { t } = useLingui();+ const { locale } = useLocale();++ return (+ <DatePicker+ aria-label={t`Planning horizon`}+ closeOnSelect+ value={fenceDate ? parseDate(fenceDate) : null}+ onChange={(value) => onChange(value ? value.toString() : null)}+ helperText={+ isOverridden+ ? t`Changed for this view only. The item's planning horizon is not updated.`+ : undefined+ }+ inline={+ <span+ className={cn(+ "whitespace-nowrap tabular-nums",+ !fenceDate && "text-muted-foreground",+ isOverridden && "font-medium"+ )}+ >+ {fenceDate ? formatDate(fenceDate, undefined, locale) : t`None`}+ </span>+ }+ />+ );+});++/**+ * The start of the first week the projected on-hand goes below zero — when a+ * reschedule has to land by. Red once that week has started.+ */+export const FirstNegativeDateCell = memo(function FirstNegativeDateCell({+ date,+ todayIso+}: {+ date: string | null;+ todayIso: string;+}) {+ const { locale } = useLocale();+ if (!date) return <span>-</span>;++ const isDue = date <= todayIso;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ className={cn(+ "whitespace-nowrap tabular-nums",+ isDue && "text-red-500 font-bold"+ )}+ >+ {formatDate(date, undefined, locale)}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {isDue ? (+ <Trans>Projected stock is already below zero this week</Trans>+ ) : (+ <Trans>First week the projected stock goes below zero</Trans>+ )}+ </TooltipContent>+ </Tooltip>+ );+});diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsxnew file mode 100644index 0000000000..f8a3296bf5--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/PlanningOrderGrids.tsx@@ -0,0 +1,608 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+ HStack,+ IconButton,+ Skeleton+} from "@carbon/react";+import { formatDate, INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";+import { parseDate } from "@internationalized/date";+import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import type { PostgrestSingleResponse } from "@supabase/supabase-js";+import type { ColumnDef } from "@tanstack/react-table";+import type { ReactNode } from "react";+import { useCallback, useEffect, useMemo, useRef } from "react";+import { LuEllipsisVertical, LuTrash } from "react-icons/lu";+import { Hyperlink } from "~/components";+import { EditableDate, EditableNumber } from "~/components/Editable";+import Grid from "~/components/Grid";+import { useAfterFirstPaint, useQuantityFormatter } from "~/hooks";+import type { PlanningAction } from "~/modules/production";+import type { PlanningActionHandlers } from "./PlanningActionLines";+import {+ PlanningActionRowActions,+ PlanningActionTypeWithReason+} from "./PlanningActionLines";+import type { PlanningPurchaseOrder } from "./planning-review";+import { isPlanningActionLate } from "./planning-review";++// The two tables of the planning order drawer. They look alike and save+// DIFFERENTLY, which is why they are two tables and not one list:+//+// SuggestedOrdersGrid — orders that do not exist yet. Editing a cell changes+// a draft held by the planning grid; nothing is written until the drawer's+// Order / Make button creates them.+// OpenOrdersGrid — purchase order lines / jobs that already exist. Editing a+// cell SAVES it (optimistic, reverted on failure), the way a count line or+// a Properties field does. Rows a status has locked are plain text.+//+// One list with both kinds hid that difference: an edit to an existing order+// sat unsaved until Order was pressed, and was dropped by Close.++const SAVED = {+ success: true,+ data: null,+ error: null,+ count: null,+ status: 200,+ statusText: "OK"+} as const;++/** A draft cell has nothing to persist: the grid's `onDataChange` is the save. */+const draftMutation = async () => SAVED;++/** An editable quantity commits `parse(format(x))` on blur, so it needs the+ * quantity kind's digits and step — Intl's default would round to three. */+const QUANTITY_FIELD = {+ minValue: 0,+ formatOptions: INPUT_FORMAT.quantity,+ step: INPUT_STEP.quantity+};++function SectionTitle({+ children,+ action+}: {+ children: ReactNode;+ action?: ReactNode;+}) {+ return (+ <HStack className="w-full justify-between min-h-8">+ <span className="font-medium text-sm">{children}</span>+ {action}+ </HStack>+ );+}++// ─── Suggested orders (draft) ────────────────────────────────────────────────++type SuggestedOrder = {+ quantity: number;+ dueDate?: string | null;+};++type SuggestedOrdersGridProps<O extends SuggestedOrder> = {+ title: ReactNode;+ /** Shown at the right of the title — the "N More After <fence>" button. */+ titleAction?: ReactNode;+ orders: O[];+ /** Days between placing the order and receiving it, for the Order By date. */+ leadTime: number;+ /** Today on the location's calendar (ISO), to flag an order-by date that has+ * already passed. */+ todayIso: string;+ quantityHeader: string;+ /** Header of the derived "last day to act" column: a purchase is ordered+ * by that day, a job is started by it. */+ orderByHeader: string;+ isDisabled?: boolean;+ onChange: (orders: O[]) => void;+ onAdd: () => void;+};++/**+ * Holds the drawer's expensive sections (the two grids and the chart) back+ * until the drawer itself is on screen.+ *+ * Built in the same pass as the drawer they kept the click from showing+ * anything for 200 ms on a part with a handful of orders, and far longer on one+ * with forty: every open order mounts tooltips, a menu and editable cells. With+ * this the drawer slides in at once over placeholders of about the right size,+ * and the sections fill in a frame or two later.+ */+export function DeferredDrawerSections({ children }: { children: ReactNode }) {+ const isPainted = useAfterFirstPaint();++ if (!isPainted) {+ return (+ <div className="flex w-full flex-col gap-4" aria-busy="true">+ <Skeleton className="h-28 w-full" />+ <Skeleton className="h-28 w-full" />+ <Skeleton className="h-64 w-full" />+ </div>+ );+ }++ return <>{children}</>;+}++// About eight orders tall. A part can have hundreds of open orders; past this+// the grid scrolls inside itself and renders only the rows in view. That grid+// lays its columns out fixed, so each column's `size` IS its width.+const ORDER_GRID_MAX_HEIGHT = 400;++export function SuggestedOrdersGrid<O extends SuggestedOrder>({+ title,+ titleAction,+ orders,+ leadTime,+ todayIso,+ quantityHeader,+ orderByHeader,+ isDisabled = false,+ onChange,+ onAdd+}: SuggestedOrdersGridProps<O>) {+ const { t } = useLingui();+ const { locale } = useLocale();+ const formatQuantity = useQuantityFormatter();++ const editableComponents = useMemo(+ () => ({+ quantity: EditableNumber<O>(draftMutation, QUANTITY_FIELD),+ dueDate: EditableDate<O>(draftMutation)+ }),+ []+ );++ const columns = useMemo<ColumnDef<O>[]>(() => {+ const cols: ColumnDef<O>[] = [+ {+ accessorKey: "quantity",+ header: quantityHeader,+ size: 120,+ cell: ({ row }) => (+ <span className="block min-w-[72px] tabular-nums">+ {formatQuantity(row.original.quantity)}+ </span>+ )+ },+ {+ accessorKey: "dueDate",+ header: t`Due Date`,+ size: 140,+ cell: ({ row }) => (+ <span className="block min-w-[104px] tabular-nums">+ {row.original.dueDate+ ? formatDate(row.original.dueDate, undefined, locale)+ : "—"}+ </span>+ )+ },+ {+ // The last day to place the order and still receive it by the due+ // date. Derived from the row's CURRENT due date, so it moves with an+ // edit; red once that day has passed.+ id: "orderBy",+ header: orderByHeader,+ size: 140,+ cell: ({ row }) => {+ const dueDate = row.original.dueDate;+ if (!dueDate) return "—";+ const orderBy = parseDate(dueDate)+ .subtract({ days: leadTime })+ .toString();+ return (+ <span+ className={+ orderBy < todayIso+ ? "tabular-nums font-medium text-red-500"+ : "tabular-nums"+ }+ >+ {formatDate(orderBy, undefined, locale)}+ </span>+ );+ }+ }+ ];++ // A suggestion is unsaved state until Order is pressed, so removing one+ // costs nothing and needs no confirmation — one click, as price breaks do.+ if (!isDisabled) {+ cols.push({+ id: "remove",+ header: "",+ size: 48,+ cell: ({ row }) => (+ <button+ type="button"+ aria-label={t`Remove order`}+ className="rounded p-1 text-muted-foreground transition-colors hover:text-destructive"+ onClick={(event) => {+ event.stopPropagation();+ onChange(orders.filter((_, index) => index !== row.index));+ }}+ >+ <LuTrash className="size-4" />+ </button>+ )+ });+ }++ return cols;+ }, [+ quantityHeader,+ orderByHeader,+ formatQuantity,+ locale,+ leadTime,+ todayIso,+ isDisabled,+ orders,+ onChange,+ t+ ]);++ return (+ <div className="flex w-full flex-col gap-2">+ <SectionTitle action={titleAction}>{title}</SectionTitle>+ <Grid<O>+ data={orders}+ columns={columns}+ canEdit={!isDisabled}+ editableComponents={editableComponents}+ onDataChange={onChange}+ onNewRow={!isDisabled ? onAdd : undefined}+ contained={false}+ withSimpleSorting={false}+ maxHeight={ORDER_GRID_MAX_HEIGHT}+ />+ </div>+ );+}++// ─── Open orders (saved) ─────────────────────────────────────────────────────++export type OpenOrderRow = {+ /** The record a cell edit saves to: the PO LINE id, or the job id. */+ id: string;+ /** Where the readable id links to: the purchase order, or the job. */+ documentPath: string | null;+ readableId: string;+ status: string | null;+ /** In the order's own units — purchase units on a PO line. */+ quantity: number | null;+ dueDate: string | null;+ /** False once a status has locked the order (sent to the supplier, released+ * to the floor): its cells render as plain text. */+ isEditable: boolean;+ /** The open (else dismissed) planning action that targets this order. */+ action: PlanningAction | null;+ /** The action's suggested quantity, converted to this row's units. */+ suggestedQuantity: number | null;+ /** The purchase order behind a PO line row, for the order's own menu+ * (Reopen, Finalize). Jobs have none. */+ purchaseOrder?: PlanningPurchaseOrder | null;+};++/** The ⋯ of an order no planning action targets: only the order's own+ * commands. Renders nothing when the host offers none for it. */+function OrderOnlyMenu({+ order,+ canUpdate,+ purchaseOrderMenuItems+}: {+ order: PlanningPurchaseOrder;+ canUpdate: boolean;+ purchaseOrderMenuItems: (order: PlanningPurchaseOrder) => ReactNode;+}) {+ const { t } = useLingui();+ const items = purchaseOrderMenuItems(order);+ if (!items) return null;+ return (+ <div className="flex justify-end">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ size="sm"+ variant="ghost"+ aria-label={t`More options`}+ icon={<LuEllipsisVertical />}+ isDisabled={!canUpdate}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">{items}</DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++export type OpenOrderField = "quantity" | "dueDate";++type OpenOrdersGridProps = PlanningActionHandlers & {+ title: ReactNode;+ documentHeader: string;+ quantityHeader: string;+ /** The order's status as an icon-only pill (`<XStatus iconOnly />`). */+ renderStatusIcon: (status: string) => ReactNode;+ /** `null` while the orders are being read; an `Error` when the read failed. */+ rows: OpenOrderRow[] | null | Error;+ /** Today on the location's calendar — a suggestion dated before it is late. */+ todayIso: string;+ /** Persist one field of one order. Resolve `false` (after reporting the+ * reason) to have the cell revert. */+ onSave: (+ row: OpenOrderRow,+ field: OpenOrderField,+ value: number | string+ ) => Promise<boolean>;+ onRowsChange: (rows: OpenOrderRow[]) => void;+};++const QUANTITY_ACTION_TYPES: ReadonlySet<string> = new Set([+ "Increase",+ "Decrease"+]);+const DATE_ACTION_TYPES: ReadonlySet<string> = new Set([+ "Expedite",+ "Defer",+ "Release"+]);++// The Due Date cell beside it already carries the year; the suggested date+// only needs to be told apart from it, and the drawer is narrow.+const SHORT_DATE = { month: "short", day: "numeric" } as const;++export function OpenOrdersGrid({+ title,+ documentHeader,+ quantityHeader,+ rows,+ todayIso,+ renderStatusIcon,+ onSave,+ onRowsChange,+ ...handlers+}: OpenOrdersGridProps) {+ const { t } = useLingui();+ const { locale } = useLocale();+ const formatQuantity = useQuantityFormatter();++ // The editors must keep their identity for the life of the drawer: each+ // `EditableNumber` / `EditableDate` call returns a NEW component, so rebuilding+ // them remounts the open editor and drops what the planner is typing (Tab+ // carries the edit into the next cell while the previous save is in flight,+ // and the caller's `onSave` changes when that save revalidates). The latest+ // `onSave` is read through a ref instead — React 18 has no useEffectEvent.+ const latestOnSave = useRef(onSave);+ useEffect(() => {+ latestOnSave.current = onSave;+ });++ const editableComponents = useMemo(() => {+ const saveCell = async (+ accessorKey: string,+ value: unknown,+ row: OpenOrderRow+ ): Promise<PostgrestSingleResponse<unknown>> => {+ const field = accessorKey as OpenOrderField;+ const saved = await latestOnSave.current(+ row,+ field,+ field === "quantity" ? Number(value) : String(value)+ );+ return (saved+ ? SAVED+ : {+ ...SAVED,+ error: { message: "Not saved" }+ }) as unknown as PostgrestSingleResponse<unknown>;+ };+ return {+ quantity: EditableNumber<OpenOrderRow>(saveCell, QUANTITY_FIELD),+ dueDate: EditableDate<OpenOrderRow>(saveCell)+ };+ }, []);++ // `handlers` is a rest object, new on every render, so the memo depends on+ // its members instead.+ // biome-ignore lint/correctness/useExhaustiveDependencies: the handler members listed ARE `handlers`+ const columns = useMemo<ColumnDef<OpenOrderRow>[]>(+ () => [+ {+ // The order's status as an icon in front of its number, the name in+ // the icon's tooltip. The pill itself is the widest thing in the row+ // ("To Receive and Invoice"): as its own column it pushed the+ // suggestion off the drawer, and under the number it doubled the row+ // height. Here the status is context — why this row can or cannot be+ // edited — so the icon and its colour are enough.+ id: "document",+ header: documentHeader,+ size: 190,+ cell: ({ row }) => (+ <HStack spacing={2} className="flex-nowrap">+ {row.original.status && renderStatusIcon(row.original.status)}+ {row.original.documentPath ? (+ <Hyperlink+ to={row.original.documentPath}+ className="whitespace-nowrap"+ >+ {row.original.readableId}+ </Hyperlink>+ ) : (+ <span className="whitespace-nowrap">+ {row.original.readableId}+ </span>+ )}+ </HStack>+ )+ },+ {+ accessorKey: "quantity",+ header: quantityHeader,+ size: 110,+ cell: ({ row }) => (+ <span className="tabular-nums">+ {row.original.quantity === null+ ? "—"+ : formatQuantity(row.original.quantity)}+ </span>+ )+ },+ {+ accessorKey: "dueDate",+ header: t`Due Date`,+ size: 130,+ cell: ({ row }) => (+ <span+ className={+ // an open order due before today is overdue+ row.original.dueDate && row.original.dueDate < todayIso+ ? "whitespace-nowrap tabular-nums font-medium text-red-500"+ : "whitespace-nowrap tabular-nums"+ }+ >+ {row.original.dueDate+ ? formatDate(row.original.dueDate, undefined, locale)+ : "—"}+ </span>+ )+ },+ {+ // What MRP suggests for THIS order, on its own row: the type, the+ // value it would set (the reason is behind the info icon), and the+ // one button that acts on it.+ id: "suggestion",+ header: t`Suggestion`,+ size: 330,+ cell: ({ row }) => {+ const { action, suggestedQuantity, purchaseOrder } = row.original;+ if (!action) {+ return purchaseOrder && handlers.purchaseOrderMenuItems ? (+ <OrderOnlyMenu+ order={purchaseOrder}+ canUpdate={handlers.canUpdate}+ purchaseOrderMenuItems={handlers.purchaseOrderMenuItems}+ />+ ) : null;+ }+ const isDismissed = action.status === "Dismissed";+ return (+ <HStack spacing={2} className="flex-nowrap justify-between">+ <HStack+ spacing={2}+ className={+ isDismissed+ ? "flex-nowrap whitespace-nowrap text-muted-foreground"+ : "flex-nowrap whitespace-nowrap"+ }+ >+ <PlanningActionTypeWithReason action={action} />+ {DATE_ACTION_TYPES.has(action.type) && (+ <span+ className={+ // the same rule as the expanded row: an urgent action+ // (or a Release) whose day has passed+ isPlanningActionLate(action, todayIso)+ ? "tabular-nums font-medium text-red-500"+ : "tabular-nums"+ }+ >+ {formatDate(action.suggestedDate, SHORT_DATE, locale)}+ </span>+ )}+ {QUANTITY_ACTION_TYPES.has(action.type) &&+ suggestedQuantity !== null && (+ <span className="tabular-nums">+ {formatQuantity(suggestedQuantity)}+ </span>+ )}+ </HStack>+ <PlanningActionRowActions+ action={action}+ purchaseOrder={purchaseOrder}+ {...handlers}+ />+ </HStack>+ );+ }+ }+ ],+ [+ documentHeader,+ quantityHeader,+ renderStatusIcon,+ formatQuantity,+ locale,+ todayIso,+ t,+ handlers.currentUserId,+ handlers.canUpdate,+ handlers.isBusy,+ handlers.onApply,+ handlers.onDismiss,+ handlers.onReopen,+ handlers.onAssignToMe,+ handlers.purchaseOrderMenuItems+ ]+ );++ const isRowEditable = useCallback((row: OpenOrderRow) => row.isEditable, []);++ // No open orders is the normal case for many parts: say nothing rather than+ // show an empty table. A failed read is NOT that case and says so.+ if (Array.isArray(rows) && rows.length === 0) return null;++ return (+ <div className="flex w-full flex-col gap-2">+ <SectionTitle>{title}</SectionTitle>+ {rows === null ? (+ <div className="flex flex-col gap-2">+ <Skeleton className="h-8 w-full" />+ <Skeleton className="h-8 w-full" />+ </div>+ ) : rows instanceof Error ? (+ <span className="text-sm text-muted-foreground">+ <Trans>+ These orders could not be loaded. Close and reopen to try again.+ </Trans>+ </span>+ ) : (+ <Grid<OpenOrderRow>+ data={rows}+ columns={columns}+ canEdit={handlers.canUpdate}+ editableComponents={editableComponents}+ isRowEditable={isRowEditable}+ onDataChange={onRowsChange}+ contained={false}+ withSimpleSorting={false}+ maxHeight={ORDER_GRID_MAX_HEIGHT}+ />+ )}+ </div>+ );+}++/**+ * The one planning action to show on an order's row: MRP emits at most one+ * change per target document, but a dismissed one can coexist with a newer+ * open one — the open action wins — and a planned order also carries its+ * Release. A change comes first (make it, then release the order); the+ * Release shows when there is nothing to change.+ */+export function actionForOrder(+ actions: PlanningAction[],+ matches: (action: PlanningAction) => boolean+): PlanningAction | null {+ const mine = actions.filter(matches);+ const open = mine.filter((a) => a.status === "Open");+ return open.find((a) => a.type !== "Release") ?? open[0] ?? mine[0] ?? null;+}diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningWeekStrip.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningWeekStrip.tsxnew file mode 100644index 0000000000..28151134ce--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/PlanningWeekStrip.tsx@@ -0,0 +1,179 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { cn, Tooltip, TooltipContent, TooltipTrigger } from "@carbon/react";+import { getLocalTimeZone, parseDate } from "@internationalized/date";+import { useLingui } from "@lingui/react/macro";+import { useDateFormatter } from "@react-aria/i18n";+import type { PointerEvent } from "react";+import { memo, useCallback, useMemo, useState } from "react";+import { useQuantityFormatter } from "~/hooks";+import { planningWeekGeometry } from "./planning-week-geometry";++export type PlanningPeriod = { id: string; startDate: string; endDate: string };++/**+ * The projected on-hand a planning row carries per week, in period order.+ * `week1` is the present week; a missing key means MRP wrote no projection.+ */+export function planningWeekValues(+ row: Record<string, unknown>,+ periods: PlanningPeriod[]+): (number | undefined)[] {+ return periods.map((_, index) => {+ const value = row[`week${index + 1}`];+ return typeof value === "number" ? value : undefined;+ });+}++const BAR_WIDTH = 4;+const BAR_GAP = 1;++/** Grid column width that fits every bar plus the cell padding. */+export function planningWeekStripSize(periodCount: number): number {+ return periodCount * (BAR_WIDTH + BAR_GAP) + 32;+}++type Hovered = { index: number; element: HTMLElement };++/**+ * The projected on-hand for every planning week as a small column chart on a+ * zero line: stock above it in a neutral tone, a shortfall hanging below it in+ * red. The same reading as the item planning chart (red below zero), sized for+ * a grid cell — where the row runs out and how deep it goes is visible without+ * opening anything. Red is the only hue, so it stays rare: a healthy row is+ * quiet, and sign is carried by direction as well as colour.+ *+ * A single tooltip serves the whole strip and follows the hovered week, so a+ * page of rows costs one tooltip per row rather than one per week.+ */+export const PlanningWeekStrip = memo(function PlanningWeekStrip({+ periods,+ values+}: {+ periods: PlanningPeriod[];+ values: (number | undefined)[];+}) {+ const { t } = useLingui();+ const dateFormatter = useDateFormatter({ month: "short", day: "numeric" });+ const formatQuantity = useQuantityFormatter();+ const [hovered, setHovered] = useState<Hovered | null>(null);+ const { zero, heights } = useMemo(+ () => planningWeekGeometry(values),+ [values]+ );++ const onPointerMove = useCallback((event: PointerEvent<HTMLDivElement>) => {+ const week = (event.target as HTMLElement).closest<HTMLElement>(+ "[data-week-index]"+ );+ if (!week) return;+ const index = Number(week.dataset.weekIndex);+ setHovered((current) =>+ current?.index === index ? current : { index, element: week }+ );+ }, []);++ // Without this the last week touched stayed highlighted after the pointer+ // left the strip — the highlight is hover state and has to end with the hover.+ const onPointerLeave = useCallback(() => setHovered(null), []);++ const period = hovered ? periods[hovered.index] : undefined;+ const value = hovered ? values[hovered.index] : undefined;+ const weekNumber = hovered ? hovered.index + 1 : 0;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div+ role="img"+ aria-label={t`Projected stock by week`}+ className="relative flex h-6"+ style={{ gap: BAR_GAP }}+ onPointerMove={onPointerMove}+ onPointerLeave={onPointerLeave}+ >+ {/* the zero line */}+ <div+ aria-hidden+ className="pointer-events-none absolute inset-x-0 h-px -translate-y-1/2 bg-border"+ style={{ top: `${zero}%` }}+ />+ {values.map((weekValue, index) => {+ const isShort = weekValue !== undefined && weekValue < 0;+ const hasBar = weekValue !== undefined && weekValue !== 0;+ return (+ // The week's hit area is the full height of the strip, so a+ // short bar is as easy to hover as a tall one.+ <div+ key={periods[index]?.id ?? index}+ data-week-index={index}+ className="relative h-full shrink-0"+ style={{ width: BAR_WIDTH }}+ >+ {hasBar ? (+ <div+ className={cn(+ "absolute inset-x-0 min-h-[2px] rounded-[1px]",+ isShort ? "bg-red-500" : "bg-muted-foreground/50"+ )}+ style={+ isShort+ ? { top: `${zero}%`, height: `${heights[index]}%` }+ : {+ bottom: `${100 - zero}%`,+ height: `${heights[index]}%`+ }+ }+ />+ ) : (+ // exactly zero: a tick on the line; no projection: nothing+ weekValue === 0 && (+ <div+ className="absolute inset-x-0 h-[2px] -translate-y-1/2 rounded-[1px] bg-muted-foreground/50"+ style={{ top: `${zero}%` }}+ />+ )+ )}+ {/* The hovered week, marked over the whole column — the same+ cue as the planning chart's cursor band. It sits ON TOP of+ the bar: behind it, a full-height bar hid it completely. */}+ {hovered?.index === index && (+ <div+ aria-hidden+ className="absolute inset-0 rounded-[1px] bg-foreground/20"+ />+ )}+ </div>+ );+ })}+ </div>+ </TooltipTrigger>+ {hovered && period && (+ <TooltipContent anchor={hovered.element}>+ <div className="grid grid-cols-[auto_auto] gap-x-3 gap-y-0.5">+ <span className="col-span-2 font-medium">+ {weekNumber === 1 ? t`Present Week` : t`Week ${weekNumber}`}+ </span>+ <span className="col-span-2 text-xs text-muted-foreground">+ {dateFormatter.formatRange(+ parseDate(period.startDate).toDate(getLocalTimeZone()),+ parseDate(period.endDate).toDate(getLocalTimeZone())+ )}+ </span>+ <span className="text-muted-foreground">{t`Projected`}</span>+ <span+ className={cn(+ "text-right tabular-nums",+ value !== undefined && value < 0 && "font-medium text-red-500"+ )}+ >+ {value === undefined ? "-" : formatQuantity(value)}+ </span>+ </div>+ </TooltipContent>+ )}+ </Tooltip>+ );+});diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsxindex 9f1ddd66db..6703db96bf 100644--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx@@ -3,9 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { useRevalidator } from "@carbon/query";import {Button,- DatePicker,Drawer,DrawerBody,DrawerContent,@@ -13,53 +13,77 @@ import {DrawerFooter,DrawerHeader,DrawerTitle,- HStack,- IconButton,- NumberDecrementStepper,- NumberField,- NumberIncrementStepper,- NumberInput,- NumberInputGroup,- NumberInputStepper,- Separator,- Table as TableBase,- Tbody,- Td,- Th,- Thead,- Tr,- toast,- useMount,- VStack+ toast} from "@carbon/react";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import { formatDate } from "@carbon/utils";+import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";-import { memo, useCallback, useEffect, useMemo } from "react";-import {- LuBlocks,- LuCalendar,- LuChevronDown,- LuChevronUp,- LuCirclePlay,- LuExternalLink,- LuPlus,- LuStar,- LuTrash2-} from "react-icons/lu";+import { useLocale } from "@react-aria/i18n";+import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { LuExternalLink } from "react-icons/lu";import { Link, useFetcher } from "react-router";-import { useRouteData } from "~/hooks";import { getLinkToItemPlanning } from "~/modules/items/ui/Item/ItemForm";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";-import { ItemReorderPolicy } from "~/modules/items/ui/Item/ItemReorderPolicy";-import type { ProductionOrder } from "~/modules/production";+import type { PlanningAction, ProductionOrder } from "~/modules/production";+import {+ isJobEditableFromPlanning,+ type jobStatus+} from "~/modules/production/production.models";+import type { PlanningActionHandlers } from "~/modules/production/ui/Planning/PlanningActionLines";+import {+ BeyondFenceButton,+ PlanningPolicySummary,+ periodIdFor+} from "~/modules/production/ui/Planning/PlanningDrawerParts";+import type {+ OpenOrderField,+ OpenOrderRow+} from "~/modules/production/ui/Planning/PlanningOrderGrids";+import {+ actionForOrder,+ DeferredDrawerSections,+ OpenOrdersGrid,+ SuggestedOrdersGrid+} from "~/modules/production/ui/Planning/PlanningOrderGrids";+import { chartedOrderQuantity } from "~/modules/production/ui/Planning/planning-increase";import type { action as bulkUpdateAction } from "~/routes/x+/production+/planning.update";import { path } from "~/utils/path";import type { ProductionPlanningItem } from "../../types";import { JobStatus } from "../Jobs";+/** An existing job in the planned-order shape the chart reads, plus the+ * quantity it was read at (so the chart can tell a planner's edit from the+ * stored job). */+type OpenProductionOrder = ProductionOrder & {+ existingId: string;+ loadedQuantity: number;+};+type ProductionPlanningOrderDrawerProps = {+ /**+ * Today on the plant's calendar (the planning loader's `locationToday`).+ * Planned-order defaults are business dates there, and "late" is measured+ * from it, never from the planner's browser zone.+ */+ locationToday: string;row: ProductionPlanningItem;orders: ProductionOrder[];+ /** Suggested orders required AFTER the row's time fence. The drawer opens+ * without them; one button extends the fence to take them in. */+ beyondFenceOrders: ProductionOrder[];+ /** The row's time fence (ISO date), or null when it has none. */+ timeFenceDate: string | null;+ /** True when the fence was moved on screen, away from the saved horizon. */+ isTimeFenceOverridden: boolean;+ /** Move this row's fence without leaving the drawer — the same on-screen+ * override as the grid's Planning Horizon cell. `null` clears the fence+ * for this view. The suggested orders re-split around the new date. */+ onTimeFenceChange: (date: string | null) => void;+ /** The item's change actions on existing jobs, inside the fence. Each one is+ * shown on the row of the job it targets. */+ actions: PlanningAction[];+ /** Apply / dismiss / reopen / assign, owned by the grid (one fetcher). */+ actionHandlers: PlanningActionHandlers;setOrders: (item: ProductionPlanningItem, orders: ProductionOrder[]) => void;locationId: string;periods: { id: string; startDate: string; endDate: string }[];@@ -71,96 +95,259 @@ export const ProductionPlanningOrderDrawer = memo(({row,orders,+ beyondFenceOrders,+ timeFenceDate,+ isTimeFenceOverridden,+ onTimeFenceChange,+ actions,+ actionHandlers,setOrders,locationId,periods,isOpen,- onClose+ onClose,+ locationToday}: ProductionPlanningOrderDrawerProps) => {const fetcher = useFetcher<typeof bulkUpdateAction>();+ const { revalidate } = useRevalidator();const { t } = useLingui();- // Planned-order defaults are business dates on the plant's calendar — use- // the loader's location-today, not the planner's browser zone.- const planningData = useRouteData<{ locationToday?: string }>(- path.to.productionPlanning- );- const locationToday =- planningData?.locationToday ?? today(getLocalTimeZone()).toString();+ const { locale } = useLocale();+ const fenceLabel = timeFenceDate+ ? formatDate(timeFenceDate, undefined, locale)+ : null;const { carbon } = useCarbon();- // Memoize getExistingOrders callback- const getExistingOrders = useCallback(async () => {- if (!carbon || !row.id) return;-- const { data: existingOrderData } = await carbon- ?.from("job")- .select("*")- .eq("itemId", row.id)- .is("salesOrderId", null)- .is("salesOrderLineId", null)- .in("status", ["Draft", "Planned"]);-- if (existingOrderData) {- const existingOrders: ProductionOrder[] = existingOrderData- .filter(- (order) =>- !orders.some((existing) => existing.existingId === order.id)+ // ── Open jobs: the item's existing make-to-stock jobs ───────────────────+ // Held here, not in the grid's draft list: a cell edit on one of these is+ // SAVED (onSaveOpenJob), where a suggested job is a draft until Make is+ // pressed. `null` while loading, an Error when the read failed.+ //+ // Released jobs (Ready / In Progress / Paused) are listed too, read-only:+ // MRP raises actions on them, and an action needs its job's row to sit on.+ const [openJobs, setOpenJobs] = useState<+ OpenProductionOrder[] | null | Error+ >(null);++ // Re-read when the item's actions change: applying one rewrites its job.+ const actionsKey = actions.map((a) => `${a.id}:${a.status}`).join(",");++ // Only while open: the drawer stays mounted on its last item so it can+ // slide out, and that item's actions change with every Apply on the grid.+ // biome-ignore lint/correctness/useExhaustiveDependencies: actionsKey stands in for `actions`; periods are fixed for the page+ useEffect(() => {+ if (!isOpen || !carbon || !row.id) return;+ let isCurrent = true;++ (async () => {+ const jobs = await carbon+ .from("job")+ .select(+ "id, jobId, status, quantity, startDate, dueDate, deadlineType")- .map((order) => {- // If no due date or due date is before first period, use first period- if (- !order.dueDate ||- parseDate(order.dueDate) < parseDate(periods[0].startDate)- ) {- return {- existingId: order.id,- existingReadableId: order.jobId,- existingQuantity: order.status === "Draft" ? 0 : order.quantity,- existingStatus: order.status,- startDate: order.startDate ?? null,- dueDate: order.dueDate ?? null,- quantity: order.quantity,- isASAP: order.deadlineType === "ASAP",- periodId: periods[0].id- };- }+ .eq("itemId", row.id)+ // this page's location only: the rows are editable and charted here+ .eq("locationId", locationId)+ .is("salesOrderId", null)+ .is("salesOrderLineId", null)+ .in("status", ["Draft", "Planned", "Ready", "In Progress", "Paused"]);+ if (!isCurrent) return;+ if (jobs.error) {+ setOpenJobs(new Error(jobs.error.message));+ return;+ }- // Find matching period based on due date- const period = periods.find((p) => {- const dueDate = parseDate(order.dueDate!);- const startDate = parseDate(p.startDate);- const endDate = parseDate(p.endDate);- return dueDate >= startDate && dueDate <= endDate;- });-- // If no matching period found (date is after last period), use last period- return {- existingId: order.id,- existingReadableId: order.jobId,- existingQuantity: order.status === "Draft" ? 0 : order.quantity,- existingStatus: order.status,- startDate: order.startDate ?? null,- dueDate: order.dueDate ?? null,- quantity: order.quantity,- isASAP: order.deadlineType === "ASAP",- periodId: period?.id ?? periods[periods.length - 1].id- };- });+ setOpenJobs(+ (jobs.data ?? [])+ .map(+ (job): OpenProductionOrder => ({+ existingId: job.id,+ existingReadableId: job.jobId,+ // a Draft job is not supply yet, so all of it is new to the chart+ existingQuantity: job.status === "Draft" ? 0 : job.quantity,+ existingStatus: job.status,+ startDate: job.startDate ?? null,+ dueDate: job.dueDate ?? null,+ quantity: job.quantity,+ loadedQuantity: job.quantity,+ isASAP: job.deadlineType === "ASAP",+ periodId: periodIdFor(periods, job.dueDate)+ })+ )+ .sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))+ );+ })();++ return () => {+ isCurrent = false;+ };+ }, [isOpen, carbon, row.id, locationId, actionsKey]);- setOrders(- row,- [...orders, ...existingOrders].sort((a, b) => {- return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;- })+ const openJobRows = useMemo<OpenOrderRow[] | null | Error>(() => {+ if (!Array.isArray(openJobs)) return openJobs;++ const rows: OpenOrderRow[] = openJobs.map((job) => {+ const action = actionForOrder(+ actions,+ (a) => a.jobId === job.existingId);- }- }, [carbon, orders, row, setOrders, periods]);+ return {+ id: job.existingId,+ documentPath: path.to.job(job.existingId),+ readableId: job.existingReadableId ?? "",+ status: job.existingStatus ?? null,+ quantity: job.quantity,+ dueDate: job.dueDate ?? null,+ isEditable: isJobEditableFromPlanning(job.existingStatus),+ action,+ suggestedQuantity: action ? Number(action.suggestedQuantity) : null+ };+ });- useMount(() => {- if (row.id) {- getExistingOrders();+ // An action whose job is not in the list still has to be shown — a+ // suggestion that silently drops out of the drawer reads as "nothing to+ // do". It gets a read-only row built from the action itself.+ for (const action of actions) {+ if (rows.some((r) => r.action?.id === action.id)) continue;+ rows.push({+ id: action.id,+ documentPath: action.jobId ? path.to.job(action.jobId) : null,+ readableId: action.jobReadableId ?? "—",+ status: action.jobStatus ?? null,+ quantity: null,+ dueDate: null,+ isEditable: false,+ action,+ suggestedQuantity: Number(action.suggestedQuantity)+ });}- });++ return rows;+ }, [openJobs, actions]);++ const onOpenJobsChange = useCallback((rows: OpenOrderRow[]) => {+ setOpenJobs((previous) =>+ Array.isArray(previous)+ ? previous.map((job) => {+ const updated = rows.find((r) => r.id === job.existingId);+ return updated && updated.quantity !== null+ ? {+ ...job,+ quantity: updated.quantity,+ dueDate: updated.dueDate+ }+ : job;+ })+ : previous+ );+ }, []);++ // One cell, one field, one request. The route re-reads the job under the+ // company and refuses one that has been released, so a stale row here+ // cannot edit a job on the floor.+ const onSaveOpenJob = useCallback(+ async (+ openRow: OpenOrderRow,+ field: OpenOrderField,+ value: number | string+ ) => {+ try {+ const response = await fetch(path.to.bulkUpdateProductionPlanning, {+ method: "post",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ action: "updateJob",+ locationId,+ job: { id: openRow.id, field, value }+ })+ });+ const result = (await response.json().catch(() => null)) as {+ success?: boolean;+ message?: string;+ warning?: string;+ } | null;+ if (response.ok && result?.success) {+ // Saved, but a follow-up step failed: keep the new value and say so.+ if (result.warning) toast.error(result.warning);+ // A plain fetch bypasses the router: refresh the grid row behind+ // the drawer, which otherwise shows the old value until the next+ // navigation.+ void revalidate();+ return true;+ }+ toast.error(result?.message ?? t`Failed to update job`);+ return false;+ } catch {+ toast.error(t`Failed to update job`);+ return false;+ }+ },+ [locationId, revalidate, t]+ );++ const renderOpenJobStatus = useCallback(+ (status: string) => (+ <JobStatus iconOnly status={status as (typeof jobStatus)[number]} />+ ),+ []+ );++ // What the chart overlays as planned supply: the draft jobs, plus the jobs+ // a planner can still change so an edit shows before MRP runs again, and+ // any job with an open Increase — charted at it, since it took the place+ // of a draft job.+ const chartOrders = useMemo<ProductionOrder[]>(+ () =>+ Array.isArray(openJobs)+ ? [+ ...orders,+ ...openJobs.flatMap(({ loadedQuantity, ...job }) => {+ const increase = actionForOrder(+ actions,+ (a) => a.type === "Increase" && a.jobId === job.existingId+ );+ if (!increase && !isJobEditableFromPlanning(job.existingStatus))+ return [];+ return [+ {+ ...job,+ quantity: chartedOrderQuantity({+ quantity: job.quantity,+ loadedQuantity,+ increase+ })+ }+ ];+ })+ ]+ : orders,+ [orders, openJobs, actions]+ );++ const onSuggestedOrdersChange = useCallback(+ (next: ProductionOrder[]) => setOrders(row, next),+ [row, setOrders]+ );++ // "N More After <fence>": move this row's fence out to the last suggested+ // order, rather than copying those orders into the list. The fence is the+ // one piece of state — the order list, the Action table below, and the+ // grid row's chips and quantity all follow it, so the pulled-in orders and+ // their Order actions appear together and stay in step.+ const lastBeyondFenceDate = useMemo(+ () =>+ beyondFenceOrders.reduce<string | null>(+ (latest, order) =>+ order.dueDate && (!latest || order.dueDate > latest)+ ? order.dueDate+ : latest,+ null+ ),+ [beyondFenceOrders]+ );++ const onIncludeBeyondFence = useCallback(() => {+ if (lastBeyondFenceDate) onTimeFenceChange(lastBeyondFenceDate);+ }, [lastBeyondFenceDate, onTimeFenceChange]);// Memoize handlersconst onAddOrder = useCallback(() => {@@ -178,42 +365,13 @@ export const ProductionPlanningOrderDrawer = memo(}}, [row, orders, setOrders, periods, locationToday]);- const onRemoveOrder = useCallback(- (index: number) => {- if (row.id) {- const newOrders = orders.filter((_, i) => i !== index);- setOrders(row, newOrders);- }- },- [row, orders, setOrders]- );-const onSubmit = useCallback((id: string, orders: ProductionOrder[]) => {const ordersWithPeriods = orders.map((order) => {// If no due date or due date is before first period, use first period- if (- !order.dueDate ||- parseDate(order.dueDate) < parseDate(periods[0].startDate)- ) {- return {- ...order,- periodId: periods[0].id- };- }-- // Find matching period based on due date- const period = periods.find((p) => {- const dueDate = parseDate(order.dueDate!);- const startDate = parseDate(p.startDate);- const endDate = parseDate(p.endDate);- return dueDate >= startDate && dueDate <= endDate;- });-- // If no matching period found (date is after last period), use last periodreturn {...order,- periodId: period?.id ?? periods[periods.length - 1].id+ periodId: periodIdFor(periods, order.dueDate)};});@@ -236,21 +394,6 @@ export const ProductionPlanningOrderDrawer = memo([fetcher, locationId, periods]);- // Memoize order update handler- const handleOrderUpdate = useCallback(- (index: number, updates: Partial<ProductionOrder>) => {- if (row.id) {- const newOrders = [...orders];- newOrders[index] = {- ...orders[index],- ...updates- };- setOrders(row, newOrders);- }- },- [row, orders, setOrders]- );-// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (fetcher.data?.success === false && fetcher?.data?.message) {@@ -282,238 +425,70 @@ export const ProductionPlanningOrderDrawer = memo(</DrawerHeader><DrawerBody><div className="flex flex-col gap-4 w-full">- <VStack spacing={2} className="text-sm border rounded-lg p-4">- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Reorder Policy:</Trans>- </span>- <ItemReorderPolicy reorderingPolicy={row.reorderingPolicy} />- </HStack>- <Separator />- {row.reorderingPolicy === "Maximum Quantity" && (- <>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Reorder Point:- </span>- <span>{row.reorderPoint}</span>- </HStack>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Maximum Inventory:- </span>- <span>{row.maximumInventoryQuantity}</span>- </HStack>- </>- )}-- {row.reorderingPolicy === "Demand-Based Reorder" && (- <>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Accumulation Period:- </span>- <span>{row.demandAccumulationPeriod} weeks</span>- </HStack>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Safety Stock:- </span>- <span>{row.demandAccumulationSafetyStock}</span>- </HStack>- </>- )}-- {row.reorderingPolicy === "Fixed Reorder Quantity" && (- <>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Reorder Point:- </span>- <span>{row.reorderPoint}</span>- </HStack>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Reorder Quantity:- </span>- <span>{row.reorderQuantity}</span>- </HStack>- </>- )}- {(row.lotSize > 0 ||- row.minimumOrderQuantity > 0 ||- row.maximumOrderQuantity > 0) && <Separator />}- {row.lotSize > 0 && (- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Lot Size:</Trans>- </span>- <span>{row.lotSize}</span>- </HStack>- )}- {row.minimumOrderQuantity > 0 && (- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Minimum Order:- </span>- <span>{row.minimumOrderQuantity}</span>- </HStack>- )}- {row.maximumOrderQuantity > 0 && (- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- Maximum Order:- </span>- <span>{row.maximumOrderQuantity}</span>- </HStack>- )}- </VStack>-- <TableBase full>- <Thead>- <Th>- <div className="flex items-center gap-2">- <LuCirclePlay />- <span>- <Trans>Job</Trans>- </span>- </div>- </Th>- <Th>- <div className="flex items-center gap-2 text-left">- <LuStar />- <span>- <Trans>Status</Trans>- </span>- </div>- </Th>- <Th>- <div className="flex items-center gap-2 text-right">- <LuBlocks />- <span>- <Trans>Quantity</Trans>- </span>- </div>- </Th>- <Th>- <div className="flex items-center gap-2">- <LuCalendar />- <span>- <Trans>Due Date</Trans>- </span>- </div>- </Th>- <Th className="w-[50px]"></Th>- </Thead>- <Tbody>- {orders.map((order, index) => (- <Tr key={index}>- <Td className="group-hover:bg-inherit justify-between whitespace-nowrap">- {order.existingReadableId && order.existingId ? (- <Link to={path.to.job(order.existingId)}>- {order.existingReadableId}- </Link>- ) : (- "New Job"- )}- </Td>- <Td className="flex flex-row items-center gap-1 group-hover:bg-inherit">- <JobStatus status={order.existingStatus as "Draft"} />- </Td>- <Td className="text-right group-hover:bg-inherit">- <NumberField- value={order.quantity}- onBlur={(e) => {- const datePickerInput = e.target- .closest("tr")- ?.querySelector(- '[role="textbox"]'- ) as HTMLElement;- if (datePickerInput) {- datePickerInput.focus();- }- }}- onChange={(value) => {- if (value) {- handleOrderUpdate(index, { quantity: value });- }- }}- >- <NumberInputGroup className="relative group-hover:bg-inherit">- <NumberInput />- <NumberInputStepper>- <NumberIncrementStepper>- <LuChevronUp size="1em" strokeWidth="3" />- </NumberIncrementStepper>- <NumberDecrementStepper>- <LuChevronDown size="1em" strokeWidth="3" />- </NumberDecrementStepper>- </NumberInputStepper>- </NumberInputGroup>- </NumberField>- </Td>- <Td className="text-right group-hover:bg-inherit">- <HStack className="justify-end">- <DatePicker- value={- order.dueDate ? parseDate(order.dueDate) : null- }- onChange={(date) => {- handleOrderUpdate(index, {- dueDate: date ? date.toString() : null- });- }}- />- </HStack>- </Td>- <Td className="group-hover:bg-inherit">- <IconButton- aria-label={t`Remove order`}- variant="ghost"- size="sm"- isDisabled={!!order.existingId}- onClick={() => onRemoveOrder(index)}- icon={<LuTrash2 className="text-destructive" />}- />- </Td>- </Tr>- ))}- </Tbody>- </TableBase>-- <div>- <Button- variant="secondary"- size="sm"- className="mt-4"- leftIcon={<LuPlus />}- onClick={onAddOrder}- >- Add Order- </Button>- </div>-- <ItemPlanningChart- compact- itemId={row.id}- locationId={locationId}- safetyStock={row.demandAccumulationSafetyStock}- plannedOrders={orders}+ <PlanningPolicySummary+ item={row}+ fenceDate={timeFenceDate}+ isFenceOverridden={isTimeFenceOverridden}+ onFenceChange={onTimeFenceChange}/>++ <DeferredDrawerSections>+ <SuggestedOrdersGrid<ProductionOrder>+ title={<Trans>Suggested Jobs</Trans>}+ titleAction={+ lastBeyondFenceDate &&+ timeFenceDate && (+ <BeyondFenceButton+ count={beyondFenceOrders.length}+ fenceLabel={fenceLabel}+ onClick={onIncludeBeyondFence}+ />+ )+ }+ orders={orders}+ leadTime={row.leadTime ?? 0}+ todayIso={locationToday}+ quantityHeader={t`Quantity`}+ orderByHeader={t`Start By`}+ onChange={onSuggestedOrdersChange}+ onAdd={onAddOrder}+ />++ <OpenOrdersGrid+ title={<Trans>Open Jobs</Trans>}+ documentHeader={t`Job`}+ quantityHeader={t`Qty`}+ rows={openJobRows}+ todayIso={locationToday}+ renderStatusIcon={renderOpenJobStatus}+ onSave={onSaveOpenJob}+ onRowsChange={onOpenJobsChange}+ {...actionHandlers}+ />++ <ItemPlanningChart+ compact+ itemId={row.id}+ locationId={locationId}+ safetyStock={row.demandAccumulationSafetyStock}+ timeFenceDate={timeFenceDate}+ plannedOrders={chartOrders}+ />+ </DeferredDrawerSections></div></DrawerBody><DrawerFooter><Button variant="secondary" onClick={onClose}>- Close+ <Trans>Close</Trans></Button><Buttonvariant="primary"onClick={() => onSubmit(row.id, orders)}- disabled={fetcher.state !== "idle"}- isDisabled={fetcher.state !== "idle"}+ disabled={fetcher.state !== "idle" || orders.length === 0}+ isDisabled={fetcher.state !== "idle" || orders.length === 0}isLoading={fetcher.state !== "idle"}>- Make+ <Trans>Make</Trans></Button></DrawerFooter></DrawerContent>@@ -525,9 +500,22 @@ export const ProductionPlanningOrderDrawer = memo(fetcher.state,onClose,onAddOrder,- onRemoveOrder,onSubmit,- handleOrderUpdate,+ onSuggestedOrdersChange,+ lastBeyondFenceDate,+ beyondFenceOrders,+ onIncludeBeyondFence,+ openJobRows,+ renderOpenJobStatus,+ onSaveOpenJob,+ onOpenJobsChange,+ actionHandlers,+ chartOrders,+ locationToday,+ timeFenceDate,+ isTimeFenceOverridden,+ onTimeFenceChange,+ fenceLabel,t]);diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsxindex 63f6f767c9..780fd4d5d2 100644--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx@@ -12,7 +12,6 @@ import {DropdownMenuLabel,DropdownMenuSeparator,HStack,- Loading,PulsingDot,Tooltip,TooltipContent,@@ -20,94 +19,181 @@ import {toast,VStack} from "@carbon/react";-import { getLocalTimeZone, parseDate } from "@internationalized/date";+import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";-import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";import type { ColumnDef } from "@tanstack/react-table";+import { useCallback, useEffect, useMemo, useState } from "react";import {- useCallback,- useDeferredValue,- useEffect,- useMemo,- useState-} from "react";-import {- LuBlocks,LuBookMarked,- LuBox,LuCircleCheck,LuCirclePlay,- LuSquareChartGantt+ LuListTodo,+ LuSquareChartGantt,+ LuUserCheck} from "react-icons/lu";-import { Link, useFetcher } from "react-router";+import { Link, useFetcher, useSearchParams } from "react-router";import {+ EmployeeAvatarGroup,exportOnlyColumn,ItemThumbnail,- MethodItemTypeIcon,Table} from "~/components";-import { Enumerable } from "~/components/Enumerable";+import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useLocations } from "~/components/Form/Location";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";-import { usePermissions } from "~/hooks";-import { inventoryItemTypes } from "~/modules/inventory/inventory.models";-import { itemReorderingPolicies } from "~/modules/items/items.models";import {- clearOrdersCache,- getProductionOrdersFromPlanning,- getReorderPolicyDescription,- ItemReorderPolicy-} from "~/modules/items/ui/Item/ItemReorderPolicy";-import type { ProductionOrder } from "~/modules/production";+ useLinkedDrawerItem,+ useMrpScheduleDescription,+ usePermissions,+ useQuantityFormatter,+ useUser+} from "~/hooks";+import type { PlanningAction, ProductionOrder } from "~/modules/production";+import {+ PLANNING_ACTIONS_COLUMN,+ PLANNING_ASSIGNEE_COLUMN,+ PLANNING_DRAWER_PARAM+} from "~/modules/production";+import {+ isApplyablePlanningAction,+ isNewSupplyAction,+ PlanningActionLines,+ PlanningActionsCell,+ planningActionDot,+ planningActionsExportValue,+ usePlanningActionTypeOptions+} from "~/modules/production/ui/Planning/PlanningActionLines";+import {+ openNewSupplyActions,+ productionOrdersFromActions+} from "~/modules/production/ui/Planning/planned-orders-from-actions";+import { splitOrdersByFence } from "~/modules/production/ui/Planning/planning-fence";+import { planningColumns } from "~/modules/production/ui/Planning/planningColumns";+import { useJobPlanningRelease } from "~/modules/production/ui/Planning/useJobPlanningRelease";+import { usePlanningActions } from "~/modules/production/ui/Planning/usePlanningActions";import type { action as mrpAction } from "~/routes/api+/mrp";import type { action as bulkUpdateAction } from "~/routes/x+/production+/planning.update";+import { usePeople } from "~/stores";import { path } from "~/utils/path";import type { ProductionPlanningItem } from "../../types";import { ProductionPlanningOrderDrawer } from "./ProductionPlanningOrderDrawer";type ProductionPlanningTableProps = {data: ProductionPlanningItem[];+ /** The row a `?item=` link opens the drawer on when it is not in `data`. */+ drawerItem: ProductionPlanningItem | null;count: number;locationId: string;periods: { id: string; startDate: string; endDate: string }[];+ /** The persisted MRP worklist for the rows on this page (spec §P1.7),+ * rendered as the Actions column + each item's expanded row. Every action+ * is here whatever its date; the row's time fence decides what shows. */+ planningActions: PlanningAction[];+ /** The Actions-column filter in effect; null when the grid is not filtered+ * by action type. */+ actionTypes: string[] | null;+ /** Today on the location's calendar (ISO date). */+ locationToday: string;};const ProductionPlanningTable = ({data,+ drawerItem,count,locationId,- periods+ periods,+ planningActions,+ actionTypes,+ locationToday}: ProductionPlanningTableProps) => {const permissions = usePermissions();- const { t } = useLingui();-- const dateFormatter = useDateFormatter({- month: "short",- day: "numeric"- });+ const { t, i18n } = useLingui();- const numberFormatter = useNumberFormatter();+ // Memoized on the locale, so it never rebuilds `columns` on its own.+ const formatQuantity = useQuantityFormatter();const locations = useLocations();const unitOfMeasures = useUnitOfMeasure();+ const itemPostingGroups = useItemPostingGroups();const mrpFetcher = useAction<typeof mrpAction>({onSettled: (data) => {- if (data) {- clearOrdersCache();- setOrdersMap({}); // Reset local state to force recalculation- }+ // the drawer re-seeds from the new run's actions+ if (data) setOrdersMap({});}});+ const mrpScheduleDescription = useMrpScheduleDescription();++ // What the order drawer can open on: the page's rows, plus the row a link+ // names when it is not on this page.+ const drawerRows = useMemo(+ () => (drawerItem ? [...data, drawerItem] : data),+ [data, drawerItem]+ );++ // ── Planning actions (the MRP worklist) ──────────────────────────────────+ const user = useUser();+ const canUpdateActions = permissions.can("update", "production");+ const actionTypeOptions = usePlanningActionTypeOptions("Make");+ const [people] = usePeople();+ const {+ actionHandlers: changeActionHandlers,+ isActionsBusy,+ timeFence,+ actionsByItemId,+ fencedActionsByItemId,+ visibleActionsByItemId,+ submitActions+ } = usePlanningActions({+ data: drawerRows,+ planningActions,+ actionTypes,+ locationId,+ updatePath: path.to.bulkUpdateProductionPlanning,+ currentUserId: user.id,+ canUpdate: canUpdateActions+ });++ // A job's Release button releases it from here (the jobs table's release+ // route), rather than opening the job.+ const { onRelease, isReleasing } = useJobPlanningRelease();+ const actionHandlers = useMemo(+ () => ({+ ...changeActionHandlers,+ isBusy: changeActionHandlers.isBusy || isReleasing,+ onRelease+ }),+ [changeActionHandlers, isReleasing, onRelease]+ );const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();- // Clear local state when data changes (e.g., filters, search)- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ // The drawer's draft orders are page state keyed by item. They are dropped+ // when the page's scope changes (location, filters, search, sort, page) and+ // when MRP recalculates (mrpFetcher above) or an order is placed (below) —+ // NOT on every reload of the loader: Apply, Dismiss and Assign inside the+ // drawer revalidate it, and that used to wipe the planner's edits in the+ // suggested-orders table above them.+ const [searchParams] = useSearchParams();+ // The open drawer is in the address too, and is not a change of scope.+ const pageScope = useMemo(() => {+ const scope = new URLSearchParams(searchParams);+ scope.delete(PLANNING_DRAWER_PARAM);+ return scope.toString();+ }, [searchParams]);+ // biome-ignore lint/correctness/useExhaustiveDependencies: the scope string is the dependencyuseEffect(() => {setOrdersMap({});- }, [data]);+ }, [pageScope]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {+ // Once per completed submission: the fetcher settles to idle with that+ // submission's data. Keyed on `data.success` alone, a second Create Jobs in+ // the same session (success again) never re-ran this — no toast, and the+ // spent drafts stayed in `ordersMap`.+ if (bulkUpdateFetcher.state !== "idle" || !bulkUpdateFetcher.data) {+ return;+ }+if (bulkUpdateFetcher.data?.success === false &&bulkUpdateFetcher?.data?.message@@ -117,14 +203,14 @@ const ProductionPlanningTable = ({}if (bulkUpdateFetcher.data?.success === true) {+ // The drafts became jobs; the next open re-seeds from the new split.+ setOrdersMap({});const {jobs = [],- updatedJobCount = 0,alreadyPlannedItemCount = 0,noDemandItemCount = 0} = bulkUpdateFetcher.data as {jobs?: { id: string; readableId: string }[];- updatedJobCount?: number;alreadyPlannedItemCount?: number;noDemandItemCount?: number;};@@ -145,7 +231,7 @@ const ProductionPlanningTable = ({);}- if (jobs.length === 0 && updatedJobCount === 0) {+ if (jobs.length === 0) {toast.info(skipped.length > 0 ? skipped.join(" · ") : t`No jobs were created`);@@ -154,16 +240,10 @@ const ProductionPlanningTable = ({const created =jobs.length === 1 ? t`1 job created` : t`${jobs.length} jobs created`;- const updated =- updatedJobCount > 0- ? updatedJobCount === 1- ? t`1 job updated`- : t`${updatedJobCount} jobs updated`- : null;toast.success(<VStack spacing={1}>- <span>{[created, updated].filter(Boolean).join(" · ")}</span>+ <span>{created}</span>{jobs.length > 0 && (<span className="flex flex-wrap gap-2 text-xs">{jobs.slice(0, 2).map((job) => (@@ -192,7 +272,7 @@ const ProductionPlanningTable = ({{ duration: 8000 });}- }, [bulkUpdateFetcher.data?.success]);+ }, [bulkUpdateFetcher.state, bulkUpdateFetcher.data]);const isDisabled =!permissions.can("create", "production") ||@@ -204,17 +284,22 @@ const ProductionPlanningTable = ({{});- // Computed from the rows, a render behind them so a large plan does not- // block typing; `isPending` covers the gap.- const deferredData = useDeferredValue(data);- const isPending = deferredData !== data;- const ordersByItemId = useMemo(() => {- const orders = new Map<string, ProductionOrder[]>();- for (const item of deferredData) {- orders.set(item.id, getProductionOrdersFromPlanning(item, periods));- }- return orders;- }, [deferredData, periods]);+ // A row's suggested jobs are its open Make actions: what MRP wrote after it+ // moved expedited supply, folded a shortfall into an open job as an+ // Increase, and summed each week. They seed the drawer, size the Make+ // button, and are what a bulk Create Jobs submits for rows never opened.+ const ordersByItemId = useMemo(+ () =>+ new Map(+ data.map((row) => [+ row.id,+ productionOrdersFromActions(+ openNewSupplyActions(actionsByItemId.get(row.id), "Make")+ )+ ])+ ),+ [data, actionsByItemId]+ );// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback(@@ -225,11 +310,16 @@ const ProductionPlanningTable = ({.filter((row) => row.id).map((row) => {// Drawer edits win (even an emptied list); fall back to- // auto-computed orders only for items never opened in the drawer+ // auto-computed orders only for items never opened in the drawer.+ // The fallback stops at the row's time fence: a bulk order raises+ // what is due inside the planning horizon, not the whole window.const sourceOrders =row.id! in ordersMap? ordersMap[row.id!]!- : (ordersByItemId.get(row.id!) ?? []);+ : splitOrdersByFence(+ ordersByItemId.get(row.id!) ?? [],+ timeFence.fenceDateFor(row)+ ).inside;const ordersWithPeriods = sourceOrders.map((order) => {// If no due date or due date is before first period, use first periodif (@@ -271,11 +361,37 @@ const ProductionPlanningTable = ({});},- [bulkUpdateFetcher, locationId, ordersMap, ordersByItemId]+ [bulkUpdateFetcher, locationId, ordersMap, ordersByItemId, timeFence]);- const [selectedItem, setSelectedItem] =- useState<ProductionPlanningItem | null>(null);+ // Moving a row's fence changes which suggested orders its drawer opens on.+ // The drawer's list is kept per item once opened (planner edits win), so a+ // stale list would neither show the newly included orders nor offer them —+ // drop it and let the drawer re-seed from the new split.+ const setFenceDate = timeFence.setFenceDate;+ const onFenceChange = useCallback(+ (itemId: string, date: string | null) => {+ setFenceDate(itemId, date);+ setOrdersMap((prev) => {+ if (!(itemId in prev)) return prev;+ const { [itemId]: _dropped, ...rest } = prev;+ return rest;+ });+ },+ [setFenceDate]+ );++ // The drawer stays mounted, on the last selected part, while it slides out.+ const {+ item: selectedItem,+ isOpen: isDrawerOpen,+ key: drawerKey,+ open: openDrawer,+ close: closeDrawer+ } = useLinkedDrawerItem({+ param: PLANNING_DRAWER_PARAM,+ rows: drawerRows+ });const setOrders = useCallback((item: ProductionPlanningItem, orders: ProductionOrder[]) => {@@ -289,52 +405,57 @@ const ProductionPlanningTable = ({[]);+ // The drawer's own Planning Horizon control: the same on-screen override as+ // the grid cell, for the row the drawer is open on.+ const selectedItemId = selectedItem?.id;+ const onSelectedFenceChange = useCallback(+ (date: string | null) => {+ if (selectedItemId) onFenceChange(selectedItemId, date);+ },+ [selectedItemId, onFenceChange]+ );++ // The drawer's suggested orders, split at the selected row's time fence: it+ // opens on what is due inside the fence and can pull the rest in. A+ // shortfall MRP folded into an Increase on an existing job has no Make+ // action, so it is offered there, in Open Orders, and not here.+ const selectedOrders = useMemo(() => {+ if (!selectedItem?.id) return { inside: [], beyond: [] };+ return splitOrdersByFence(+ ordersByItemId.get(selectedItem.id) ?? [],+ timeFence.fenceDateFor(selectedItem)+ );+ }, [selectedItem, ordersByItemId, timeFence]);++ // The drawer's Open Orders table shows the selected row's change actions on existing+ // jobs (Expedite, Defer, Increase, …). Order / Make actions are left out —+ // each one is already a "New" row in the drawer's order list, right above+ // the table.+ const selectedActions = useMemo(+ () =>+ selectedItem?.id+ ? (fencedActionsByItemId.get(selectedItem.id) ?? []).filter(+ (action) => !isNewSupplyAction(action)+ )+ : [],+ [selectedItem, fencedActionsByItemId]+ );++ // The drawer's Open Orders rows carry the same Apply / Dismiss / Reopen /+ // Assign controls as the expanded row, through the same single fetcher.+// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst columns = useMemo<ColumnDef<ProductionPlanningItem>[]>(() => {- const periodColumns: ColumnDef<ProductionPlanningItem>[] = periods.map(- (period, index) => {- const isCurrentWeek = index === 0;- const weekNumber = index + 1;- const weekKey = `week${weekNumber}` as keyof ProductionPlanningItem;- const startDate = parseDate(period.startDate).toDate(- getLocalTimeZone()- );- const endDate = parseDate(period.endDate).toDate(getLocalTimeZone());-- return {- accessorKey: weekKey,- header: () => (- <VStack spacing={0}>- <div>{isCurrentWeek ? "Present Week" : `Week ${weekNumber}`}</div>- <div className="text-xs text-muted-foreground">- {dateFormatter.format(startDate)} -{" "}- {dateFormatter.format(endDate)}- </div>- </VStack>- ),- cell: ({ row }) => {- const value = row.getValue<number>(weekKey);- if (value === undefined) return "-";- return (- <span- className={value < 0 ? "text-red-500 font-bold" : undefined}- >- {numberFormatter.format(value)}- </span>- );- },- meta: {- filterHeader: isCurrentWeek- ? t`Present Week`- : t`Week ${weekNumber}`,- exportValue: (row: ProductionPlanningItem) => {- const value = row[weekKey] as number | undefined;- return value === undefined ? null : value;- }- }- };- }- );+ const shared = planningColumns<ProductionPlanningItem>({+ i18n,+ periods,+ locationToday,+ formatQuantity,+ unitOfMeasures,+ itemPostingGroups,+ timeFence,+ onFenceChange+ });return [{@@ -343,8 +464,11 @@ const ProductionPlanningTable = ({cell: ({ row }) => (<HStackclassName="py-1 cursor-pointer"- onClick={() => {- setSelectedItem(row.original);+ onClick={(event) => {+ // The row itself toggles its expanded actions on click; this+ // opens the drawer instead, so the click must not reach it.+ event.stopPropagation();+ openDrawer(row.original);}}><ItemThumbnail@@ -372,112 +496,81 @@ const ProductionPlanningTable = ({value: (row) => row.name ?? null}),{- accessorKey: "unitOfMeasureCode",- header: "",+ id: PLANNING_ACTIONS_COLUMN,+ header: t`Actions`,cell: ({ row }) => (- <Enumerable- value={- unitOfMeasures.find(- (uom) => uom.value === row.original.unitOfMeasureCode- )?.label ?? null- }+ <PlanningActionsCell+ actions={visibleActionsByItemId.get(row.original.id) ?? []}/>),meta: {- filterHeader: t`Unit of Measure`,- exportValue: (row: ProductionPlanningItem) =>- unitOfMeasures.find((uom) => uom.value === row.unitOfMeasureCode)- ?.label ?? null- }- },- {- accessorKey: "reorderingPolicy",- header: t`Reorder Policy`,- cell: ({ row }) => {- return (- <HStack>- <Tooltip>- <TooltipTrigger>- <ItemReorderPolicy- reorderingPolicy={row.original.reorderingPolicy}- />- </TooltipTrigger>- <TooltipContent>- {getReorderPolicyDescription(row.original)}- </TooltipContent>- </Tooltip>- </HStack>- );- },- meta: {+ icon: <LuListTodo />,+ pluralHeader: t`Actions`,filter: {type: "static",- options: itemReorderingPolicies.map((policy) => ({- label: <ItemReorderPolicy reorderingPolicy={policy} />,- value: policy- }))+ options: actionTypeOptions},- icon: <LuCircleCheck />- }- },- {- accessorKey: "quantityOnHand",- header: t`On Hand`,- cell: ({ row }) => numberFormatter.format(row.original.quantityOnHand),- meta: {- icon: <LuBlocks />,- renderTotal: true- }- },- ...periodColumns,- {- accessorKey: "quantityToOrder",- header: t`Qty to Order`,- cell: ({ row }) => {- const value = row.original.quantityToOrder;- if (value === undefined || value === 0) return "-";- return (- <span className="font-medium">{numberFormatter.format(value)}</span>- );- },- meta: {- icon: <LuCirclePlay />+ exportValue: (row: ProductionPlanningItem) =>+ planningActionsExportValue(visibleActionsByItemId.get(row.id) ?? [])}},{- accessorKey: "type",- header: t`Type`,- cell: ({ row }) =>- row.original.type && (- <HStack>- <MethodItemTypeIcon type={row.original.type} />- <span>{row.original.type}</span>- </HStack>- ),+ id: PLANNING_ASSIGNEE_COLUMN,+ header: t`Assignee`,+ cell: ({ row }) => (+ <EmployeeAvatarGroup+ employeeIds={[+ ...new Set(+ (visibleActionsByItemId.get(row.original.id) ?? []).flatMap(+ (action) => (action.assignee ? [action.assignee] : [])+ )+ )+ ]}+ />+ ),meta: {+ icon: <LuUserCheck />,+ pluralHeader: t`Assignees`,filter: {type: "static",- options: inventoryItemTypes- .filter((t) => ["Part", "Tool"].includes(t))- .map((type) => ({- label: (- <HStack spacing={2}>- <MethodItemTypeIcon type={type} />- <span>{type}</span>- </HStack>- ),- value: type- }))+ options: people.map((employee) => ({+ value: employee.id,+ label: employee.name+ }))},- icon: <LuBox />+ exportValue: (row: ProductionPlanningItem) =>+ [+ ...new Set(+ (visibleActionsByItemId.get(row.id) ?? []).flatMap((action) =>+ action.assignee ? [action.assignee] : []+ )+ )+ ]+ .map(+ (id) => people.find((person) => person.id === id)?.name ?? id+ )+ .join(", ")}},+ ...shared.periods,+ shared.reorderPolicy,+ shared.unitOfMeasure,+ shared.onHand,+ shared.firstNegativeDate,+ shared.latestOrderDate,+ shared.timeFence,+ shared.type,+ shared.itemGroup,{id: "Order",header: "",cell: ({ row }) => {+ // only what is due inside the row's time fenceconst orders = row.original.id- ? (ordersByItemId.get(row.original.id) ?? [])+ ? splitOrdersByFence(+ ordersByItemId.get(row.original.id) ?? [],+ timeFence.fenceDateFor(row.original)+ ).inside: [];const orderQuantity = orders.reduce((acc, order) =>@@ -486,25 +579,34 @@ const ProductionPlanningTable = ({);const isBlocked = row.original.manufacturingBlocked;const hasOrders = orders.length > 0 && orderQuantity > 0;+ const quantity = formatQuantity(orderQuantity);+ // An open action that adds or advances supply needs doing even with+ // nothing new to order (an Increase on an existing order), so it lights+ // the dot too; a Decrease, Defer or Cancel does not.+ const dot =+ planningActionDot(+ visibleActionsByItemId.get(row.original.id) ?? []+ ) ?? (hasOrders ? "green" : null);return (<div className="flex justify-end"><Buttonvariant="secondary"- leftIcon={hasOrders ? undefined : <LuCircleCheck />}+ leftIcon={dot ? undefined : <LuCircleCheck />}isDisabled={isDisabled || isBlocked}- onClick={() => {- setSelectedItem(row.original);+ onClick={(event) => {+ event.stopPropagation();+ openDrawer(row.original);}}>{isBlocked ? (- "Blocked"- ) : hasOrders ? (+ t`Blocked`+ ) : dot ? (<HStack>- <PulsingDot />- <span>Make {orderQuantity}</span>+ <PulsingDot variant={dot} />+ <span>{hasOrders ? t`Make ${quantity}` : t`Make`}</span></HStack>) : (- "Make"+ t`Make`)}</Button></div>@@ -513,16 +615,30 @@ const ProductionPlanningTable = ({}];}, [- dateFormatter,- numberFormatter,+ t,+ i18n,+ formatQuantity,unitOfMeasures,- isDisabled+ isDisabled,+ visibleActionsByItemId,+ actionTypeOptions,+ people,+ itemPostingGroups,+ ordersByItemId,+ timeFence,+ locationToday// Note: ordersMap is intentionally not in deps to avoid column regeneration// getOrdersForItem inside the cell will access the latest ordersMap via closure]);const renderActions = useCallback((selectedRows: typeof data) => {+ // inside each row's time fence only — what the row is showing+ const applyableIds = selectedRows.flatMap((row) =>+ (visibleActionsByItemId.get(row.id) ?? [])+ .filter(isApplyablePlanningAction)+ .map((action) => action.id)+ );return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>@@ -537,13 +653,59 @@ const ProductionPlanningTable = ({<DropdownMenuIcon icon={<LuSquareChartGantt />} /><Trans>Create Jobs</Trans></DropdownMenuItem>+ <DropdownMenuItem+ disabled={+ !canUpdateActions || applyableIds.length === 0 || isActionsBusy+ }+ onSelect={() =>+ submitActions({+ action: "apply",+ planningActionIds: applyableIds+ })+ }+ >+ <DropdownMenuIcon icon={<LuListTodo />} />+ <Trans>Apply Suggested Changes</Trans>+ {applyableIds.length > 0 && (+ <span className="ml-auto pl-3 text-xs text-muted-foreground tabular-nums">+ {applyableIds.length}+ </span>+ )}+ </DropdownMenuItem></DropdownMenuContent>);},- [bulkUpdateFetcher.state, onBulkUpdate]+ [+ bulkUpdateFetcher.state,+ onBulkUpdate,+ visibleActionsByItemId,+ canUpdateActions,+ isActionsBusy,+ submitActions+ ]+ );++ const canExpandRow = useCallback(+ (row: ProductionPlanningItem) =>+ (visibleActionsByItemId.get(row.id)?.length ?? 0) > 0,+ [visibleActionsByItemId]+ );++ const renderExpandedRow = useCallback(+ (row: ProductionPlanningItem) => (+ <PlanningActionLines+ actions={visibleActionsByItemId.get(row.id) ?? []}+ todayIso={locationToday}+ {...actionHandlers}+ onOrder={() => openDrawer(row)}+ />+ ),+ [visibleActionsByItemId, locationToday, actionHandlers, openDrawer]);const defaultColumnVisibility = {+ // carries the Assignee filter; the avatars are opt-in+ [PLANNING_ASSIGNEE_COLUMN]: false,type: false};@@ -553,7 +715,7 @@ const ProductionPlanningTable = ({};return (- <Loading isLoading={isPending}>+ <><Table<ProductionPlanningItem>count={count}columns={columns}@@ -585,17 +747,15 @@ const ProductionPlanningTable = ({<Trans>Recalculate</Trans></Button></TooltipTrigger>- <TooltipContent>- <Trans>- MRP runs automatically every 3 hours, but you can run it- manually here.- </Trans>- </TooltipContent>+ <TooltipContent>{mrpScheduleDescription}</TooltipContent></Tooltip></mrpFetcher.Form></div>}renderActions={renderActions}+ renderExpandedRow={renderExpandedRow}+ pinExpandedRows+ canExpandRow={canExpandRow}title={t`Material Planning`}table="production-planning"withSavedView@@ -604,21 +764,28 @@ const ProductionPlanningTable = ({{selectedItem && (<ProductionPlanningOrderDrawer+ key={drawerKey}+ locationToday={locationToday}locationId={locationId}row={selectedItem}orders={selectedItem.id- ? ordersMap[selectedItem.id] ||- getProductionOrdersFromPlanning(selectedItem, periods)+ ? ordersMap[selectedItem.id] || selectedOrders.inside: []}+ beyondFenceOrders={selectedOrders.beyond}+ timeFenceDate={timeFence.fenceDateFor(selectedItem)}+ isTimeFenceOverridden={timeFence.isOverridden(selectedItem)}+ onTimeFenceChange={onSelectedFenceChange}+ actions={selectedActions}+ actionHandlers={actionHandlers}setOrders={setOrders}periods={periods}- isOpen={!!selectedItem}- onClose={() => setSelectedItem(null)}+ isOpen={isDrawerOpen}+ onClose={closeDrawer}/>)}- </Loading>+ </>);};diff --git a/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.ts b/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.tsnew file mode 100644index 0000000000..cf61e75aba--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planned-orders-from-actions.ts@@ -0,0 +1,138 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Pure helpers that turn the persisted MRP worklist into the order drawer's+// suggested orders. No JSX, no lingui — unit-tested by+// apps/erp/test/planned-orders-from-actions.test.ts.+//+// The planning action is the source of truth for a suggestion (spec §P1.8).+// The drawer and the grid's Order / Make button used to size orders again in+// the browser from the weekly projections, and missed what MRP does after+// sizing: it moves expedited supply, folds a shortfall into an open order as+// an Increase, and sums each week into one action. The two lists then+// disagreed, and ordering from the drawer bought the Increase's quantity a+// second time.++import type { Database, Json } from "@carbon/database";+import { RoundingMode, round } from "@carbon/utils";+import { z } from "zod";+import type { ProductionOrder } from "~/modules/production/production.models";+import type { PlannedOrder } from "~/modules/purchasing/purchasing.models";++type NewSupplyActionFields = {+ type: Database["public"]["Enums"]["planningActionType"];+ status: Database["public"]["Enums"]["planningActionStatus"];+ purchaseOrderLineId: string | null;+ jobId: string | null;+ periodId: string;+ suggestedQuantity: number;+ suggestedDate: string;+ latestOrderDate: string | null;+ isASAP: boolean;+ supplierId: string | null;+ policyName: string | null;+ reason: string | null;+ triggerValues: Json | null;+};++/**+ * The item's open suggestions for NEW supply of one kind: an Order (buy) or a+ * Make (job) with no order or job behind it. A dismissed suggestion is the+ * planner's "no", so it never seeds the drawer.+ */+export function openNewSupplyActions<A extends NewSupplyActionFields>(+ actions: A[] | undefined,+ type: "Order" | "Make"+): A[] {+ return (actions ?? []).filter(+ (action) =>+ action.type === type &&+ action.status === "Open" &&+ !action.purchaseOrderLineId &&+ !action.jobId+ );+}++/** One job suggestion per open Make action, in the item's own units. */+export function productionOrdersFromActions(+ actions: NewSupplyActionFields[]+): ProductionOrder[] {+ return actions.map((action) => ({+ startDate: action.latestOrderDate ?? action.suggestedDate,+ dueDate: action.suggestedDate,+ periodId: action.periodId,+ quantity: Number(action.suggestedQuantity),+ isASAP: action.isASAP+ }));+}++/**+ * One purchase suggestion per open Order action. The action's quantity is in+ * inventory units; the order is in the supplier's purchase units, rounded up+ * to a whole unit.+ */+export function plannedOrdersFromActions(+ actions: NewSupplyActionFields[],+ context: {+ /** Inventory units in one purchase unit, from the chosen supplier part. */+ conversionFactor: number;+ /** The supplier chosen for the row; the action's own supplier otherwise. */+ supplierId?: string | null;+ itemReadableId?: string;+ description?: string;+ unitOfMeasureCode?: string;+ }+): PlannedOrder[] {+ const { conversionFactor } = context;+ return actions.map((action) => {+ const quantity = Number(action.suggestedQuantity);+ return {+ startDate: action.latestOrderDate ?? action.suggestedDate,+ dueDate: action.suggestedDate,+ periodId: action.periodId,+ quantity:+ conversionFactor > 0+ ? round(quantity / conversionFactor, 0, RoundingMode.Up)+ : quantity,+ supplierId: context.supplierId ?? action.supplierId ?? undefined,+ itemReadableId: context.itemReadableId,+ description: context.description,+ unitOfMeasureCode: context.unitOfMeasureCode,+ policyName: action.policyName ?? undefined,+ reason: action.reason ?? undefined,+ triggerValues: triggerValuesOf(action.triggerValues)+ };+ });+}++/** MRP writes the policy's trigger values as a flat object of numbers. */+function triggerValuesOf(value: Json | null): PlannedOrder["triggerValues"] {+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ return undefined;+ }+ const numbers: Record<string, number> = {};+ for (const [key, entry] of Object.entries(value)) {+ if (typeof entry === "number") numbers[key] = entry;+ }+ return numbers;+}++const supplierPartsValidator = z.array(+ z.object({ supplierId: z.string(), conversionFactor: z.number() })+);++/**+ * Inventory units in one purchase unit for the chosen supplier, read from the+ * planning row's supplier parts; 1 when the supplier has no part for the item.+ */+export function supplierConversionFactor(+ suppliers: unknown,+ supplierId: string | null | undefined+): number {+ const parts = supplierPartsValidator.safeParse(suppliers);+ return (+ parts.data?.find((part) => part.supplierId === supplierId)+ ?.conversionFactor ?? 1+ );+}diff --git a/apps/erp/app/modules/production/ui/Planning/planning-action-scope.ts b/apps/erp/app/modules/production/ui/Planning/planning-action-scope.tsnew file mode 100644index 0000000000..04f453dc88--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planning-action-scope.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+// Pure helpers for the planning grid's Actions and Assignee filters.+// No JSX, no lingui — unit-tested by apps/erp/test/planning-action-scope.test.ts.++/** Column id of the planning grid's Actions column — also the `filter=` key+ * its static type filter writes (`planningActions:eq:Expedite`, or `:in:` for+ * several). It is not a column of the grid RPC: the loader strips it with+ * `resolvePlanningActionScope` and hands it to the RPC as an argument, which+ * evaluates it in the database against each item's planning horizon. */+export const PLANNING_ACTIONS_COLUMN = "planningActions";+/** Column id of the grid's Assignee column, and the `filter=` key of its+ * people filter (`planningAssignee:in:<userId>,<userId>`). Like the Actions+ * filter it is not an RPC column: the loader turns it into the RPC's+ * assignees argument. */+export const PLANNING_ASSIGNEE_COLUMN = "planningAssignee";+/** Search param that carries the item whose order drawer is open+ * (`?item=<itemId>`), so a link to the grid opens the same drawer. */+export const PLANNING_DRAWER_PARAM = "item";++type GridFilter = { column: string; operator: string; value?: string };++/**+ * Splits the grid's URL filters into the ones the planning RPC can apply as+ * column filters and the Actions / Assignee filters, which become RPC+ * ARGUMENTS: the grid keeps the items with at least one OPEN action, inside the+ * item's planning horizon, that matches every requested predicate on the SAME+ * action (one of the types AND assigned to one of the people). `undefined` means "no restriction of that kind".+ *+ * The RPC does the matching (not this function, and not an item-id list) so the+ * filter is complete at any volume and sees the horizon: an earlier version+ * resolved item ids from the first 500 loaded actions and silently dropped+ * items beyond that.+ */+export function resolvePlanningActionScope(args: { filters?: GridFilter[] }): {+ gridFilters: GridFilter[];+ actionTypes: string[] | undefined;+ actionAssignees: string[] | undefined;+} {+ const all = args.filters ?? [];+ const valuesOf = (column: string) => [+ ...new Set(+ all+ .filter((f) => f.column === column)+ .flatMap((f) => (f.value ?? "").split(",").filter(Boolean))+ )+ ];+ const types = valuesOf(PLANNING_ACTIONS_COLUMN);+ const assignees = valuesOf(PLANNING_ASSIGNEE_COLUMN);++ return {+ gridFilters: all.filter(+ (f) =>+ f.column !== PLANNING_ACTIONS_COLUMN &&+ f.column !== PLANNING_ASSIGNEE_COLUMN+ ),+ actionTypes: types.length > 0 ? types : undefined,+ actionAssignees: assignees.length > 0 ? assignees : undefined+ };+}++/**+ * The actions a row SHOWS under the Actions-column filter: only the filtered+ * types. The RPC keeps an item when it has one matching action, but the item+ * usually carries others too — a grid filtered to Expedite that still listed+ * each row's Defer and Cancel read as an unfiltered grid. No types (no filter)+ * shows everything.+ */+export function actionsOfTypes<+ A extends { type: Database["public"]["Enums"]["planningActionType"] }+>(actions: readonly A[], types: readonly string[] | null | undefined): A[] {+ if (!types || types.length === 0) return [...actions];+ return actions.filter((action) => types.includes(action.type));+}diff --git a/apps/erp/app/modules/production/ui/Planning/planning-fence.ts b/apps/erp/app/modules/production/ui/Planning/planning-fence.tsnew file mode 100644index 0000000000..f93dde5601--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planning-fence.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Pure helpers for the planning horizon (time fence). No JSX, no lingui —+// unit-tested by apps/erp/test/planning-fence.test.ts.+//+// MRP generates actions and suggested orders over the whole planning window.+// The fence is a READ-TIME lens: a row surfaces only what falls on or before+// its fence date (today + the item's planning horizon). `null` is "no fence".+//+// The grid RPC applies the SAME comparison in SQL for the Actions filter+// (`a."horizonDate" <= as_of + days`), using the saved horizon. These helpers+// apply it on screen, where a planner may have widened one row's fence without+// saving — so keep the two in step: one inclusive `<=` on ISO dates.++/** ISO `YYYY-MM-DD` strings order chronologically, so `<=` is a date compare. */+export function isInsideFence(+ date: string | null | undefined,+ fenceDate: string | null+): boolean {+ if (!fenceDate) return true;+ // an undated suggestion cannot be placed outside a fence — keep it visible+ if (!date) return true;+ return date <= fenceDate;+}++/**+ * The row's effective fence: the planner's on-screen override when there is+ * one, else the saved horizon the RPC resolved (`timeFenceDate`), else none.+ * An override of `null` is a cleared fence — no fence for this view — and+ * `undefined` is no override at all.+ */+export function effectiveFenceDate(+ savedFenceDate: string | null | undefined,+ override: string | null | undefined+): string | null {+ return override !== undefined ? override : (savedFenceDate ?? null);+}++/** The actions a row surfaces under its fence (open and dismissed alike). */+export function actionsInsideFence<A extends { horizonDate: string }>(+ actions: A[],+ fenceDate: string | null+): A[] {+ if (!fenceDate) return actions;+ return actions.filter((action) =>+ isInsideFence(action.horizonDate, fenceDate)+ );+}++/**+ * Suggested new orders split at the fence by the date they are REQUIRED:+ * `inside` is what the grid offers to order, `beyond` is what a planner can+ * still pull in from the order drawer.+ */+export function splitOrdersByFence<O extends { dueDate?: string | null }>(+ orders: O[],+ fenceDate: string | null+): { inside: O[]; beyond: O[] } {+ if (!fenceDate) return { inside: orders, beyond: [] };+ const inside: O[] = [];+ const beyond: O[] = [];+ for (const order of orders) {+ if (isInsideFence(order.dueDate, fenceDate)) inside.push(order);+ else beyond.push(order);+ }+ return { inside, beyond };+}diff --git a/apps/erp/app/modules/production/ui/Planning/planning-increase.ts b/apps/erp/app/modules/production/ui/Planning/planning-increase.tsnew file mode 100644index 0000000000..ca5cebfd40--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planning-increase.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Pure helper for the Increase actions MRP folds new supply into.+// No JSX, no lingui — unit-tested by apps/erp/test/planning-increase.test.ts.+//+// When an open order lands in the same window as a new-supply suggestion, MRP+// folds the suggestion INTO that order: one Increase replaces the Order / Make+// (`convertOrdersToIncreases`, @carbon/planning). The drawer's suggested+// orders come from the Order / Make actions, so the folded one is not among+// them; the chart still has to count the Increase on the existing order.++type IncreaseLike = {+ type: string;+ status: string;+ periodId: string;+};++function isOpenIncrease(action: IncreaseLike) {+ return action.type === "Increase" && action.status === "Open";+}++/**+ * The quantity the drawer's chart draws an existing order at, in inventory+ * units. An open Increase on it stands in for the new order it replaced, so+ * "if ordered" counts it — unless the planner has changed the order's+ * quantity in the drawer since it loaded, which is their answer to it.+ */+export function chartedOrderQuantity(args: {+ quantity: number;+ loadedQuantity: number;+ increase: (IncreaseLike & { suggestedQuantity: number | string }) | null;+}): number {+ const { quantity, loadedQuantity, increase } = args;+ if (!increase || !isOpenIncrease(increase) || quantity !== loadedQuantity) {+ return quantity;+ }+ return Math.max(quantity, Number(increase.suggestedQuantity) || 0);+}diff --git a/apps/erp/app/modules/production/ui/Planning/planning-review.ts b/apps/erp/app/modules/production/ui/Planning/planning-review.tsnew file mode 100644index 0000000000..6733094ef9--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planning-review.ts@@ -0,0 +1,168 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Pure helpers: whether a planning action can be applied from the page or must+// be reviewed on its order, and what the order's own menu offers. No JSX, no+// lingui — unit-tested by apps/erp/test/planning-review.test.ts.+//+// MRP stamps `requiresManualAction` as of its run. Read on its own, a PO+// reopened since stayed on "Review" until the next run, though Apply (which+// re-reads the order) would already go through. The live status decides+// instead; the stamp is only the fallback when the order was not read.++import type { Database } from "@carbon/database";+import { isJobEditableFromPlanning } from "~/modules/production/production.models";+import {+ canCreatePurchaseOrderRevision,+ isPurchaseOrderEditableFromPlanning+} from "~/modules/purchasing/purchasing.models";++type PurchaseOrderStatus = Database["public"]["Enums"]["purchaseOrderStatus"];++const DATE_ACTION_TYPES: ReadonlySet<string> = new Set(["Expedite", "Defer"]);++export type ReviewableAction = {+ type: string;+ requiresManualAction: boolean;+ purchaseOrderLineId: string | null;+ purchaseOrderStatus: PurchaseOrderStatus | null;+ /** The line's promised date, else its delivery's: the supplier's promise. */+ purchaseOrderLinePromisedDate: string | null;+ jobId: string | null;+ jobStatus: Database["public"]["Enums"]["jobStatus"] | null;+};++/**+ * Review rather than Apply: the order is past what planning may change (a PO+ * in approval or sent, a released job), or a date move would have to change a+ * supplier's promised date — Apply writes the required date, which a promise+ * outranks. The same rules the planning.update routes apply.+ */+export function planningActionNeedsReview(action: ReviewableAction): boolean {+ if (action.purchaseOrderLineId) {+ if (!action.purchaseOrderStatus) return action.requiresManualAction;+ if (!isPurchaseOrderEditableFromPlanning(action.purchaseOrderStatus)) {+ return true;+ }+ return (+ DATE_ACTION_TYPES.has(action.type) &&+ Boolean(action.purchaseOrderLinePromisedDate)+ );+ }+ if (action.jobId) {+ if (!action.jobStatus) return action.requiresManualAction;+ return !isJobEditableFromPlanning(action.jobStatus);+ }+ return action.requiresManualAction;+}++/**+ * The action types that can be LATE: each one adds supply or brings it+ * forward, so missing its date leaves stock short. A Decrease, Defer or+ * Cancel takes away supply nothing needs — its date is only where the order+ * sits now, and waiting costs nothing but excess — so it is never urgent,+ * whatever its date or flag.+ */+const URGENCY_TYPES: ReadonlySet<string> = new Set([+ "Order",+ "Make",+ "Expedite",+ "Increase"+]);++/** Late: an urgent type whose date has passed, or that MRP flagged ASAP.+ * A Release is late once its release day has passed — on the day itself it+ * is due, not late. */+export function isPlanningActionLate(+ action: {+ type: string;+ status: string;+ isASAP: boolean;+ suggestedDate: string;+ },+ todayIso: string+): boolean {+ if (action.status !== "Open") return false;+ if (action.type === "Release") return action.suggestedDate < todayIso;+ if (!URGENCY_TYPES.has(action.type)) return false;+ return action.isASAP || action.suggestedDate < todayIso;+}++/** The dot on a row's Order / Make button. It asks for MORE or EARLIER+ * supply, so only an open action that adds or advances it lights it — an+ * Increase on an existing order counts even with nothing new to order: red+ * when one is ASAP, green otherwise. A Release lights it red once its day+ * has come (MRP flags it ASAP then) and not before — every planned order+ * has one, so a green dot for each would say nothing. A Decrease, Defer or+ * Cancel never lights it; they stay in the Actions column and the expanded+ * row. Null when nothing does. */+export function planningActionDot(+ actions: { type: string; status: string; isASAP: boolean }[]+): "red" | "green" | null {+ const open = actions.filter((a) => a.status === "Open");+ if (open.some((a) => a.type === "Release" && a.isASAP)) return "red";+ const supply = open.filter((a) => URGENCY_TYPES.has(a.type));+ if (supply.length === 0) return null;+ return supply.some((a) => a.isASAP) ? "red" : "green";+}++/**+ * A Release whose order is no longer Planned (sent, in approval, released to+ * the floor) since MRP ran: it no longer applies, and the planning pages drop+ * it until the next run deletes it. Unknown status keeps it.+ */+export function isStaleRelease(action: {+ type: string;+ purchaseOrderLineId: string | null;+ purchaseOrderStatus: PurchaseOrderStatus | null;+ jobId: string | null;+ jobStatus: Database["public"]["Enums"]["jobStatus"] | null;+}): boolean {+ if (action.type !== "Release") return false;+ if (action.purchaseOrderLineId) {+ return (+ action.purchaseOrderStatus !== null &&+ action.purchaseOrderStatus !== "Planned"+ );+ }+ if (action.jobId) {+ return action.jobStatus !== null && action.jobStatus !== "Planned";+ }+ return false;+}++export type PlanningPurchaseOrder = {+ id: string;+ /** The PO number, for confirmations. */+ readableId?: string | null;+ status: PurchaseOrderStatus | null;+ /** Set at finalize: the PO reached the supplier. */+ orderDate: string | null;+};++/**+ * What a purchase order's menu offers on the planning pages. A PO planning+ * cannot change can be reopened — to Planned, so it stays MRP supply — and a+ * released one reopened as its next revision; a Draft or Planned PO can be+ * finalized. The status route holds the permissions and the approval rules.+ */+export function purchaseOrderPlanningMenu(order: PlanningPurchaseOrder): {+ canReopen: boolean;+ canReopenAsRevision: boolean;+ canFinalize: boolean;+} {+ if (!order.status) {+ return { canReopen: false, canReopenAsRevision: false, canFinalize: false };+ }+ const isEditable = isPurchaseOrderEditableFromPlanning(order.status);+ return {+ canReopen: !isEditable,+ canReopenAsRevision: canCreatePurchaseOrderRevision({+ newStatus: "Planned",+ currentStatus: order.status,+ orderDate: order.orderDate+ }),+ canFinalize: isEditable+ };+}diff --git a/apps/erp/app/modules/production/ui/Planning/planning-week-geometry.ts b/apps/erp/app/modules/production/ui/Planning/planning-week-geometry.tsnew file mode 100644index 0000000000..527408c0bb--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planning-week-geometry.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Pure geometry for the planning grid's Stock Availability strip. No JSX, no+// lingui — unit-tested by apps/erp/test/planning-week-geometry.test.ts.++/**+ * Where the zero line sits and how tall each week's bar is, as PERCENTAGES of+ * the strip's height. The row is scaled to its own range — the largest stock+ * above zero plus the deepest shortfall below it — so the shape reads at any+ * magnitude: a part holding 20,000 and a part holding 12 both fill the strip.+ * Magnitudes are therefore comparable along a row, not between rows; the+ * tooltip and the CSV carry the numbers.+ */+export function planningWeekGeometry(values: (number | undefined)[]): {+ /** Distance of the zero line from the TOP of the strip, 0–100. */+ zero: number;+ /** Bar height per week, 0–100; 0 for a zero or missing value. */+ heights: number[];+} {+ let above = 0;+ let below = 0;+ for (const value of values) {+ if (value === undefined) continue;+ if (value > above) above = value;+ if (-value > below) below = -value;+ }+ const range = above + below;+ // nothing but zeros (or nothing at all): a flat line through the middle+ if (range === 0) return { zero: 50, heights: values.map(() => 0) };++ return {+ zero: (above / range) * 100,+ heights: values.map((value) =>+ value === undefined ? 0 : (Math.abs(value) / range) * 100+ )+ };+}diff --git a/apps/erp/app/modules/production/ui/Planning/planningColumns.tsx b/apps/erp/app/modules/production/ui/Planning/planningColumns.tsxnew file mode 100644index 0000000000..d6d9d21847--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/planningColumns.tsx@@ -0,0 +1,301 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Badge,+ HStack,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@carbon/react";+import type { I18n } from "@lingui/core";+import { msg } from "@lingui/core/macro";+import type { ColumnDef } from "@tanstack/react-table";+import {+ LuBlocks,+ LuBox,+ LuCalendarClock,+ LuCalendarRange,+ LuChartNoAxesColumn,+ LuCircleCheck,+ LuGroup,+ LuTrendingDown+} from "react-icons/lu";+import { exportOnlyColumn, MethodItemTypeIcon } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { inventoryItemTypes } from "~/modules/inventory/inventory.models";+import { itemReorderingPolicies } from "~/modules/items/items.models";+import {+ getReorderPolicyDescription,+ ItemReorderPolicy+} from "~/modules/items/ui/Item/ItemReorderPolicy";+import type { ProductionPlanningItem } from "~/modules/production";+import {+ LatestOrderDateCell,+ latestOrderDateExportValue+} from "~/modules/production/ui/Planning/LatestOrderDate";+import {+ FirstNegativeDateCell,+ TimeFenceCell,+ type useTimeFenceOverrides+} from "~/modules/production/ui/Planning/PlanningFence";+import {+ PlanningWeekStrip,+ planningWeekStripSize,+ planningWeekValues+} from "~/modules/production/ui/Planning/PlanningWeekStrip";+import type { PurchasingPlanningItem } from "~/modules/purchasing";++// Labels as descriptors: this factory is not a component, so it cannot use+// `useLingui`'s `t`; the grid's `i18n` renders them.+const LABELS = {+ stockAvailability: msg`Stock Availability`,+ presentWeek: msg`Present Week`,+ unitOfMeasure: msg`Unit of Measure`,+ itemGroup: msg`Item Group`,+ reorderPolicy: msg`Reorder Policy`,+ onHand: msg`On Hand`,+ firstNegativeDate: msg`1st Negative On Hand`,+ latestOrderDate: msg`Latest Order Date`,+ timeFence: msg`Planning Horizon`,+ type: msg`Type`+};++const weekLabel = (weekNumber: number) => msg`Week ${weekNumber}`;++type PlanningRow = ProductionPlanningItem | PurchasingPlanningItem;+type Option = { value: string; label: string };++/**+ * The columns the production and purchasing planning grids share, built once.+ * Each grid keeps its own order and its own columns (item link, supplier,+ * lead time, quantity to order, the Order button) around these. They were two+ * copies that differed only in the row type.+ *+ * `accessorKey` is typed against the union of the two row types, which the+ * grid's own row type narrows; the cast at the end is that narrowing.+ *+ * Labels come from `LABELS` and render through the grid's `i18n`.+ */+export function planningColumns<T extends PlanningRow>(ctx: {+ i18n: I18n;+ periods: { id: string; startDate: string; endDate: string }[];+ locationToday: string;+ formatQuantity: (quantity: number) => string;+ unitOfMeasures: Option[];+ itemPostingGroups: Option[];+ timeFence: ReturnType<typeof useTimeFenceOverrides>;+ onFenceChange: (itemId: string, date: string | null) => void;+}) {+ const {+ i18n,+ periods,+ locationToday,+ formatQuantity,+ unitOfMeasures,+ itemPostingGroups,+ timeFence,+ onFenceChange+ } = ctx;++ const columns = {+ // The grid shows every week as one bar in a strip; the CSV keeps a column+ // per week so an export still carries the numbers.+ periods: [+ {+ id: "stockAvailability",+ header: i18n._(LABELS.stockAvailability),+ cell: ({ row }) => (+ <PlanningWeekStrip+ periods={periods}+ values={planningWeekValues(row.original, periods)}+ />+ ),+ size: planningWeekStripSize(periods.length),+ meta: {+ icon: <LuChartNoAxesColumn />+ }+ },+ ...periods.map((_, index) => {+ const weekNumber = index + 1;+ const weekKey = `week${weekNumber}` as keyof PlanningRow;+ return exportOnlyColumn<PlanningRow>({+ id: weekKey,+ header:+ index === 0+ ? i18n._(LABELS.presentWeek)+ : i18n._(weekLabel(weekNumber)),+ value: (row) => {+ const value = row[weekKey] as number | undefined;+ return value === undefined ? null : value;+ }+ });+ })+ ] as ColumnDef<PlanningRow>[],+ unitOfMeasure: {+ accessorKey: "unitOfMeasureCode",+ header: "",+ cell: ({ row }) => (+ <Enumerable+ value={+ unitOfMeasures.find(+ (uom) => uom.value === row.original.unitOfMeasureCode+ )?.label ?? null+ }+ />+ ),+ meta: {+ filterHeader: i18n._(LABELS.unitOfMeasure),+ exportValue: (row: PlanningRow) =>+ unitOfMeasures.find((uom) => uom.value === row.unitOfMeasureCode)+ ?.label ?? null+ }+ } as ColumnDef<PlanningRow>,+ itemGroup: {+ accessorKey: "itemPostingGroupId",+ header: i18n._(LABELS.itemGroup),+ cell: ({ row }) => {+ const label = itemPostingGroups.find(+ (group) => group.value === row.original.itemPostingGroupId+ )?.label;+ return label ? <Badge variant="secondary">{label}</Badge> : null;+ },+ meta: {+ filter: {+ type: "static",+ options: itemPostingGroups.map((group) => ({+ value: group.value,+ label: <Badge variant="secondary">{group.label}</Badge>+ }))+ },+ icon: <LuGroup />,+ exportValue: (row: PlanningRow) =>+ itemPostingGroups.find(+ (group) => group.value === row.itemPostingGroupId+ )?.label ?? null+ }+ } as ColumnDef<PlanningRow>,+ reorderPolicy: {+ accessorKey: "reorderingPolicy",+ header: i18n._(LABELS.reorderPolicy),+ cell: ({ row }) => (+ <HStack>+ <Tooltip>+ <TooltipTrigger>+ <ItemReorderPolicy+ reorderingPolicy={row.original.reorderingPolicy}+ />+ </TooltipTrigger>+ <TooltipContent>+ {getReorderPolicyDescription(row.original)}+ </TooltipContent>+ </Tooltip>+ </HStack>+ ),+ meta: {+ filter: {+ type: "static",+ options: itemReorderingPolicies.map((policy) => ({+ label: <ItemReorderPolicy reorderingPolicy={policy} />,+ value: policy+ }))+ },+ icon: <LuCircleCheck />+ }+ } as ColumnDef<PlanningRow>,+ onHand: {+ accessorKey: "quantityOnHand",+ header: i18n._(LABELS.onHand),+ cell: ({ row }) => formatQuantity(row.original.quantityOnHand),+ meta: {+ icon: <LuBlocks />,+ renderTotal: true+ }+ } as ColumnDef<PlanningRow>,+ firstNegativeDate: {+ accessorKey: "firstNegativeDate",+ header: i18n._(LABELS.firstNegativeDate),+ cell: ({ row }) => (+ <FirstNegativeDateCell+ date={row.original.firstNegativeDate}+ todayIso={locationToday}+ />+ ),+ meta: {+ icon: <LuTrendingDown />+ }+ } as ColumnDef<PlanningRow>,+ latestOrderDate: {+ // The order-by date MRP stored on the item's open new-supply actions —+ // the same actions the order drawer lists — so cell, sort and drawer+ // agree.+ accessorKey: "latestOrderDate",+ header: i18n._(LABELS.latestOrderDate),+ cell: ({ row }) => (+ <LatestOrderDateCell+ itemPlanning={row.original}+ todayIso={locationToday}+ />+ ),+ meta: {+ icon: <LuCalendarClock />,+ exportValue: latestOrderDateExportValue+ }+ } as ColumnDef<PlanningRow>,+ timeFence: {+ accessorKey: "timeFenceDate",+ header: i18n._(LABELS.timeFence),+ cell: ({ row }) => (+ // The row toggles its expanded actions on click. React events bubble+ // through the calendar's portal, so every click in the picker would+ // reach the row without this.+ <div onClick={(event) => event.stopPropagation()}>+ <TimeFenceCell+ fenceDate={timeFence.fenceDateFor(row.original)}+ isOverridden={timeFence.isOverridden(row.original)}+ onChange={(date) => onFenceChange(row.original.id, date)}+ />+ </div>+ ),+ meta: {+ icon: <LuCalendarRange />,+ exportValue: (row: PlanningRow) => timeFence.fenceDateFor(row)+ }+ } as ColumnDef<PlanningRow>,+ type: {+ accessorKey: "type",+ header: i18n._(LABELS.type),+ cell: ({ row }) =>+ row.original.type && (+ <HStack>+ <MethodItemTypeIcon type={row.original.type} />+ <span>{row.original.type}</span>+ </HStack>+ ),+ meta: {+ filter: {+ type: "static",+ options: inventoryItemTypes+ .filter((type) => ["Part", "Tool"].includes(type))+ .map((type) => ({+ label: (+ <HStack spacing={2}>+ <MethodItemTypeIcon type={type} />+ <span>{type}</span>+ </HStack>+ ),+ value: type+ }))+ },+ icon: <LuBox />+ }+ } as ColumnDef<PlanningRow>+ };++ return columns as unknown as {+ [K in keyof typeof columns]: (typeof columns)[K] extends unknown[]+ ? ColumnDef<T>[]+ : ColumnDef<T>;+ };+}diff --git a/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.ts b/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.tsnew file mode 100644index 0000000000..ed3fbaa09c--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useAction } from "@carbon/query";+import { toast } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import { useCallback } from "react";+import type { PlanningAction } from "~/modules/production";+import type { action as releaseAction } from "~/routes/x+/job+/release";+import { path } from "~/utils/path";++/**+ * A job's Release action, released from the planning page through the jobs+ * table's release route: the job page's checks (operations, blocked+ * manufacturing, outside-operation suppliers), the release itself, and the+ * location's schedule run. A job that fails a check is named with its reason.+ * Once released the job is no longer Planned, so its Release drops out when+ * the page reloads (`isStaleRelease`).+ */+export function useJobPlanningRelease(): {+ onRelease: (action: PlanningAction) => void;+ isReleasing: boolean;+} {+ const { t } = useLingui();+ const releaseFetcher = useAction<typeof releaseAction>({+ onSuccess: (result) => {+ if (!result.success) return;+ if (result.released) toast.success(t`Job released`);+ for (const warning of result.warnings) {+ toast.error(+ t`${warning.readableId} was released with a problem: ${warning.message}`+ );+ }+ for (const failure of result.failed) {+ toast.error(+ t`Could not release ${failure.readableId}: ${failure.message}`+ );+ }+ if (!result.scheduled) {+ toast.error(t`The schedule could not be updated after the release`);+ }+ },+ onError: (result) => {+ if (!result.success) toast.error(result.message);+ }+ });++ const submit = releaseFetcher.submit;+ const onRelease = useCallback(+ (action: PlanningAction) => {+ if (!action.jobId) return;+ submit(+ { jobIds: [action.jobId] },+ {+ method: "post",+ action: path.to.bulkReleaseJob,+ encType: "application/json"+ }+ );+ },+ [submit]+ );++ return { onRelease, isReleasing: releaseFetcher.isPending };+}diff --git a/apps/erp/app/modules/production/ui/Planning/usePlanningActions.ts b/apps/erp/app/modules/production/ui/Planning/usePlanningActions.tsnew file mode 100644index 0000000000..9677556856--- /dev/null+++ b/apps/erp/app/modules/production/ui/Planning/usePlanningActions.ts@@ -0,0 +1,144 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { toast } from "@carbon/react";+import { useCallback, useEffect, useMemo } from "react";+import { useFetcher } from "react-router";+import type { PlanningAction } from "~/modules/production";+import { actionsOfTypes } from "~/modules/production";+import {+ type FenceRow,+ useTimeFenceOverrides+} from "~/modules/production/ui/Planning/PlanningFence";+import { actionsInsideFence } from "~/modules/production/ui/Planning/planning-fence";+import { isStaleRelease } from "~/modules/production/ui/Planning/planning-review";++/**+ * The planning grids' MRP worklist state, shared by the production and+ * purchasing tables: the submit fetcher and its toast, each row's actions+ * inside its time fence, and the ones the Actions-column filter shows.+ */+export function usePlanningActions({+ data,+ planningActions,+ actionTypes,+ locationId,+ updatePath,+ currentUserId,+ canUpdate+}: {+ data: FenceRow[];+ planningActions: PlanningAction[];+ /** The Actions-column filter; null shows every type. */+ actionTypes: string[] | null;+ locationId: string;+ /** The planning route's update action (`planning.update`). */+ updatePath: string;+ currentUserId: string;+ canUpdate: boolean;+}) {+ const actionsFetcher = useFetcher<{ success?: boolean; message?: string }>();+ const isActionsBusy = actionsFetcher.state !== "idle";++ useEffect(() => {+ if (actionsFetcher.state !== "idle" || !actionsFetcher.data?.message)+ return;+ if (actionsFetcher.data.success) {+ toast.success(actionsFetcher.data.message);+ } else {+ toast.error(actionsFetcher.data.message);+ }+ }, [actionsFetcher.state, actionsFetcher.data]);++ const actionsByItemId = useMemo(() => {+ const map = new Map<string, PlanningAction[]>();+ for (const action of planningActions) {+ // a Release whose order moved on since MRP ran no longer applies+ if (isStaleRelease(action)) continue;+ const list = map.get(action.itemId);+ if (list) list.push(action);+ else map.set(action.itemId, [action]);+ }+ return map;+ }, [planningActions]);++ // A row surfaces only what falls on or before its fence date (today + the+ // item's planning horizon). Moving a row's fence here is page state: it+ // re-filters what is already loaded and never touches the item.+ const timeFence = useTimeFenceOverrides();++ const fencedActionsByItemId = useMemo(() => {+ const map = new Map<string, PlanningAction[]>();+ for (const row of data) {+ const actions = actionsByItemId.get(row.id);+ if (!actions) continue;+ const fenced = actionsInsideFence(actions, timeFence.fenceDateFor(row));+ if (fenced.length > 0) map.set(row.id, fenced);+ }+ return map;+ }, [data, actionsByItemId, timeFence]);++ // What the GRID shows and acts on: under the Actions-column filter, only+ // the filtered types. The order drawer keeps every fenced action — it lists+ // the item's open orders, and one shown without its pending suggestion+ // would read as "nothing to do".+ const visibleActionsByItemId = useMemo(() => {+ if (!actionTypes) return fencedActionsByItemId;+ const map = new Map<string, PlanningAction[]>();+ for (const [itemId, actions] of fencedActionsByItemId) {+ const visible = actionsOfTypes(actions, actionTypes);+ if (visible.length > 0) map.set(itemId, visible);+ }+ return map;+ }, [fencedActionsByItemId, actionTypes]);++ // ONE batched request per click: the route derives each row's behaviour+ // from its persisted type, and a fetcher holds a single in-flight submission.+ const submitActions = useCallback(+ (payload: Record<string, unknown>) => {+ actionsFetcher.submit(JSON.stringify({ locationId, ...payload }), {+ method: "post",+ action: updatePath,+ encType: "application/json"+ });+ },+ [actionsFetcher, locationId, updatePath]+ );++ // What the expanded action lines and the order drawer's open-orders grid+ // act through: the same props `PlanningActionLines` takes.+ const actionHandlers = useMemo(+ () => ({+ currentUserId,+ canUpdate,+ isBusy: isActionsBusy,+ onApply: (ids: string[]) =>+ submitActions({ action: "apply", planningActionIds: ids }),+ onDismiss: (ids: string[]) =>+ submitActions({ action: "dismiss", planningActionIds: ids }),+ onReopen: (ids: string[]) =>+ submitActions({ action: "reopen", planningActionIds: ids }),+ onAssignToMe: (ids: string[]) =>+ submitActions({+ action: "assign",+ planningActionIds: ids,+ assignee: currentUserId+ }),+ // An empty assignee unassigns.+ onAssign: (ids: string[], assignee: string) =>+ submitActions({ action: "assign", planningActionIds: ids, assignee })+ }),+ [currentUserId, canUpdate, isActionsBusy, submitActions]+ );++ return {+ actionHandlers,+ isActionsBusy,+ timeFence,+ actionsByItemId,+ fencedActionsByItemId,+ visibleActionsByItemId,+ submitActions+ };+}diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.mdindex a47378f00d..200b4cdb13 100644--- a/apps/erp/app/modules/purchasing/AGENTS.md+++ b/apps/erp/app/modules/purchasing/AGENTS.md@@ -4,13 +4,15 @@ Purchase orders, supplier management, supplier quotes/interactions, RFQs, and pr## Key Domain Concepts-- **Purchase Order (PO)** — document sent to a supplier. Statuses: Draft → Needs Approval → To Review → To Receive → To Receive and Invoice → To Invoice → Completed. MUST use `closePurchaseOrder` to close manually.+- **Purchase Order (PO)** — document sent to a supplier. Statuses (`purchaseOrderStatusType`, `purchasing.models.ts`): Draft → Planned (from a planning suggestion) → Needs Approval → To Review → To Receive → To Receive and Invoice → To Invoice → Completed, plus Rejected and Closed. MUST use `closePurchaseOrder` to close manually.- **PO Revision** — `purchaseOrder.revisionId` counts amendments to a released order. Created ONLY when the header dropdown's "Create PO Revision" action posts `createRevision=true`; a plain Reopen never bumps. The write is `reopenPurchaseOrderAsRevision` (Kysely, `purchasing.service.ts`): a compare-and-swap that sets `revisionId = revisionId + 1` **in SQL** with the eligibility conditions (locked status + non-null `orderDate`) in the WHERE clause, so concurrent requests can't collide and an ineligible order matches 0 rows. `canCreatePurchaseOrderRevision` (`purchasing.models.ts`) is the matching pure predicate used to gate the menu item — keep the two in sync. Unlike quotes, a PO revision is in-place: no new row, receipts/invoices stay attached. Displayed as `PO000123-1` when > 0 via `getPurchaseOrderDisplayId` (`@carbon/documents/utils`) on the PDF, email, filenames, and UI; the two-tone in-app rendering uses `<RevisionSuffix>` (`~/components`).- **Supplier Interaction** — umbrella entity linking a supplier quote to RFQs, POs, and documents. A supplier quote always lives under an interaction.- **Supplier Quote** — vendor-side pricing with line-level price breaks (`supplierQuoteLinePrice`). Can be finalized (`finalizeSupplierQuote`) and converted to POs via the `convert` server function.- **RFQ (Request for Quotation)** — solicits pricing from multiple suppliers. Links to supplier quotes via `purchasingRfqToSupplierQuote`. Statuses managed by `updatePurchasingRFQStatus`.- **Conversion Factor** — when a supplier's UoM differs from stocking UoM, `conversionFactor` on `purchaseOrderLine` scales quantities at receipt: `inventoryQty = purchaseQty × conversionFactor`. See `.claude/rules/purchasing-conversion-factors.md`.-- **Purchasing Planning** — MRP-driven planned orders surfaced via `getPurchasingPlanning` (calls `get_purchasing_planning` RPC).+- **Purchasing Planning** — MRP-driven planned orders surfaced via `getPurchasingPlanning` (calls the `get_purchasing_planning_grid` RPC, which wraps `get_purchasing_planning` with the planning-horizon fence, first negative week, latest order date and the database-side action filters). Planning actions on PO lines are applied by `x+/purchasing+/planning.update.tsx` through `applyPurchasingPlanningActions(db, …)` — set-based, one Kysely transaction for the whole batch: the claim, one `UPDATE … FROM (VALUES …)` for the dates, one for the quantities (tax pair restated via `taxPairForQuantity`), one `DELETE` for the cancels (a Draft / Planned PO and nothing received or invoiced, in the statement), and the un-claim of refused rows (`planning-action-claims.ts`, shared with production). The drawer's inline edit of one line goes through `updatePurchaseOrderLineSchedule` (one Kysely UPDATE with the same Draft / Planned guard, returns `updated`). Planning changes a PO only while `isPurchaseOrderEditableFromPlanning` (Draft / Planned — not in approval, not sent). Ordering suggestions raises one PO per supplier per week (`planningPurchaseOrderWeek` + `findPlanningPurchaseOrder`, `purchasing.models.ts`), so each week's PO is finalized on its own and the later weeks stay editable from planning. An Increase / Decrease writes `quantityReceived` + the suggested quantity still to come (MRP reads a line's `quantityToReceive`), so a reopened, partly received line keeps its receipts. A row's ⋯ (expanded action lines and the drawer's Open Orders) carries the order's own commands from `usePurchaseOrderPlanningCommands` (`ui/Planning/`): **Reopen** / **Reopen as Revision** on a PO planning cannot change, posting `status=Planned` (+ `createRevision`) to the PO status route — Planned, NOT Draft, because Draft is not MRP supply (`openPurchaseOrderLines`) and a Draft PO's lines would be suggested again as a new order — and **Finalize** on a Draft / Planned PO, through `PurchaseOrderFinalizeModal` (now takes a `purchaseOrderId` prop) with its order + default CC from `api+/purchasing.purchase-order.$id.finalize.ts`.+- **Planning approval bypass** — `purchaseOrder.createdFromPlanning` (migration `20261006214907`) is set by the planning Order route on the POs it creates (and restored on planning POs it adds lines to). `upsertPurchaseOrderLine` / `deletePurchaseOrderLine` clear it BEFORE writing (`clearPlanningOrigin`), so any manual line change — PO page, API, MCP, kanban — sends the PO back through approval; planning's Apply and drawer edits (Kysely) never touch it. `$orderId.finalize.tsx` skips `isApprovalRequired` when the flag is set AND `companySettings.skipApprovalForPlanningPurchaseOrders` (default true, Settings → Planning → Purchase Order Approval) — failing closed on a read error.+- **Reopen** — `purchase-order+/$orderId.status.tsx` treats a move to Draft OR Planned as a reopen (`PURCHASE_ORDER_REOPEN_STATUSES` / `isPurchaseOrderReopenStatus`): `purchasing_delete` from a locked status, pending approvals cancelled (from Needs Approval only by the requester or an approver), and an optional revision bump — `reopenPurchaseOrderAsRevision` takes the target status, `canCreatePurchaseOrderRevision` accepts either. A reopen to Planned skips the MRP run when the PO already was supply (Planned / To Receive / To Receive and Invoice).## Safety@@ -64,7 +66,9 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing- `duplicatePurchaseOrder` — copies a PO with new sequence- `finalizePurchaseOrder` / `finalizeSupplierQuote` — lock documents for processing- `sendSupplierQuote` — sends quote to supplier-- `getPurchasingPlanning` — MRP-driven planned order view (RPC `get_purchasing_planning`)+- `getPurchasingPlanning` — MRP-driven planned order view (RPC `get_purchasing_planning_grid`)+- `applyPurchasingPlanningActions(db, { companyId, userId, actions })` — one Kysely transaction for a batch of planning actions on PO lines: the claim (Open → Actioned, returning each action's suggested quantity and date, which are what gets written), one `UPDATE … FROM (VALUES …)` for dates and one for quantities (`taxPairForQuantity` restates the tax pair), one `DELETE` for Cancels (Draft / Planned PO, nothing received or invoiced), then the refused claims are released. Returns `{ applied, alreadyApplied, refused, failed }`+- `updatePurchaseOrderLineSchedule(client, db, args)` — planning's single-line write (the order drawer's inline edit): `requiredDate` or `purchaseQuantity` on a line of a Draft / Planned PO, the guard inside the UPDATE; returns `{ updated, error }`- `getSupplierApprovalContext` — reads approval workflow state- `getPurchasingRFQ` / `getPurchasingRFQs` / `upsertPurchasingRFQ` — RFQ management- `getSupplierQuotesForComparison` — side-by-side quote comparisondiff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.tsindex 7c3e313fe5..261891bce5 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts@@ -77,9 +77,21 @@ describe("canCreatePurchaseOrderRevision", () => {).toBe(expected);});- it("is never eligible for a non-Draft target status", () => {+ it("follows the same matrix when reopening to Planned", () => {+ for (const { currentStatus, orderDate, expected } of reopenMatrix) {+ expect(+ canCreatePurchaseOrderRevision({+ newStatus: "Planned",+ currentStatus,+ orderDate+ })+ ).toBe(expected);+ }+ });++ it("is never eligible for a target status that is not a reopen", () => {for (const newStatus of purchaseOrderStatusType) {- if (newStatus === "Draft") continue;+ if (newStatus === "Draft" || newStatus === "Planned") continue;for (const currentStatus of purchaseOrderStatusType) {expect(canCreatePurchaseOrderRevision({diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.tsindex 9cfcfb9abe..6351597933 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts@@ -2,12 +2,23 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { Database } from "@carbon/database";import {bicMatchesCountry,getBankFieldConfig,- isValidSwiftBic+ isValidSwiftBic,+ type TaxPair,+ taxableBase,+ taxPairFromAmount,+ taxPairFromPercent} from "@carbon/utils";-import { getLocalTimeZone, today } from "@internationalized/date";+import {+ type CalendarDate,+ getLocalTimeZone,+ parseDate,+ startOfWeek,+ today+} from "@internationalized/date";import { z } from "zod";import { zfd } from "zod-form-data";import { address, contact } from "~/types/validators";@@ -107,15 +118,18 @@ export const plannedOrderValidator = z.object({periodId: z.string().min(1, { message: "Period is required" }),quantity: zfd.numeric(z.number().min(0)),existingId: zfd.text(z.string().optional()),+ // The chart and the drawer's open-order rows use this to tell an existing+ // line from a suggested order. The Order action ignores it: an existing+ // line is edited only through updatePurchaseOrderLineSchedule.existingLineId: zfd.text(z.string().optional()),existingQuantity: zfd.numeric(z.number().optional()),existingReadableId: zfd.text(z.string().optional()),- existingStatus: zfd.text(z.string().optional()),+ existingStatus: zfd.text(z.enum(purchaseOrderStatusType).optional()),supplierId: zfd.text(z.string().optional()),itemReadableId: zfd.text(z.string().optional()),unitPrice: zfd.numeric(z.number().optional()),unitOfMeasureCode: zfd.text(z.string().optional()),- // ── Reorder-policy attribution (populated by calculateOrders for+ // ── Reorder-policy attribution (copied from the Order action for// MRP-suggested orders; absent for user-added "Add Order" rows). ──policyName: zfd.text(z.string().optional()),reason: zfd.text(z.string().optional()),@@ -741,11 +755,131 @@ export function isPurchaseOrderLocked();}+/**+ * The PO statuses planning may change: Apply on a planning action, the order+ * drawer's inline edits, and Cancel's line delete. An allowlist on purpose —+ * a PO in approval (Needs Approval, To Review, Rejected) or sent to the supplier+ * is reviewed on the PO. Matches MRP's own `isCommittedPurchaseOrderStatus`+ * (`@carbon/planning`), which offers "Review on PO" for every other status.+ */+export const PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES = [+ "Draft",+ "Planned"+] as const;++export function isPurchaseOrderEditableFromPlanning(+ status: Database["public"]["Enums"]["purchaseOrderStatus"] | null | undefined+): boolean {+ return PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES.some(+ (editable) => editable === status+ );+}++/**+ * The tax pair for a PO line whose quantity changes. The extended price is a+ * generated column, the tax amount is not, so a quantity write must restate+ * the amount at the line's rate or the pair stops agreeing.+ *+ * A line with a rate keeps it. A line that holds only an amount (written before+ * the pair was enforced) has its rate derived once from the old base, so its+ * tax scales with the quantity instead of being zeroed.+ */+export function taxPairForQuantity(+ line: {+ supplierUnitPrice: number | null;+ supplierShippingCost: number | null;+ purchaseQuantity: number | null;+ taxPercent: number | null;+ supplierTaxAmount: number | null;+ },+ purchaseQuantity: number,+ currencyDecimals: number+): TaxPair {+ const unitPrice = Number(line.supplierUnitPrice ?? 0);+ const shippingCost = Number(line.supplierShippingCost ?? 0);+ const rate =+ line.taxPercent ??+ taxPairFromAmount(+ taxableBase(unitPrice, Number(line.purchaseQuantity ?? 0), shippingCost),+ Number(line.supplierTaxAmount ?? 0),+ 0+ ).percent;++ return taxPairFromPercent(+ taxableBase(unitPrice, purchaseQuantity, shippingCost),+ rate,+ currencyDecimals+ );+}++/**+ * The week a planned PO line is ordered in, as the date that week starts.+ * Planning raises one PO per supplier per week, so each PO can be finalized+ * and sent alone while the later weeks stay Planned and MRP can still change+ * them. Weeks start on Sunday, as the planning grid's periods do+ * (`getOrCreatePeriods`). A line due before `asOf` (the location's today), or+ * with no due date, is in the current week: it is late, so it goes on the next PO sent.+ */+export function planningPurchaseOrderWeek(+ requiredDate: string | null | undefined,+ asOf: CalendarDate+): string {+ const due = requiredDate ? parseDate(requiredDate) : asOf;+ return startOfWeek(due.compare(asOf) < 0 ? asOf : due, "en-US").toString();+}++/**+ * The open PO a planned order for `week` joins: the oldest candidate for the+ * supplier, in the supplier's currency, whose lines are ALL in that week.+ * Candidates are the supplier's Draft / Planned purchase orders at the+ * location, oldest first. A PO with lines in several weeks (raised before the+ * weekly rule, or a line moved by hand) takes no more orders, so it cannot+ * keep collecting weeks, and a PO with no lines is never reused.+ */+export function findPlanningPurchaseOrder<+ P extends {+ supplierId: string;+ currencyCode: string | null;+ purchaseOrderLine: { requiredDate: string | null }[];+ }+>(+ candidates: P[],+ target: { supplierId: string; currencyCode: string; week: string },+ asOf: CalendarDate+): P | undefined {+ return candidates.find(+ (po) =>+ po.supplierId === target.supplierId &&+ po.currencyCode === target.currencyCode &&+ po.purchaseOrderLine.length > 0 &&+ po.purchaseOrderLine.every(+ (line) =>+ planningPurchaseOrderWeek(line.requiredDate, asOf) === target.week+ )+ );+}++/**+ * The statuses a reopen moves a purchase order back to: Draft from the PO+ * page, Planned from the planning pages. Planned because Draft is not MRP+ * supply (`openPurchaseOrderLines` leaves it out): a PO reopened to Draft from+ * planning dropped out of the plan, and the next run suggested its whole+ * quantity again as a new order.+ */+export const PURCHASE_ORDER_REOPEN_STATUSES = ["Draft", "Planned"] as const;++export function isPurchaseOrderReopenStatus(+ status: string | null | undefined+): status is (typeof PURCHASE_ORDER_REOPEN_STATUSES)[number] {+ return PURCHASE_ORDER_REOPEN_STATUSES.some((reopen) => reopen === status);+}+/*** Whether a status change is ELIGIBLE to create a revision — the bump itself* also requires the explicit `createRevision` flag. Only a released order- * qualifies: `orderDate` is set at finalize, so an order reopened from- * "Needs Approval" or closed straight from Draft never reached the supplier.+ * reopened to Draft or Planned qualifies: `orderDate` is set at finalize, so+ * an order reopened from "Needs Approval" or closed straight from Draft never+ * reached the supplier.*/export function canCreatePurchaseOrderRevision(transition: {newStatus: (typeof purchaseOrderStatusType)[number];@@ -753,7 +887,7 @@ export function canCreatePurchaseOrderRevision(transition: {orderDate: string | null | undefined;}): boolean {return (- transition.newStatus === "Draft" &&+ isPurchaseOrderReopenStatus(transition.newStatus) &&isPurchaseOrderLocked(transition.currentStatus) &&Boolean(transition.orderDate));diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex cd0af41075..0217243a0d 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -14,6 +14,7 @@ import {EPSILON,getPurchaseOrderStatus,getPurchaseReturnOrderStatus,+ RoundingMode,round} from "@carbon/utils";import type {@@ -34,6 +35,10 @@ import {getExchangeRate} from "../accounting/accounting.service";import type { PurchaseInvoice } from "../invoicing/types";+import {+ claimPlanningActions,+ releasePlanningActionClaims+} from "../production/planning-action-claims";import { upsertExternalLink } from "../shared/shared.service";import { updateSortOrder } from "../shared/sort-order";import type {@@ -61,7 +66,12 @@ import type {supplierTypeValidator,supplierValidator} from "./purchasing.models";-import { PURCHASE_ORDER_LOCKED_STATUSES } from "./purchasing.models";+import {+ PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES,+ PURCHASE_ORDER_LOCKED_STATUSES,+ type PURCHASE_ORDER_REOPEN_STATUSES,+ taxPairForQuantity+} from "./purchasing.models";import type { PurchaseOrder, PurchasingRFQ, SupplierQuote } from "./types";const PURCHASE_ORDERS_LIST_COLUMNS =@@ -122,11 +132,47 @@ export async function deletePurchaseOrder(return client.from("purchaseOrder").delete().eq("id", purchaseOrderId);}+/**+ * A purchase order raised by the planning pages skips the approval rule+ * (`purchaseOrder.createdFromPlanning`, with the company's+ * `skipApprovalForPlanningPurchaseOrders`). Any manual change to its lines+ * forfeits that, so an MRP order cannot be padded to dodge approval: the line+ * writers below clear the flag BEFORE they write — a failed clear stops the+ * write, so a line never changes while the PO still skips approval. Planning+ * restores the flag after its own line writes (`planning.update.tsx`).+ */+async function clearPlanningOrigin(+ client: SupabaseClient<Database>,+ where: { purchaseOrderId: string } | { purchaseOrderLineId: string }+) {+ let purchaseOrderId: string | null;+ if ("purchaseOrderId" in where) {+ purchaseOrderId = where.purchaseOrderId;+ } else {+ const line = await client+ .from("purchaseOrderLine")+ .select("purchaseOrderId")+ .eq("id", where.purchaseOrderLineId)+ .maybeSingle();+ if (line.error) return { error: line.error };+ purchaseOrderId = line.data?.purchaseOrderId ?? null;+ }+ if (!purchaseOrderId) return { error: null };+ const cleared = await client+ .from("purchaseOrder")+ .update({ createdFromPlanning: false })+ .eq("id", purchaseOrderId)+ .eq("createdFromPlanning", true);+ return { error: cleared.error };+}+/** @mcp delete */export async function deletePurchaseOrderLine(client: SupabaseClient<Database>,purchaseOrderLineId: string) {+ const cleared = await clearPlanningOrigin(client, { purchaseOrderLineId });+ if (cleared.error) return { data: null, error: cleared.error };return client.from("purchaseOrderLine").delete()@@ -570,14 +616,31 @@ export async function getPurchasingPlanning(periods: string[],args: GenericQueryFilters & {search: string | null;+ /** Today on the location's calendar (ISO date): the day each item's+ * planning horizon is counted from. */+ asOf: string;+ /** Keep only items with an OPEN planning action of one of these types+ * inside the item's planning horizon (the grid's Actions filter). */+ actionTypes?: string[];+ /** Keep only items with such an action assigned to this user ("Assigned+ * to me"). Combined with `actionTypes` on the SAME action. */+ actionAssignees?: string[];}) {+ // The grid RPC wraps get_purchasing_planning: same rows and projection, plus the+ // item group, the planning horizon / time fence date, the first week the+ // projection goes negative and the latest order date — and it evaluates the+ // action filter in the database, so it is complete at any volume and paging+ // stays correct.let query = client.rpc(- "get_purchasing_planning",+ "get_purchasing_planning_grid",{location_id: locationId,company_id: companyId,- periods+ periods,+ as_of: args.asOf,+ action_types: args.actionTypes,+ action_assignees: args.actionAssignees},{count: LIST_COUNT@@ -590,8 +653,12 @@ export async function getPurchasingPlanning();}+ // What the row's Order / Make button offers (the grid RPC's orderQuantity,+ // from MRP's open new-supply actions), then the part number so a page is+ // stable when many rows have nothing to order.query = setGenericQueryFilters(query, args, [- { column: "quantityToOrder", ascending: false }+ { column: "orderQuantity", ascending: false },+ { column: "readableIdWithRevision", ascending: true }]);return query;@@ -1360,7 +1427,8 @@ export async function updatePurchaseOrderStatus(}/**- * Reopens a released purchase order to Draft as its next revision.+ * Reopens a released purchase order as its next revision — to Draft from the+ * PO page, or to Planned from planning (see `PURCHASE_ORDER_REOPEN_STATUSES`).** Compare-and-swap: the increment and the eligibility conditions are both in* SQL, so concurrent requests can't share a revision number and an ineligible@@ -1372,17 +1440,19 @@ export async function reopenPurchaseOrderAsRevision({id,companyId,- updatedBy+ updatedBy,+ status = "Draft"}: {id: string;companyId: string;updatedBy: string;+ status?: (typeof PURCHASE_ORDER_REOPEN_STATUSES)[number];}) {const result = await db.updateTable("purchaseOrder").set((eb) => ({- status: "Draft" as const,+ status,assignee: null,revisionId: eb("revisionId", "+", 1),updatedBy,@@ -2042,6 +2112,12 @@ export async function upsertPurchaseOrderLine() {const normalized = normalizePurchaseOrderLineReferences(purchaseOrderLine);+ // a manual line change forfeits the planning approval bypass+ const cleared = await clearPlanningOrigin(client, {+ purchaseOrderId: normalized.purchaseOrderId+ });+ if (cleared.error) return { data: null, error: cleared.error };+if ("id" in normalized) {return client.from("purchaseOrderLine")@@ -2171,6 +2247,337 @@ export async function shortClosePurchaseOrderLine(});}+// ── Planning actions: Apply, set-based ──────────────────────────────────────++export type PurchasingPlanningApplyAction = {+ planningActionId: string;+ type: "Expedite" | "Defer" | "Increase" | "Decrease" | "Cancel";+ lineId: string;+ purchaseOrderId: string;+ /** Expedite / Defer: the new required date */+ suggestedDate: string | null;+ /** Increase / Decrease: the new quantity, in INVENTORY units */+ suggestedQuantity: number | null;+};++export type PurchasingPlanningApplyResult = {+ /** changed and marked Actioned */+ applied: string[];+ /** marked Actioned by another apply since the page loaded; nothing changed */+ alreadyApplied: string[];+ /** the write was refused (PO sent or in approval, line received or invoiced+ * since it was read): the action stays Open for review on the PO */+ refused: { id: string; purchaseOrderId: string }[];+ /** could not be computed (a currency with no precision): the action stays Open */+ failed: { id: string; message: string }[];+};++/**+ * Apply a batch of planning actions to their purchase order lines in ONE+ * transaction, set-based: every date change is one statement, every quantity+ * change one, every cancel one, and the claim one — about five round trips+ * for any batch size. It used to be one claim and one to three round trips+ * per action, in sequence, which made a large batch run into the request's+ * time limit with the rest of it still unapplied.+ *+ * Order inside the transaction:+ * 1. claim: every Open action flips to Actioned; one that does not flip was+ * applied by someone else since the page loaded, and its line is left+ * alone — a stale page never overwrites a later manual edit.+ * 2. write: each claimed action's change, with the same guards as the+ * single-line writers (a Draft / Planned PO; nothing received or invoiced+ * on a line to cancel). A refused write un-claims its action.+ * 3. un-claim: back to Open — or deleted when an MRP run has meanwhile written+ * a fresh Open row for the same need (the natural-key index), as+ * `releasePlanningActionClaim` does.+ * A failure anywhere rolls the whole batch back: nothing is half-applied.+ *+ * A quantity change restates the line's tax pair (`taxPairForQuantity`): the+ * extended price is generated from the quantity, the tax amount is stored.+ * `suggestedQuantity` is in INVENTORY units; the line stores PURCHASE units,+ * converted by the line's own `conversionFactor` and rounded up to a whole+ * purchase unit, as the drawer shows it. It is what the line should still+ * BRING — MRP reads a line's `quantityToReceive` — so what was already+ * received is added back: a PO reopened from planning after a partial receipt+ * would otherwise lose it (an Increase to 16 on a line with 5 received left+ * only 11 to come).+ */+export async function applyPurchasingPlanningActions(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ companyGroupId: string;+ userId: string;+ actions: PurchasingPlanningApplyAction[];+ }+): Promise<PurchasingPlanningApplyResult> {+ const { companyId, companyGroupId, userId, actions } = args;+ const result: PurchasingPlanningApplyResult = {+ applied: [],+ alreadyApplied: [],+ refused: [],+ failed: []+ };+ if (actions.length === 0) return result;++ const now = datetime.timestamp();+ const editableStatuses = [...PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES];++ await db.transaction().execute(async (trx) => {+ // 1. claim+ const claimed = await claimPlanningActions(trx, {+ ids: actions.map((a) => a.planningActionId),+ companyId,+ userId,+ now+ });+ // The quantity and date come from the claim, not from the page's read+ // (see claimPlanningActions); the page's values are only the fallback.+ const held = actions.flatMap((a) => {+ const claim = claimed.get(a.planningActionId);+ if (!claim) return [];+ return [+ {+ ...a,+ suggestedDate: claim.suggestedDate ?? a.suggestedDate,+ suggestedQuantity: claim.suggestedQuantity ?? a.suggestedQuantity+ }+ ];+ });+ for (const action of actions) {+ if (!claimed.has(action.planningActionId)) {+ result.alreadyApplied.push(action.planningActionId);+ }+ }++ const editablePurchaseOrders = trx+ .selectFrom("purchaseOrder")+ .select("id")+ .where("companyId", "=", companyId)+ .where("status", "in", editableStatuses);++ const changedLines = new Set<string>();++ // 2a. dates+ const dates = held.filter(+ (a) => (a.type === "Expedite" || a.type === "Defer") && a.suggestedDate+ );+ if (dates.length > 0) {+ const rows = await sql<{ id: string }>`+ UPDATE "purchaseOrderLine" AS l+ SET "requiredDate" = v."requiredDate"::date,+ "updatedBy" = ${userId},+ "updatedAt" = ${now}+ FROM (VALUES ${sql.join(+ dates.map((a) => sql`(${a.lineId}, ${a.suggestedDate})`)+ )}) AS v("id", "requiredDate")+ WHERE l."id" = v."id"+ AND l."companyId" = ${companyId}+ AND l."purchaseOrderId" IN (${editablePurchaseOrders})+ RETURNING l."id"+ `.execute(trx);+ for (const row of rows.rows) changedLines.add(row.id);+ }++ // 2b. quantities — the tax pair is computed here, in TypeScript, from one+ // read of the lines' pricing and one of their currencies+ const quantities = held.filter(+ (a) =>+ (a.type === "Increase" || a.type === "Decrease") &&+ a.suggestedQuantity !== null+ );+ if (quantities.length > 0) {+ const lineIds = [...new Set(quantities.map((a) => a.lineId))];+ // A PO with no currency is in the company's base currency, as the PO+ // line form reads it; refusing it failed every Increase / Decrease on+ // such a PO with "Currency (none) has no precision".+ const lines = (+ await trx+ .selectFrom("purchaseOrderLine as pol")+ .innerJoin("purchaseOrder as po", "po.id", "pol.purchaseOrderId")+ .innerJoin("company as c", "c.id", "po.companyId")+ .select([+ "pol.id",+ "pol.supplierUnitPrice",+ "pol.supplierShippingCost",+ "pol.purchaseQuantity",+ "pol.quantityReceived",+ "pol.taxPercent",+ "pol.supplierTaxAmount",+ "pol.conversionFactor",+ "po.currencyCode",+ "c.baseCurrencyCode"+ ])+ .where("pol.id", "in", lineIds)+ .where("pol.companyId", "=", companyId)+ .execute()+ ).map(({ baseCurrencyCode, ...line }) => ({+ ...line,+ currencyCode: line.currencyCode ?? baseCurrencyCode+ }));+ const lineById = new Map(lines.map((line) => [line.id, line]));+ const codes = [+ ...new Set(+ lines.flatMap((l) => (l.currencyCode ? [l.currencyCode] : []))+ )+ ];+ const currencies =+ codes.length > 0+ ? await trx+ .selectFrom("currencies")+ .select(["code", "decimalPlaces"])+ .where("companyGroupId", "=", companyGroupId)+ .where("code", "in", codes)+ .execute()+ : [];+ const decimalsByCode = new Map(+ currencies.flatMap((c) =>+ c.code && c.decimalPlaces != null ? [[c.code, c.decimalPlaces]] : []+ )+ );++ const values: {+ lineId: string;+ quantity: number;+ percent: number;+ amount: number;+ }[] = [];+ const unheld: string[] = [];+ for (const action of quantities) {+ const line = lineById.get(action.lineId);+ const decimals = line?.currencyCode+ ? decimalsByCode.get(line.currencyCode)+ : undefined;+ if (!line || decimals === undefined) {+ result.failed.push({+ id: action.planningActionId,+ message: line+ ? `Currency ${line.currencyCode ?? "(none)"} has no precision`+ : "Purchase order line not found"+ });+ unheld.push(action.planningActionId);+ continue;+ }+ const conversionFactor = Number(line.conversionFactor) || 1;+ // MRP suggests a whole number of purchase units already+ // (`quantityAfterApply`, @carbon/planning); the inner round strips+ // float noise (1.1 / 0.1 = 11.000000000000002) that would otherwise+ // ceil it a whole purchase unit up.+ const toReceive =+ conversionFactor > 0+ ? round(+ round(Number(action.suggestedQuantity) / conversionFactor),+ 0,+ RoundingMode.Up+ )+ : Number(action.suggestedQuantity);+ const quantity = round(+ (Number(line.quantityReceived) || 0) + toReceive+ );+ const pair = taxPairForQuantity(line, quantity, decimals);+ values.push({+ lineId: action.lineId,+ quantity,+ percent: pair.percent,+ amount: pair.amount+ });+ }+ // a failed computation never holds its claim+ for (const id of unheld) claimed.delete(id);++ if (values.length > 0) {+ const rows = await sql<{ id: string }>`+ UPDATE "purchaseOrderLine" AS l+ SET "purchaseQuantity" = v."purchaseQuantity"::numeric,+ "taxPercent" = v."taxPercent"::numeric,+ "supplierTaxAmount" = v."supplierTaxAmount"::numeric,+ "updatedBy" = ${userId},+ "updatedAt" = ${now}+ FROM (VALUES ${sql.join(+ values.map(+ (v) =>+ sql`(${v.lineId}, ${v.quantity}, ${v.percent}, ${v.amount})`+ )+ )}) AS v("id", "purchaseQuantity", "taxPercent", "supplierTaxAmount")+ WHERE l."id" = v."id"+ AND l."companyId" = ${companyId}+ AND l."purchaseOrderId" IN (${editablePurchaseOrders})+ RETURNING l."id"+ `.execute(trx);+ for (const row of rows.rows) changedLines.add(row.id);+ }+ }++ // 2c. cancels — a Draft / Planned PO and nothing received or invoiced on+ // the line, in the one DELETE, so a finalize or a receipt that lands+ // after the caller read the PO cannot slip in between. Not+ // shortClosePurchaseOrderLine: that recomputes the header status from+ // the lines and turned an unsent one-line Draft into "Completed". The+ // delete cascades to the action rows themselves, so these need no+ // claim to keep and nothing to un-claim.+ const cancels = held.filter((a) => a.type === "Cancel");+ if (cancels.length > 0) {+ const deleted = await trx+ .deleteFrom("purchaseOrderLine")+ .where(+ "id",+ "in",+ cancels.map((a) => a.lineId)+ )+ .where("companyId", "=", companyId)+ .where((eb) =>+ eb.and([+ eb(eb.fn.coalesce("quantityReceived", eb.val(0)), "=", 0),+ eb(eb.fn.coalesce("quantityInvoiced", eb.val(0)), "=", 0)+ ])+ )+ .where("purchaseOrderId", "in", editablePurchaseOrders)+ // A draft invoice line holds an ON DELETE RESTRICT reference: deleting+ // under it threw and rolled the whole batch back. Left alone, the+ // action goes to review like any other refused Cancel.+ .where(({ not, exists, selectFrom }) =>+ not(+ exists(+ selectFrom("purchaseInvoiceLine")+ .select("purchaseInvoiceLine.id")+ .whereRef(+ "purchaseInvoiceLine.purchaseOrderLineId",+ "=",+ "purchaseOrderLine.id"+ )+ )+ )+ )+ .returning("id")+ .execute();+ for (const row of deleted) changedLines.add(row.id);+ }++ // 3. settle: applied, or refused and un-claimed+ const refusedIds: string[] = [];+ for (const action of held) {+ if (result.failed.some((f) => f.id === action.planningActionId)) continue;+ if (changedLines.has(action.lineId)) {+ result.applied.push(action.planningActionId);+ } else {+ refusedIds.push(action.planningActionId);+ result.refused.push({+ id: action.planningActionId,+ purchaseOrderId: action.purchaseOrderId+ });+ }+ }+ await releasePlanningActionClaims(trx, {+ ids: [...refusedIds, ...result.failed.map((f) => f.id)],+ companyId,+ userId,+ now+ });+ });++ return result;+}+/** @mcp upsert */export async function upsertPurchaseOrderPayment(client: SupabaseClient<Database>,@@ -3298,6 +3705,120 @@ export async function getDefaultAttachmentsForPO(});}+/**+ * Apply a planning schedule/quantity change to a PO line.+ * `purchaseQuantity` is in PURCHASE units — the caller converts from inventory+ * units via the line's conversionFactor.+ *+ * A quantity change also restates the line's tax pair (`taxPairForQuantity`):+ * the extended price is generated from the quantity, the tax amount is stored,+ * so writing the quantity alone left the old amount against a new base.+ *+ * The Draft / Planned condition (`PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES`)+ * is part of the UPDATE, so a PO sent or put in approval after the caller read+ * it is left alone: `updated` is false, and the caller sends the planner to+ * the PO instead.+ */+export async function updatePurchaseOrderLineSchedule(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ lineId: string;+ companyId: string;+ companyGroupId: string;+ userId: string;+ requiredDate?: string;+ purchaseQuantity?: number;+ }+): Promise<{ updated: boolean; error: { message: string } | null }> {+ let tax: { taxPercent: number; supplierTaxAmount: number } | undefined;++ if (args.purchaseQuantity !== undefined) {+ const line = await client+ .from("purchaseOrderLine")+ .select(+ "supplierUnitPrice, supplierShippingCost, purchaseQuantity, taxPercent, supplierTaxAmount, purchaseOrder!inner(currencyCode)"+ )+ .eq("id", args.lineId)+ .eq("companyId", args.companyId)+ .single();+ if (line.error) return { updated: false, error: line.error };++ // A PO with no currency is in the company's base currency, as the PO+ // line form reads it.+ let currencyCode = line.data.purchaseOrder?.currencyCode ?? null;+ if (!currencyCode) {+ const company = await client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", args.companyId)+ .single();+ if (company.error) return { updated: false, error: company.error };+ currencyCode = company.data.baseCurrencyCode;+ }+ if (!currencyCode) {+ return {+ updated: false,+ error: { message: "Purchase order has no currency" }+ };+ }+ const currency = await getCurrencyByCode(+ client,+ args.companyGroupId,+ currencyCode+ );+ if (currency.error) return { updated: false, error: currency.error };+ if (currency.data?.decimalPlaces == null) {+ return {+ updated: false,+ error: { message: `Currency ${currencyCode} has no precision` }+ };+ }++ const pair = taxPairForQuantity(+ line.data,+ args.purchaseQuantity,+ currency.data.decimalPlaces+ );+ tax = { taxPercent: pair.percent, supplierTaxAmount: pair.amount };+ }++ try {+ const updated = await db+ .updateTable("purchaseOrderLine")+ .set({+ ...(args.requiredDate !== undefined+ ? { requiredDate: args.requiredDate }+ : {}),+ ...(args.purchaseQuantity !== undefined+ ? { purchaseQuantity: args.purchaseQuantity }+ : {}),+ ...(tax ?? {}),+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", args.lineId)+ .where("companyId", "=", args.companyId)+ .where("purchaseOrderId", "in", (eb) =>+ eb+ .selectFrom("purchaseOrder")+ .select("id")+ .where("companyId", "=", args.companyId)+ .where("status", "in", [...PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES])+ )+ .returning("id")+ .execute();+ return { updated: updated.length > 0, error: null };+ } catch (err) {+ return {+ updated: false,+ error: {+ message: err instanceof Error ? err.message : "Failed to update line"+ }+ };+ }+}+// ─── Purchase Return Orders (Supplier Returns) ───/** @mcp read */diff --git a/apps/erp/app/modules/purchasing/types.ts b/apps/erp/app/modules/purchasing/types.tsindex 8fb12bf7e6..961801a18b 100644--- a/apps/erp/app/modules/purchasing/types.ts+++ b/apps/erp/app/modules/purchasing/types.ts@@ -4,6 +4,7 @@import type { Database } from "@carbon/database";import type { FileObject } from "@supabase/storage-js";+import type { PlanningGridColumns } from "../production/types";import type {getPurchaseOrderDelivery,getPurchaseOrderLines,@@ -59,9 +60,13 @@ export type PurchaseOrderType =export type PurchaseOrderTransactionType =Database["public"]["Enums"]["purchaseOrderTransactionType"];-export type PurchasingPlanningItem = NonNullable<- Awaited<ReturnType<typeof getPurchasingPlanning>>["data"]->[number];+export type PurchasingPlanningItem = Omit<+ NonNullable<+ Awaited<ReturnType<typeof getPurchasingPlanning>>["data"]+ >[number],+ keyof PlanningGridColumns+> &+ PlanningGridColumns;export type PurchasingRFQ = NonNullable<Awaited<ReturnType<typeof getPurchasingRFQs>>["data"]diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsxindex 2c19ff74fd..4443c45079 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx@@ -3,9 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { useRevalidator } from "@carbon/query";import {Button,- DatePicker,Drawer,DrawerBody,DrawerContent,@@ -14,14 +14,6 @@ import {DrawerHeader,DrawerTitle,HStack,- IconButton,- NumberDecrementStepper,- NumberField,- NumberIncrementStepper,- NumberInput,- NumberInputGroup,- NumberInputStepper,- Separator,Table as TableBase,Tabs,TabsContent,@@ -33,45 +25,97 @@ import {Thead,Tr,toast,- useDisclosure,- useMount,- VStack+ useDisclosure} from "@carbon/react";-import { getLocalTimeZone, parseDate, today } from "@internationalized/date";+import { formatDate, RoundingMode, round } from "@carbon/utils";+import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";-import { memo, useCallback, useEffect, useState } from "react";-import {- LuBlocks,- LuCalendar,- LuChevronDown,- LuChevronUp,- LuCircleCheck,- LuCirclePlay,- LuCirclePlus,- LuExternalLink,- LuPlus,- LuStar,- LuTrash2-} from "react-icons/lu";+import { useLocale } from "@react-aria/i18n";+import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { LuCircleCheck, LuCirclePlus, LuExternalLink } from "react-icons/lu";import { Link, useFetcher } from "react-router";import { SupplierAvatar } from "~/components";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";-import { useCurrencyFormatter, useRouteData } from "~/hooks";+import { useCurrencyFormatter, useQuantityFormatter } from "~/hooks";import type { SupplierPart } from "~/modules/items/types";import { SupplierPartForm } from "~/modules/items/ui/Item";import { getLinkToItemPlanning } from "~/modules/items/ui/Item/ItemForm";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";-import { ItemReorderPolicy } from "~/modules/items/ui/Item/ItemReorderPolicy";+import type { PlanningAction } from "~/modules/production";+import {+ type PlanningActionHandlers,+ reviewPathFor+} from "~/modules/production/ui/Planning/PlanningActionLines";+import {+ BeyondFenceButton,+ PlanningPolicySummary,+ periodIdFor+} from "~/modules/production/ui/Planning/PlanningDrawerParts";+import type {+ OpenOrderField,+ OpenOrderRow+} from "~/modules/production/ui/Planning/PlanningOrderGrids";+import {+ actionForOrder,+ DeferredDrawerSections,+ OpenOrdersGrid,+ SuggestedOrdersGrid+} from "~/modules/production/ui/Planning/PlanningOrderGrids";+import { chartedOrderQuantity } from "~/modules/production/ui/Planning/planning-increase";import type { action as bulkUpdateAction } from "~/routes/x+/purchasing+/planning.update";import { path } from "~/utils/path";-import type { PlannedOrder } from "../../purchasing.models";+import type {+ PlannedOrder,+ purchaseOrderStatusType+} from "../../purchasing.models";+import {+ isPurchaseOrderEditableFromPlanning,+ isPurchaseOrderLocked+} from "../../purchasing.models";import type { PurchasingPlanningItem } from "../../types";import { PurchasingStatus } from "../PurchaseOrder";+/** An existing PO line in the planned-order shape the chart reads, plus the+ * factor between its purchase units and inventory units, and the quantity it+ * was read at (so the chart can tell a planner's edit from the stored line). */+type OpenPurchaseOrder = PlannedOrder & {+ existingLineId: string;+ conversionFactor: number;+ /** Purchase units already received, on a line whose quantity is the ordered+ * total (an editable one); 0 on a sent line, which shows what is to come. */+ receivedOffset: number;+ loadedQuantity: number;+};+type PurchasingPlanningOrderDrawerProps = {+ /**+ * Today on the plant's calendar (the planning loader's `locationToday`).+ * Planned-order defaults are business dates there, and "late" is measured+ * from it, never from the planner's browser zone.+ */+ locationToday: string;isOpen: boolean;locationId: string;orders: PlannedOrder[];+ /** Suggested orders required AFTER the row's time fence. The drawer opens+ * without them; one button extends the fence to take them in. */+ beyondFenceOrders: PlannedOrder[];+ /** The row's time fence (ISO date), or null when it has none. */+ timeFenceDate: string | null;+ /** True when the fence was moved on screen, away from the saved horizon. */+ isTimeFenceOverridden: boolean;+ /** Move this row's fence without leaving the drawer — the same on-screen+ * override as the grid's Planning Horizon cell. `null` clears the fence+ * for this view. The suggested orders re-split around the new date. */+ onTimeFenceChange: (date: string | null) => void;+ /** The item's change actions on existing orders, inside the fence. Each one+ * is shown on the row of the order it targets. */+ actions: PlanningAction[];+ /** Apply / dismiss / reopen / assign, owned by the grid (one fetcher). */+ actionHandlers: PlanningActionHandlers;+ /** Bumped when a purchase order was reopened or finalized from the page:+ * the open orders are re-read, since no action of theirs changed. */+ ordersVersion?: number;periods: { id: string; startDate: string; endDate: string }[];selectedItem: PurchasingPlanningItem;selectedSupplier: string;@@ -86,122 +130,343 @@ export const PurchasingPlanningOrderDrawer = memo(selectedItem,setSelectedItem,orders,+ beyondFenceOrders,+ timeFenceDate,+ isTimeFenceOverridden,+ onTimeFenceChange,+ actions,+ actionHandlers,+ ordersVersion = 0,setOrders,locationId,periods,selectedSupplier,isOpen,onClose,- onSupplierChange+ onSupplierChange,+ locationToday}: PurchasingPlanningOrderDrawerProps) => {const { t } = useLingui();- // Planned-order defaults are business dates on the plant's calendar — use- // the loader's location-today, not the planner's browser zone.- const planningData = useRouteData<{ locationToday?: string }>(- path.to.purchasingPlanning- );- const locationToday =- planningData?.locationToday ?? today(getLocalTimeZone()).toString();+ const { locale } = useLocale();+ const fenceLabel = timeFenceDate+ ? formatDate(timeFenceDate, undefined, locale)+ : null;const fetcher = useFetcher<typeof bulkUpdateAction>();+ const { revalidate } = useRevalidator();const { carbon } = useCarbon();const formatter = useCurrencyFormatter();+ const formatQuantity = useQuantityFormatter();const unitOfMeasureOptions = useUnitOfMeasure();const [activeTab, setActiveTab] = useState("ordering");- const getExistingOrders = useCallback(async () => {- if (!carbon || !selectedItem.id) return;-- const { data: existingOrderData } = await carbon- ?.from("openPurchaseOrderLines")- .select("*")- .eq("itemId", selectedItem.id)- .in("status", [- "To Review",- "Needs Approval",- "Planned",- "To Receive",- "To Receive and Invoice",- "To Invoice"- ]);-- if (existingOrderData) {- const existingOrders: PlannedOrder[] = existingOrderData- .filter(- (order) =>- !orders.some((existing) => existing.existingLineId === order.id)- )- .map((order) => {- const dueDate = order.dueDate;-- if (- !dueDate ||- parseDate(dueDate) < parseDate(periods[0].startDate)- ) {- return {- existingId: order.purchaseOrderId ?? undefined,- existingLineId: order.id ?? undefined,- existingReadableId: order.purchaseOrderReadableId ?? undefined,- existingQuantity:- order.status === "Draft"- ? 0- : (order?.quantityToReceive ?? 0),- existingStatus: order.status ?? undefined,- startDate: order.orderDate ?? null,- dueDate: null,- quantity: order.quantityToReceive ?? 0,- periodId: periods[0].id,- supplierId: order.supplierId ?? undefined- };- }+ // ── Open orders: the item's existing PO lines ───────────────────────────+ // Held here, not in the grid's draft list: a cell edit on one of these is+ // SAVED (onSaveOpenOrder), where a suggested order is a draft until Order+ // is pressed. `null` while loading, an Error when the read failed.+ const [openOrders, setOpenOrders] = useState<+ OpenPurchaseOrder[] | null | Error+ >(null);- const period = periods.find((p) => {- const d = parseDate(dueDate!);- const startDate = parseDate(p.startDate);- const endDate = parseDate(p.endDate);- return d >= startDate && d <= endDate;- });-- return {- existingId: order.purchaseOrderId ?? undefined,- existingLineId: order.id ?? undefined,- existingReadableId: order.purchaseOrderReadableId ?? undefined,- existingQuantity:- order.status === "Draft" ? 0 : (order?.quantityToReceive ?? 0),- existingStatus: order.status ?? undefined,- startDate: order.orderDate ?? null,- dueDate: dueDate ?? null,- quantity: order.quantityToReceive ?? 0,- isASAP: false,- periodId: period?.id ?? periods[periods.length - 1].id,- supplierId: order.supplierId ?? undefined- };- });+ // Re-read when the item's actions change: applying one rewrites its line.+ const actionsKey = actions.map((a) => `${a.id}:${a.status}`).join(",");++ // Only while open: the drawer stays mounted on its last item so it can+ // slide out, and that item's actions change with every Apply on the grid.+ // biome-ignore lint/correctness/useExhaustiveDependencies: actionsKey stands in for `actions`; periods are fixed for the page+ useEffect(() => {+ if (!isOpen || !carbon || !selectedItem.id) return;+ let isCurrent = true;++ (async () => {+ const lines = await carbon+ .from("openPurchaseOrderLines")+ .select("*")+ .eq("itemId", selectedItem.id)+ // this page's location only: the rows are editable and charted here+ .eq("locationId", locationId)+ .in("status", [+ "To Review",+ "Needs Approval",+ "Planned",+ "To Receive",+ "To Receive and Invoice",+ "To Invoice"+ ]);+ if (!isCurrent) return;+ if (lines.error) {+ setOpenOrders(new Error(lines.error.message));+ return;+ }- // Backend now handles grouping items by supplier into single POs- // So we just need to merge the existing orders with current orders- setOrders(- selectedItem,- [...orders, ...existingOrders].sort((a, b) => {- return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;- })+ // The view reports the quantity in INVENTORY units; the cell edits the+ // line's own purchase quantity, so read that and its factor too.+ const lineIds = (lines.data ?? []).flatMap((line) =>+ line.id ? [line.id] : []+ );+ const details =+ lineIds.length > 0+ ? await carbon+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, quantityToReceive, quantityReceived, conversionFactor"+ )+ .in("id", lineIds)+ : { data: [], error: null };+ if (!isCurrent) return;+ if (details.error) {+ setOpenOrders(new Error(details.error.message));+ return;+ }+ const detailById = new Map(+ (details.data ?? []).map((detail) => [detail.id, detail]));- }- }, [carbon, selectedItem, orders, periods, setOrders]);- useMount(async () => {- if (selectedItem.id) {- getExistingOrders();+ setOpenOrders(+ (lines.data ?? [])+ .flatMap((line): OpenPurchaseOrder[] => {+ if (!line.id) return [];+ const detail = detailById.get(line.id);+ const isLocked = isPurchaseOrderLocked(line.status);+ // purchase units: what is still to come on a sent line, the+ // ordered quantity on one that can still be changed+ const quantity = Number(+ (isLocked+ ? detail?.quantityToReceive+ : detail?.purchaseQuantity) ?? 0+ );+ return [+ {+ existingId: line.purchaseOrderId ?? undefined,+ existingLineId: line.id,+ existingReadableId: line.purchaseOrderReadableId ?? undefined,+ // inventory units, as the chart's supply rows are+ existingQuantity:+ line.status === "Draft" ? 0 : (line.quantityToReceive ?? 0),+ existingStatus: line.status ?? undefined,+ startDate: line.orderDate ?? null,+ dueDate: line.dueDate ?? null,+ quantity,+ loadedQuantity: quantity,+ receivedOffset: isLocked+ ? 0+ : Number(detail?.quantityReceived ?? 0),+ periodId: periodIdFor(periods, line.dueDate),+ supplierId: line.supplierId ?? undefined,+ conversionFactor: Number(detail?.conversionFactor ?? 1) || 1+ }+ ];+ })+ .sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))+ );+ })();++ return () => {+ isCurrent = false;+ };+ }, [+ isOpen,+ carbon,+ selectedItem.id,+ locationId,+ actionsKey,+ ordersVersion+ ]);++ const openOrderRows = useMemo<OpenOrderRow[] | null | Error>(() => {+ if (!Array.isArray(openOrders)) return openOrders;++ const rows: OpenOrderRow[] = openOrders.map((order) => {+ const action = actionForOrder(+ actions,+ (a) => a.purchaseOrderLineId === order.existingLineId+ );+ return {+ id: order.existingLineId,+ documentPath: order.existingId+ ? path.to.purchaseOrderLine(order.existingId, order.existingLineId)+ : null,+ readableId: order.existingReadableId ?? "",+ status: order.existingStatus ?? null,+ quantity: order.quantity,+ dueDate: order.dueDate ?? null,+ // the server's gate: Draft / Planned only, not in approval or sent+ isEditable: isPurchaseOrderEditableFromPlanning(order.existingStatus),+ action,+ // the action's quantity is in inventory units and is what the line+ // must still bring; the row is in purchase units, rounded up to+ // whole units, plus what was received when the row shows the+ // ordered total — the quantity Apply writes+ suggestedQuantity: action+ ? order.receivedOffset ++ round(+ Number(action.suggestedQuantity) / order.conversionFactor,+ 0,+ RoundingMode.Up+ )+ : null,+ purchaseOrder: order.existingId+ ? {+ id: order.existingId,+ readableId: order.existingReadableId,+ status: order.existingStatus ?? null,+ // the view's orderDate is the PO's, read in as the start date+ orderDate: order.startDate ?? null+ }+ : null+ };+ });++ // An action whose order is not in the list still has to be shown — a+ // suggestion that silently drops out of the drawer reads as "nothing to+ // do". It gets a read-only row built from the action itself.+ for (const action of actions) {+ if (rows.some((row) => row.action?.id === action.id)) continue;+ rows.push({+ id: action.id,+ documentPath: reviewPathFor(action),+ readableId: action.purchaseOrderReadableId ?? "—",+ status: action.purchaseOrderStatus ?? null,+ quantity: null,+ dueDate: null,+ isEditable: false,+ action,+ suggestedQuantity: Number(action.suggestedQuantity)+ });}- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (selectedItem.id) {- getExistingOrders();- }- }, [selectedSupplier]);+ return rows;+ }, [openOrders, actions]);++ const onOpenOrdersChange = useCallback((rows: OpenOrderRow[]) => {+ setOpenOrders((previous) =>+ Array.isArray(previous)+ ? previous.map((order) => {+ const row = rows.find((r) => r.id === order.existingLineId);+ return row && row.quantity !== null+ ? { ...order, quantity: row.quantity, dueDate: row.dueDate }+ : order;+ })+ : previous+ );+ }, []);++ // One cell, one field, one request. The route re-reads the line under the+ // company and refuses a PO that has been sent, so a stale row here cannot+ // edit a committed order.+ const onSaveOpenOrder = useCallback(+ async (+ row: OpenOrderRow,+ field: OpenOrderField,+ value: number | string+ ) => {+ try {+ const response = await fetch(path.to.bulkUpdatePurchasingPlanning, {+ method: "post",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ action: "updateLine",+ locationId,+ line: { id: row.id, field, value }+ })+ });+ const result = (await response.json().catch(() => null)) as {+ success?: boolean;+ message?: string;+ } | null;+ if (response.ok && result?.success) {+ // A plain fetch bypasses the router: refresh the grid row behind+ // the drawer, which otherwise shows the old value until the next+ // navigation.+ void revalidate();+ return true;+ }+ toast.error(+ result?.message ?? t`Failed to update purchase order line`+ );+ return false;+ } catch {+ toast.error(t`Failed to update purchase order line`);+ return false;+ }+ },+ [locationId, revalidate, t]+ );++ const renderOpenOrderStatus = useCallback(+ (status: string) => (+ <PurchasingStatus+ iconOnly+ status={status as (typeof purchaseOrderStatusType)[number]}+ />+ ),+ []+ );++ // What the chart overlays as planned supply: the draft orders, plus the+ // open orders so an edit to one shows before MRP runs again — at its open+ // Increase, which took the place of a draft order. The chart reads+ // existing orders in inventory units (see mergePlannedOrders), and only+ // what is still to come: received units are already on hand.+ const chartOrders = useMemo<PlannedOrder[]>(+ () => [+ ...orders,+ ...(Array.isArray(openOrders)+ ? openOrders.map(+ ({+ conversionFactor,+ loadedQuantity,+ receivedOffset,+ ...order+ }) => ({+ ...order,+ quantity: chartedOrderQuantity({+ quantity:+ Math.max(order.quantity - receivedOffset, 0) *+ conversionFactor,+ loadedQuantity:+ Math.max(loadedQuantity - receivedOffset, 0) *+ conversionFactor,+ increase: actionForOrder(+ actions,+ (a) =>+ a.type === "Increase" &&+ a.purchaseOrderLineId === order.existingLineId+ )+ })+ })+ )+ : [])+ ],+ [orders, openOrders, actions]+ );++ // "N More After <fence>": move this row's fence out to the last suggested+ // order, rather than copying those orders into the list. The fence is the+ // one piece of state — the order list, the Action table below, and the+ // grid row's chips and quantity all follow it, so the pulled-in orders and+ // their Order actions appear together and stay in step.+ const lastBeyondFenceDate = useMemo(+ () =>+ beyondFenceOrders.reduce<string | null>(+ (latest, order) =>+ order.dueDate && (!latest || order.dueDate > latest)+ ? order.dueDate+ : latest,+ null+ ),+ [beyondFenceOrders]+ );++ const onIncludeBeyondFence = useCallback(() => {+ if (lastBeyondFenceDate) onTimeFenceChange(lastBeyondFenceDate);+ }, [lastBeyondFenceDate, onTimeFenceChange]);++ const onSuggestedOrdersChange = useCallback(+ (next: PlannedOrder[]) => setOrders(selectedItem, next),+ [selectedItem, setOrders]+ );const onAddOrder = useCallback(() => {if (selectedItem.id) {@@ -232,59 +497,28 @@ export const PurchasingPlanningOrderDrawer = memo(};setOrders(selectedItem, [...orders, newOrder]);}- }, [selectedItem, orders, setOrders, periods, selectedSupplier]);-- const onRemoveOrder = useCallback(- (index: number) => {- if (selectedItem.id) {- const newOrders = orders.filter((_, i) => i !== index);- setOrders(selectedItem, newOrders);- }- },- [selectedItem, orders, setOrders]- );+ }, [+ selectedItem,+ orders,+ setOrders,+ periods,+ selectedSupplier,+ locationToday+ ]);const onSubmit = useCallback((id: string, orders: PlannedOrder[]) => {- // Skip existing PO lines that are past the Planned stage — their- // quantity/due-date inputs are disabled in the UI, so the user can't- // have edited them, and we don't want the action to issue UPDATEs- // against already-shipped lines.- const editableOrders = orders.filter(- (order) =>- !order.existingLineId ||- order.existingStatus === "Draft" ||- order.existingStatus === "Planned"- );- const ordersWithPeriods = editableOrders.map((order) => {+ const ordersWithPeriods = orders.map((order) => {// Stamp the currently-selected supplier onto every order. Orders built- // by onAddOrder/getPurchaseOrdersFromPlanning may carry a null+ // by onAddOrder/plannedOrdersFromActions may carry a null// supplierId (e.g. the item has no preferredSupplierId), which the// server validator rejects as "No suppliers provided" — the Order// button already guards that selectedSupplier is set.const supplierId = selectedSupplier ?? order.supplierId;- if (- !order.dueDate ||- parseDate(order.dueDate) < parseDate(periods[0].startDate)- ) {- return {- ...order,- supplierId,- periodId: periods[0].id- };- }-- const period = periods.find((p) => {- const dueDate = parseDate(order.dueDate!);- const startDate = parseDate(p.startDate);- const endDate = parseDate(p.endDate);- return dueDate >= startDate && dueDate <= endDate;- });-return {...order,supplierId,- periodId: period?.id ?? periods[periods.length - 1].id+ periodId: periodIdFor(periods, order.dueDate)};});@@ -307,20 +541,6 @@ export const PurchasingPlanningOrderDrawer = memo([fetcher, locationId, periods, selectedSupplier]);- const onOrderUpdate = useCallback(- (index: number, updates: Partial<PlannedOrder>) => {- if (selectedItem.id) {- const newOrders = [...orders];- newOrders[index] = {- ...orders[index],- ...updates- };- setOrders(selectedItem, newOrders);- }- },- [selectedItem, orders, setOrders]- );-// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (fetcher.state !== "idle" || !fetcher.data) {@@ -539,23 +759,18 @@ export const PurchasingPlanningOrderDrawer = memo(</div></TabsContent><TabsContent value="ordering" className="flex flex-col gap-4">- <VStack spacing={2} className="text-sm border rounded-lg p-4">- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Reorder Policy:</Trans>- </span>- <ItemReorderPolicy- reorderingPolicy={selectedItem.reorderingPolicy}- />- </HStack>- <Separator />+ <PlanningPolicySummary+ item={selectedItem}+ fenceDate={timeFenceDate}+ isFenceOverridden={isTimeFenceOverridden}+ onFenceChange={onTimeFenceChange}+ ><HStack className="justify-between w-full"><span className="text-muted-foreground"><Trans>Supplier:</Trans></span><SupplierAvatar supplierId={selectedSupplier} /></HStack>- <Separator /><HStack className="justify-between w-full"><span className="text-muted-foreground"><Trans>Purchase Unit:</Trans>@@ -576,263 +791,71 @@ export const PurchasingPlanningOrderDrawer = memo(const supplier = (selectedItem.suppliers as SupplierPart[])?.find((s) => s.supplierId === selectedSupplier);- const conversionFactor = supplier?.conversionFactor ?? 1;- return conversionFactor !== 1 ? (+ const factor = supplier?.conversionFactor ?? 1;+ const conversionFactor = formatQuantity(factor);+ return factor !== 1 ? (<HStack className="justify-between w-full"><span className="text-muted-foreground"><Trans>Conversion:</Trans></span>- <span>1 Purchase = {conversionFactor} Inventory</span>- </HStack>- ) : null;- })()}- <Separator />- {selectedItem.reorderingPolicy === "Maximum Quantity" && (- <>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Reorder Point:</Trans>- </span>- <span>{selectedItem.reorderPoint}</span>- </HStack>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Maximum Inventory:</Trans>- </span>- <span>{selectedItem.maximumInventoryQuantity}</span>- </HStack>- </>- )}-- {selectedItem.reorderingPolicy ===- "Demand-Based Reorder" && (- <>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Accumulation Period:</Trans>- </span>- <span>- {selectedItem.demandAccumulationPeriod} weeks- </span>- </HStack>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Safety Stock:</Trans>- </span><span>- {selectedItem.demandAccumulationSafetyStock}- </span>- </HStack>- </>- )}-- {selectedItem.reorderingPolicy ===- "Fixed Reorder Quantity" && (- <>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Reorder Point:</Trans>- </span>- <span>{selectedItem.reorderPoint}</span>- </HStack>- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Reorder Quantity:</Trans>+ <Trans>+ 1 Purchase = {conversionFactor} Inventory+ </Trans></span>- <span>{selectedItem.reorderQuantity}</span></HStack>- </>- )}- {(selectedItem.lotSize > 0 ||- selectedItem.minimumOrderQuantity > 0 ||- selectedItem.maximumOrderQuantity > 0) && <Separator />}- {selectedItem.lotSize > 0 && (- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Lot Size:</Trans>- </span>- <span>{selectedItem.lotSize}</span>- </HStack>- )}- {selectedItem.minimumOrderQuantity > 0 && (- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Minimum Order:</Trans>- </span>- <span>{selectedItem.minimumOrderQuantity}</span>- </HStack>- )}- {selectedItem.maximumOrderQuantity > 0 && (- <HStack className="justify-between w-full">- <span className="text-muted-foreground">- <Trans>Maximum Order:</Trans>- </span>- <span>{selectedItem.maximumOrderQuantity}</span>- </HStack>- )}- </VStack>-- <TableBase full>- <Thead>- <Tr>- <Th>- <div className="flex items-center gap-2">- <LuCirclePlay />- <span>- <Trans>PO</Trans>- </span>- </div>- </Th>- <Th>- <div className="flex items-center gap-2 text-left">- <LuStar />- <span>- <Trans>Status</Trans>- </span>- </div>- </Th>- <Th>- <div className="flex items-center gap-2 text-right">- <LuBlocks />- <span>- <Trans>Purchase Qty</Trans>- </span>- </div>- </Th>- <Th>- <div className="flex items-center gap-2">- <LuCalendar />- <span>- <Trans>Due Date</Trans>- </span>- </div>- </Th>- <Th className="w-[50px]"></Th>- </Tr>- </Thead>- <Tbody>- {orders.map((order, index) => {- // Lock the row when (a) the selected supplier differs- // from the order's supplier, or (b) the existing PO- // line is past the Planned stage (already shipped /- // being received / being invoiced). Once committed- // to the supplier, mutating quantity or due date- // would desync the receiving workflow.- const isPostPlannedExisting =- !!order.existingLineId &&- order.existingStatus !== "Draft" &&- order.existingStatus !== "Planned";- const isDisabled =- (selectedSupplier !== order.supplierId &&- !!order.existingId) ||- isPostPlannedExisting;-- return (- <Tr key={index}>- <Td className="group-hover:bg-inherit justify-between">- {order.existingReadableId && order.existingId ? (- <Link- to={path.to.purchaseOrder(order.existingId)}- >- {order.existingReadableId}- </Link>- ) : (- t`New PO`- )}- </Td>- <Td className="flex flex-row items-center gap-1 group-hover:bg-inherit">- {/* @ts-expect-error - status is a string because we have a general type for purchase orders and purchaseOrderLines */}- <PurchasingStatus status={order.existingStatus} />- </Td>- <Td className="text-right group-hover:bg-inherit">- <NumberField- value={- isDisabled- ? order.existingQuantity- : order.quantity- }- isDisabled={isDisabled}- onChange={(value) => {- if (value) {- onOrderUpdate(index, {- quantity: value- });- }- }}- >- <NumberInputGroup className="relative group-hover:bg-inherit">- <NumberInput />- <NumberInputStepper>- <NumberIncrementStepper>- <LuChevronUp size="1em" strokeWidth="3" />- </NumberIncrementStepper>- <NumberDecrementStepper>- <LuChevronDown- size="1em"- strokeWidth="3"- />- </NumberDecrementStepper>- </NumberInputStepper>- </NumberInputGroup>- </NumberField>- </Td>- <Td className="text-right group-hover:bg-inherit">- <HStack className="justify-end">- <DatePicker- value={- order.dueDate- ? parseDate(order.dueDate)- : null- }- isDisabled={isDisabled}- onChange={(date) => {- onOrderUpdate(index, {- dueDate: date ? date.toString() : null- });- }}- />- </HStack>- </Td>- <Td className="group-hover:bg-inherit">- <IconButton- aria-label={t`Remove order`}- variant="ghost"- size="sm"- isDisabled={!!order.existingId}- onClick={() => onRemoveOrder(index)}- icon={<LuTrash2 className="text-destructive" />}- />- </Td>- </Tr>- );- })}- </Tbody>- </TableBase>-- <div>- <Button- variant="secondary"- size="sm"- className="mt-4"- leftIcon={<LuPlus />}- onClick={onAddOrder}- >- Add Order- </Button>- </div>-- <ItemPlanningChart- compact- itemId={selectedItem.id}- locationId={locationId}- safetyStock={selectedItem.demandAccumulationSafetyStock}- plannedOrders={orders}- conversionFactor={- (selectedItem.suppliers as SupplierPart[])?.find(- (s) => s.supplierId === selectedSupplier- )?.conversionFactor ?? 1- }- />+ ) : null;+ })()}+ </PlanningPolicySummary>++ <DeferredDrawerSections>+ <SuggestedOrdersGrid<PlannedOrder>+ title={<Trans>Suggested Orders</Trans>}+ titleAction={+ lastBeyondFenceDate &&+ timeFenceDate && (+ <BeyondFenceButton+ count={beyondFenceOrders.length}+ fenceLabel={fenceLabel}+ onClick={onIncludeBeyondFence}+ />+ )+ }+ orders={orders}+ leadTime={selectedItem.leadTime ?? 0}+ todayIso={locationToday}+ quantityHeader={t`Purchase Qty`}+ orderByHeader={t`Order By`}+ onChange={onSuggestedOrdersChange}+ onAdd={onAddOrder}+ />++ <OpenOrdersGrid+ title={<Trans>Open Orders</Trans>}+ documentHeader={t`PO`}+ quantityHeader={t`Qty`}+ rows={openOrderRows}+ todayIso={locationToday}+ renderStatusIcon={renderOpenOrderStatus}+ onSave={onSaveOpenOrder}+ onRowsChange={onOpenOrdersChange}+ {...actionHandlers}+ />++ <ItemPlanningChart+ compact+ itemId={selectedItem.id}+ locationId={locationId}+ safetyStock={selectedItem.demandAccumulationSafetyStock}+ timeFenceDate={timeFenceDate}+ plannedOrders={chartOrders}+ conversionFactor={+ (selectedItem.suppliers as SupplierPart[])?.find(+ (s) => s.supplierId === selectedSupplier+ )?.conversionFactor ?? 1+ }+ />+ </DeferredDrawerSections></TabsContent></div></DrawerBody>@@ -851,8 +874,8 @@ export const PurchasingPlanningOrderDrawer = memo(}onSubmit(selectedItem.id, orders);}}- disabled={fetcher.state !== "idle"}- isDisabled={fetcher.state !== "idle"}+ disabled={fetcher.state !== "idle" || orders.length === 0}+ isDisabled={fetcher.state !== "idle" || orders.length === 0}isLoading={fetcher.state !== "idle"}><Trans>Order</Trans>diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsxindex eea56d345e..f02ab4c690 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx@@ -12,7 +12,6 @@ import {DropdownMenuLabel,DropdownMenuSeparator,HStack,- Loading,PulsingDot,Status,Tooltip,@@ -21,90 +20,171 @@ import {toast,VStack} from "@carbon/react";-import { getLocalTimeZone, parseDate } from "@internationalized/date";+import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";-import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useEffect, useMemo, useState } from "react";import {- memo,- useCallback,- useDeferredValue,- useEffect,- useMemo,- useState-} from "react";-import {- LuBlocks,LuBookMarked,- LuBox,LuCircleCheck,LuCirclePlay,LuClock,LuContainer,- LuSquareChartGantt+ LuListTodo,+ LuSquareChartGantt,+ LuUserCheck} from "react-icons/lu";-import { Link, useFetcher } from "react-router";+import { Link, useFetcher, useSearchParams } from "react-router";import {+ EmployeeAvatarGroup,exportOnlyColumn,ItemThumbnail,- MethodItemTypeIcon,SupplierAvatar,Table} from "~/components";-import { Enumerable } from "~/components/Enumerable";+import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useLocations } from "~/components/Form/Location";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";-import { usePermissions } from "~/hooks";-import { inventoryItemTypes } from "~/modules/inventory/inventory.models";-import { itemReorderingPolicies } from "~/modules/items/items.models";+import {+ useLinkedDrawerItem,+ useMrpScheduleDescription,+ usePermissions,+ useQuantityFormatter,+ useUser+} from "~/hooks";import type { SupplierPart } from "~/modules/items/types";+import type { PlanningAction } from "~/modules/production";+import {+ PLANNING_ACTIONS_COLUMN,+ PLANNING_ASSIGNEE_COLUMN,+ PLANNING_DRAWER_PARAM+} from "~/modules/production";+import {+ isApplyablePlanningAction,+ isNewSupplyAction,+ PlanningActionLines,+ PlanningActionsCell,+ planningActionDot,+ planningActionsExportValue,+ usePlanningActionTypeOptions+} from "~/modules/production/ui/Planning/PlanningActionLines";import {- clearOrdersCache,- getPurchaseOrdersFromPlanning,- getReorderPolicyDescription,- ItemReorderPolicy-} from "~/modules/items/ui/Item/ItemReorderPolicy";+ openNewSupplyActions,+ plannedOrdersFromActions,+ supplierConversionFactor+} from "~/modules/production/ui/Planning/planned-orders-from-actions";+import { splitOrdersByFence } from "~/modules/production/ui/Planning/planning-fence";+import { planningColumns } from "~/modules/production/ui/Planning/planningColumns";+import { usePlanningActions } from "~/modules/production/ui/Planning/usePlanningActions";import type { action as mrpAction } from "~/routes/api+/mrp";import type { action as bulkUpdateAction } from "~/routes/x+/purchasing+/planning.update";-import { useItems } from "~/stores";+import { useItems, usePeople } from "~/stores";import { useSuppliers } from "~/stores/suppliers";import { path } from "~/utils/path";import type { PlannedOrder } from "../../purchasing.models";import type { PurchasingPlanningItem } from "../../types";import { PurchasingPlanningOrderDrawer } from "./PurchasingPlanningOrderDrawer";+import { usePurchaseOrderPlanningCommands } from "./usePurchaseOrderPlanningCommands";type PlanningTableProps = {data: PurchasingPlanningItem[];+ /** The row a `?item=` link opens the drawer on when it is not in `data`. */+ drawerItem: PurchasingPlanningItem | null;count: number;locationId: string;periods: { id: string; startDate: string; endDate: string }[];+ /** The persisted MRP worklist for the rows on this page (spec §P1.7),+ * rendered as the Actions column + each item's expanded row. Every action+ * is here whatever its date; the row's time fence decides what shows. */+ planningActions: PlanningAction[];+ /** The Actions-column filter in effect; null when the grid is not filtered+ * by action type. */+ actionTypes: string[] | null;+ /** Today on the location's calendar (ISO date). */+ locationToday: string;};const PlanningTable = memo(- ({ data, count, locationId, periods }: PlanningTableProps) => {- const { t } = useLingui();+ ({+ data,+ drawerItem,+ count,+ locationId,+ periods,+ planningActions,+ actionTypes,+ locationToday+ }: PlanningTableProps) => {+ const { t, i18n } = useLingui();const permissions = usePermissions();- const dateFormatter = useDateFormatter({- month: "short",- day: "numeric"- });-- const numberFormatter = useNumberFormatter();+ // Memoized on the locale, so it never rebuilds `columns` on its own.+ const formatQuantity = useQuantityFormatter();const locations = useLocations();const unitOfMeasures = useUnitOfMeasure();const [suppliers] = useSuppliers();+ const itemPostingGroups = useItemPostingGroups();const mrpFetcher = useAction<typeof mrpAction>({onSettled: (data) => {- if (data) {- clearOrdersCache();- setOrdersMap({}); // Reset local state to force recalculation- }+ // the drawer re-seeds from the new run's actions+ if (data) setOrdersMap({});}});+ const mrpScheduleDescription = useMrpScheduleDescription();const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();+ // What the order drawer can open on: the page's rows, plus the row a link+ // names when it is not on this page.+ const drawerRows = useMemo(+ () => (drawerItem ? [...data, drawerItem] : data),+ [data, drawerItem]+ );++ // ── Planning actions (the MRP worklist) ──────────────────────────────────+ const user = useUser();+ const canUpdateActions = permissions.can("update", "purchasing");+ const actionTypeOptions = usePlanningActionTypeOptions("Buy");+ const [people] = usePeople();+ const {+ actionHandlers: changeActionHandlers,+ isActionsBusy,+ timeFence,+ actionsByItemId,+ fencedActionsByItemId,+ visibleActionsByItemId,+ submitActions+ } = usePlanningActions({+ data: drawerRows,+ planningActions,+ actionTypes,+ locationId,+ updatePath: path.to.bulkUpdatePurchasingPlanning,+ currentUserId: user.id,+ canUpdate: canUpdateActions+ });++ // The purchase order's own commands (Reopen, Finalize) join each row's ⋯.+ const {+ purchaseOrderMenuItems,+ finalizePurchaseOrder,+ purchaseOrderDialogs,+ ordersVersion+ } = usePurchaseOrderPlanningCommands();+ // Releasing a planned PO is finalizing it: the Release button opens the+ // same modal as the ⋯ Finalize item.+ const onRelease = useCallback(+ (action: PlanningAction) => {+ if (action.purchaseOrderId)+ finalizePurchaseOrder(action.purchaseOrderId);+ },+ [finalizePurchaseOrder]+ );+ const actionHandlers = useMemo(+ () => ({ ...changeActionHandlers, purchaseOrderMenuItems, onRelease }),+ [changeActionHandlers, purchaseOrderMenuItems, onRelease]+ );+// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (bulkUpdateFetcher.state !== "idle" || !bulkUpdateFetcher.data) {@@ -119,6 +199,8 @@ const PlanningTable = memo(}if (bulkUpdateFetcher.data?.success === true) {+ // The drafts became PO lines; the next open re-seeds from the new split.+ setOrdersMap({});const purchaseOrders =(bulkUpdateFetcher.data as {@@ -172,7 +254,8 @@ const PlanningTable = memo(});- // Re-seed default suppliers whenever the planning rows change. The useState+ // Re-seed default suppliers whenever the planning rows (or a linked+ // drawer row) change. The useState// initializer above only runs once at mount, so an item that gained a// supplier after the page loaded — data revalidated after adding a supplier// part, running MRP, filtering, or an initially-empty list — would never get@@ -183,7 +266,7 @@ const PlanningTable = memo(setSuppliersMap((prev) => {const next = { ...prev };let changed = false;- for (const item of data) {+ for (const item of drawerRows) {if (next[item.id]) continue;const seed =item.preferredSupplierId ??@@ -195,48 +278,67 @@ const PlanningTable = memo(}return changed ? next : prev;});- }, [data]);+ }, [drawerRows]);const isDisabled =- !permissions.can("create", "production") ||+ !permissions.can("create", "purchasing") ||bulkUpdateFetcher.state !== "idle" ||mrpFetcher.state !== "idle";const [items] = useItems();+ // A row's suggested orders are its open Order actions: what MRP wrote+ // after it moved expedited supply, folded a shortfall into an open order+ // as an Increase, and summed each week. They seed the drawer, size the+ // Order button, and are what a bulk order submits for rows never opened.+ const plannedOrdersFor = useCallback(+ (row: PurchasingPlanningItem): PlannedOrder[] => {+ const supplierId = suppliersMap[row.id];+ const item = items.find((item) => item.id === row.id);+ return plannedOrdersFromActions(+ openNewSupplyActions(actionsByItemId.get(row.id), "Order"),+ {+ conversionFactor: supplierConversionFactor(+ row.suppliers,+ supplierId+ ),+ supplierId,+ itemReadableId: item?.readableIdWithRevision,+ description: item?.name,+ unitOfMeasureCode: item?.unitOfMeasureCode+ }+ );+ },+ [actionsByItemId, items, suppliersMap]+ );++ const ordersByItemId = useMemo(+ () => new Map(data.map((row) => [row.id, plannedOrdersFor(row)])),+ [data, plannedOrdersFor]+ );+// Store orders in a map keyed by item id - calculate on-demand instead of eagerlyconst [ordersMap, setOrdersMap] = useState<Record<string, PlannedOrder[]>>({});- // Auto-computed planned orders for every row, used as the fallback when- // bulk-submitting items the user never opened in the drawer.- // Computed from the rows and the supplier chosen for each, a render- // behind them so a large plan does not block typing; `isPending` covers- // the gap.- const deferredData = useDeferredValue(data);- const isPending = deferredData !== data;- const ordersByItemId = useMemo(() => {- const orders = new Map<string, PlannedOrder[]>();- for (const item of deferredData) {- orders.set(- item.id,- getPurchaseOrdersFromPlanning(- item,- periods,- items,- suppliersMap[item.id]- )- );- }- return orders;- }, [deferredData, periods, items, suppliersMap]);-- // Clear local state when data changes (e.g., filters, search)- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ // The drawer's draft orders are page state keyed by item. They are+ // dropped when the page's scope changes (location, filters, search, sort,+ // page) and when MRP recalculates (mrpFetcher above) or an order is placed+ // (below) — NOT on every reload of the loader: Apply, Dismiss and Assign+ // inside the drawer revalidate it, and that used to wipe the planner's+ // edits in the suggested-orders table above them.+ const [searchParams] = useSearchParams();+ // The open drawer is in the address too, and is not a change of scope.+ const pageScope = useMemo(() => {+ const scope = new URLSearchParams(searchParams);+ scope.delete(PLANNING_DRAWER_PARAM);+ return scope.toString();+ }, [searchParams]);+ // biome-ignore lint/correctness/useExhaustiveDependencies: the scope string is the dependencyuseEffect(() => {setOrdersMap({});- }, [data]);+ }, [pageScope]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback(@@ -250,8 +352,11 @@ const PlanningTable = memo();if (rowsWithoutSuppliers.length > 0) {+ const count = rowsWithoutSuppliers.length;toast.error(- `Cannot place order - ${rowsWithoutSuppliers.length} item(s) have no supplier associated`+ count === 1+ ? t`Cannot place the order — 1 item has no supplier`+ : t`Cannot place the order — ${count} items have no supplier`);}@@ -266,11 +371,19 @@ const PlanningTable = memo(.map((row) => {// Prefer user-edited orders (from the drawer) when present,// otherwise fall back to the auto-computed planned orders so- // bulk submit works for items the user never opened.+ // bulk submit works for items the user never opened. An item+ // opened and emptied in the drawer stays empty: removing every+ // suggestion is the planner's choice, not a reason to re-raise+ // them. The fallback stops at the row's time fence: a bulk order+ // raises what is due inside the planning horizon, not the whole+ // planning window.const sourceOrders =- ordersMap[row.id!] && ordersMap[row.id!]!.length > 0+ row.id! in ordersMap? ordersMap[row.id!]!- : (ordersByItemId.get(row.id!) ?? []);+ : splitOrdersByFence(+ ordersByItemId.get(row.id!) ?? [],+ timeFence.fenceDateFor(row)+ ).inside;const ordersWithPeriods = sourceOrders.map((order) => {const supplierId = suppliersMap[row.id!] ?? order.supplierId;if (@@ -312,11 +425,46 @@ const PlanningTable = memo(});},- [bulkUpdateFetcher, locationId, ordersMap, ordersByItemId, suppliersMap]+ [+ bulkUpdateFetcher,+ locationId,+ ordersMap,+ ordersByItemId,+ suppliersMap,+ t,+ timeFence+ ]);- const [selectedItem, setSelectedItem] =- useState<PurchasingPlanningItem | null>(null);+ // Moving a row's fence changes which suggested orders its drawer opens on.+ // The drawer's list is kept per item once opened (planner edits win), so a+ // stale list would neither show the newly included orders nor offer them —+ // drop it and let the drawer re-seed from the new split.+ const setFenceDate = timeFence.setFenceDate;+ const onFenceChange = useCallback(+ (itemId: string, date: string | null) => {+ setFenceDate(itemId, date);+ setOrdersMap((prev) => {+ if (!(itemId in prev)) return prev;+ const { [itemId]: _dropped, ...rest } = prev;+ return rest;+ });+ },+ [setFenceDate]+ );++ // The drawer stays mounted, on the last selected part, while it slides out.+ const {+ item: selectedItem,+ setItem: setSelectedItem,+ isOpen: isDrawerOpen,+ key: drawerKey,+ open: openDrawer,+ close: closeDrawer+ } = useLinkedDrawerItem({+ param: PLANNING_DRAWER_PARAM,+ rows: drawerRows+ });const setOrders = useCallback((item: PurchasingPlanningItem, orders: PlannedOrder[]) => {@@ -330,54 +478,57 @@ const PlanningTable = memo([]);+ // The drawer's own Planning Horizon control: the same on-screen override+ // as the grid cell, for the row the drawer is open on.+ const selectedItemId = selectedItem?.id;+ const onSelectedFenceChange = useCallback(+ (date: string | null) => {+ if (selectedItemId) onFenceChange(selectedItemId, date);+ },+ [selectedItemId, onFenceChange]+ );++ // The drawer's suggested orders, split at the selected row's time fence:+ // it opens on what is due inside the fence and can pull the rest in. A+ // shortfall MRP folded into an Increase on an existing PO line has no+ // Order action, so it is offered there, in Open Orders, and not here.+ const selectedOrders = useMemo(() => {+ if (!selectedItem?.id) return { inside: [], beyond: [] };+ return splitOrdersByFence(+ plannedOrdersFor(selectedItem),+ timeFence.fenceDateFor(selectedItem)+ );+ }, [selectedItem, plannedOrdersFor, timeFence]);++ // The drawer's Open Orders table shows the selected row's change actions on existing+ // orders (Expedite, Defer, Increase, …). Order / Make actions are left+ // out — each one is already a "New" row in the drawer's order list, right+ // above the table.+ const selectedActions = useMemo(+ () =>+ selectedItem?.id+ ? (fencedActionsByItemId.get(selectedItem.id) ?? []).filter(+ (action) => !isNewSupplyAction(action)+ )+ : [],+ [selectedItem, fencedActionsByItemId]+ );++ // The drawer's Open Orders rows carry the same Apply / Dismiss / Reopen /+ // Assign controls as the expanded row, through the same single fetcher.+// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst columns = useMemo<ColumnDef<PurchasingPlanningItem>[]>(() => {- const periodColumns: ColumnDef<PurchasingPlanningItem>[] = periods.map(- (period, index) => {- const isCurrentWeek = index === 0;- const weekNumber = index + 1;- const weekKey = `week${weekNumber}` as keyof PurchasingPlanningItem;- const startDate = parseDate(period.startDate).toDate(- getLocalTimeZone()- );- const endDate = parseDate(period.endDate).toDate(getLocalTimeZone());-- return {- accessorKey: weekKey,- header: () => (- <VStack spacing={0}>- <div>- {isCurrentWeek ? "Present Week" : `Week ${weekNumber}`}- </div>- <div className="text-xs text-muted-foreground">- {dateFormatter.format(startDate)} -{" "}- {dateFormatter.format(endDate)}- </div>- </VStack>- ),- cell: ({ row }) => {- const value = row.getValue<number>(weekKey);- if (value === undefined) return "-";- return (- <span- className={value < 0 ? "text-red-500 font-bold" : undefined}- >- {numberFormatter.format(value)}- </span>- );- },- meta: {- filterHeader: isCurrentWeek- ? t`Present Week`- : t`Week ${weekNumber}`,- exportValue: (row: PurchasingPlanningItem) => {- const value = row[weekKey] as number | undefined;- return value === undefined ? null : value;- }- }- };- }- );+ const shared = planningColumns<PurchasingPlanningItem>({+ i18n,+ periods,+ locationToday,+ formatQuantity,+ unitOfMeasures,+ itemPostingGroups,+ timeFence,+ onFenceChange+ });return [{@@ -386,8 +537,11 @@ const PlanningTable = memo(cell: ({ row }) => (<HStackclassName="py-1 cursor-pointer"- onClick={() => {- setSelectedItem(row.original);+ onClick={(event) => {+ // The row itself toggles its expanded actions on click; this+ // opens the drawer instead, so the click must not reach it.+ event.stopPropagation();+ openDrawer(row.original);}}><ItemThumbnail@@ -414,30 +568,73 @@ const PlanningTable = memo(value: (row) => row.name ?? null}),{- accessorKey: "unitOfMeasureCode",- header: "",+ id: PLANNING_ACTIONS_COLUMN,+ header: t`Actions`,cell: ({ row }) => (- <Enumerable- value={- unitOfMeasures.find(- (uom) => uom.value === row.original.unitOfMeasureCode- )?.label ?? null- }+ <PlanningActionsCell+ actions={visibleActionsByItemId.get(row.original.id) ?? []}/>),meta: {- filterHeader: t`Unit of Measure`,+ icon: <LuListTodo />,+ pluralHeader: t`Actions`,+ filter: {+ type: "static",+ options: actionTypeOptions+ },exportValue: (row: PurchasingPlanningItem) =>- unitOfMeasures.find((uom) => uom.value === row.unitOfMeasureCode)- ?.label ?? null+ planningActionsExportValue(+ visibleActionsByItemId.get(row.id) ?? []+ )}},+ {+ id: PLANNING_ASSIGNEE_COLUMN,+ header: t`Assignee`,+ cell: ({ row }) => (+ <EmployeeAvatarGroup+ employeeIds={[+ ...new Set(+ (visibleActionsByItemId.get(row.original.id) ?? []).flatMap(+ (action) => (action.assignee ? [action.assignee] : [])+ )+ )+ ]}+ />+ ),+ meta: {+ icon: <LuUserCheck />,+ pluralHeader: t`Assignees`,+ filter: {+ type: "static",+ options: people.map((employee) => ({+ value: employee.id,+ label: employee.name+ }))+ },+ exportValue: (row: PurchasingPlanningItem) =>+ [+ ...new Set(+ (visibleActionsByItemId.get(row.id) ?? []).flatMap(+ (action) => (action.assignee ? [action.assignee] : [])+ )+ )+ ]+ .map(+ (id) => people.find((person) => person.id === id)?.name ?? id+ )+ .join(", ")+ }+ },+ ...shared.periods,+ shared.reorderPolicy,{accessorKey: "preferredSupplierId",header: t`Supplier`,cell: ({ row }) => {const supplierId = suppliersMap[row.original.id];- if (!supplierId) return <Status color="red">No Supplier</Status>;+ if (!supplierId)+ return <Status color="red">{t`No Supplier`}</Status>;return <SupplierAvatar supplierId={supplierId} />;},@@ -452,6 +649,7 @@ const PlanningTable = memo(icon: <LuContainer />}},+ shared.unitOfMeasure,{accessorKey: "leadTime",header: t`Lead Time`,@@ -468,97 +666,22 @@ const PlanningTable = memo(icon: <LuClock />}},- {- accessorKey: "reorderingPolicy",- header: t`Reorder Policy`,- cell: ({ row }) => {- return (- <HStack>- <Tooltip>- <TooltipTrigger>- <ItemReorderPolicy- reorderingPolicy={row.original.reorderingPolicy}- />- </TooltipTrigger>- <TooltipContent>- {getReorderPolicyDescription(row.original)}- </TooltipContent>- </Tooltip>- </HStack>- );- },- meta: {- filter: {- type: "static",- options: itemReorderingPolicies.map((policy) => ({- label: <ItemReorderPolicy reorderingPolicy={policy} />,- value: policy- }))- },- icon: <LuCircleCheck />- }- },- {- accessorKey: "quantityOnHand",- header: t`On Hand`,- cell: ({ row }) =>- numberFormatter.format(row.original.quantityOnHand),- meta: {- icon: <LuBlocks />,- renderTotal: true- }- },- ...periodColumns,- {- accessorKey: "quantityToOrder",- header: t`Qty to Order`,- cell: ({ row }) => {- const value = row.original.quantityToOrder;- if (value === undefined || value === 0) return "-";- return (- <span className="font-medium">- {numberFormatter.format(value)}- </span>- );- },- meta: {- icon: <LuCirclePlay />- }- },- {- accessorKey: "type",- header: t`Type`,- cell: ({ row }) =>- row.original.type && (- <HStack>- <MethodItemTypeIcon type={row.original.type} />- <span>{row.original.type}</span>- </HStack>- ),- meta: {- filter: {- type: "static",- options: inventoryItemTypes- .filter((t) => ["Part", "Tool"].includes(t))- .map((type) => ({- label: (- <HStack spacing={2}>- <MethodItemTypeIcon type={type} />- <span>{type}</span>- </HStack>- ),- value: type- }))- },- icon: <LuBox />- }- },+ shared.onHand,+ shared.firstNegativeDate,+ shared.latestOrderDate,+ shared.timeFence,+ shared.type,+ shared.itemGroup,{id: "Order",header: "",cell: ({ row }) => {+ // only what is due inside the row's time fenceconst orders = row.original.id- ? (ordersByItemId.get(row.original.id) ?? [])+ ? splitOrdersByFence(+ ordersByItemId.get(row.original.id) ?? [],+ timeFence.fenceDateFor(row.original)+ ).inside: [];const orderQuantity = orders.reduce((acc, order) =>@@ -567,25 +690,34 @@ const PlanningTable = memo();const isBlocked = row.original.purchasingBlocked;const hasOrders = orders.length > 0 && orderQuantity > 0;+ const quantity = formatQuantity(orderQuantity);+ // An open action that adds or advances supply needs doing even with+ // nothing new to order (an Increase on an existing order), so it lights+ // the dot too; a Decrease, Defer or Cancel does not.+ const dot =+ planningActionDot(+ visibleActionsByItemId.get(row.original.id) ?? []+ ) ?? (hasOrders ? "green" : null);return (<div className="flex justify-end"><Buttonvariant="secondary"- leftIcon={hasOrders ? undefined : <LuCircleCheck />}+ leftIcon={dot ? undefined : <LuCircleCheck />}isDisabled={isDisabled || isBlocked}- onClick={() => {- setSelectedItem(row.original);+ onClick={(event) => {+ event.stopPropagation();+ openDrawer(row.original);}}>{isBlocked ? (- "Blocked"- ) : hasOrders ? (+ t`Blocked`+ ) : dot ? (<HStack>- <PulsingDot />- <span>Order {orderQuantity}</span>+ <PulsingDot variant={dot} />+ <span>{hasOrders ? t`Order ${quantity}` : t`Order`}</span></HStack>) : (- "Order"+ t`Order`)}</Button></div>@@ -594,21 +726,37 @@ const PlanningTable = memo(}];}, [+ t,+ i18n,suppliers,- dateFormatter,- numberFormatter,+ formatQuantity,unitOfMeasures,suppliersMap,- isDisabled+ isDisabled,+ visibleActionsByItemId,+ actionTypeOptions,+ people,+ itemPostingGroups,+ ordersByItemId,+ timeFence,+ locationToday// Note: ordersMap is intentionally not in deps to avoid column regeneration// getOrdersForItem inside the cell will access the latest ordersMap via closure]);const renderActions = useCallback((selectedRows: typeof data) => {+ // inside each row's time fence only — what the row is showing+ const applyableIds = selectedRows.flatMap((row) =>+ (visibleActionsByItemId.get(row.id) ?? [])+ .filter(isApplyablePlanningAction)+ .map((action) => action.id)+ );return (<DropdownMenuContent align="end" className="min-w-[200px]">- <DropdownMenuLabel>Update</DropdownMenuLabel>+ <DropdownMenuLabel>+ <Trans>Update</Trans>+ </DropdownMenuLabel><DropdownMenuSeparator /><DropdownMenuItem@@ -618,13 +766,59 @@ const PlanningTable = memo(<DropdownMenuIcon icon={<LuSquareChartGantt />} /><Trans>Order Parts</Trans></DropdownMenuItem>+ <DropdownMenuItem+ disabled={+ !canUpdateActions || applyableIds.length === 0 || isActionsBusy+ }+ onSelect={() =>+ submitActions({+ action: "apply",+ planningActionIds: applyableIds+ })+ }+ >+ <DropdownMenuIcon icon={<LuListTodo />} />+ <Trans>Apply Suggested Changes</Trans>+ {applyableIds.length > 0 && (+ <span className="ml-auto pl-3 text-xs text-muted-foreground tabular-nums">+ {applyableIds.length}+ </span>+ )}+ </DropdownMenuItem></DropdownMenuContent>);},- [bulkUpdateFetcher.state, onBulkUpdate]+ [+ bulkUpdateFetcher.state,+ onBulkUpdate,+ visibleActionsByItemId,+ canUpdateActions,+ isActionsBusy,+ submitActions+ ]+ );++ const canExpandRow = useCallback(+ (row: PurchasingPlanningItem) =>+ (visibleActionsByItemId.get(row.id)?.length ?? 0) > 0,+ [visibleActionsByItemId]+ );++ const renderExpandedRow = useCallback(+ (row: PurchasingPlanningItem) => (+ <PlanningActionLines+ actions={visibleActionsByItemId.get(row.id) ?? []}+ todayIso={locationToday}+ {...actionHandlers}+ onOrder={() => openDrawer(row)}+ />+ ),+ [visibleActionsByItemId, locationToday, actionHandlers, openDrawer]);const defaultColumnVisibility = {+ // carries the Assignee filter; the avatars are opt-in+ [PLANNING_ASSIGNEE_COLUMN]: false,active: false,type: false};@@ -635,7 +829,7 @@ const PlanningTable = memo(};return (- <Loading isLoading={isPending}>+ <><Table<PurchasingPlanningItem>count={count}columns={columns}@@ -669,15 +863,15 @@ const PlanningTable = memo(<Trans>Recalculate</Trans></Button></TooltipTrigger>- <TooltipContent>- MRP runs automatically every 3 hours, but you can run it- manually here.- </TooltipContent>+ <TooltipContent>{mrpScheduleDescription}</TooltipContent></Tooltip></mrpFetcher.Form></div>}renderActions={renderActions}+ renderExpandedRow={renderExpandedRow}+ pinExpandedRows+ canExpandRow={canExpandRow}title={t`Material Planning`}table="planning"withSavedView@@ -686,25 +880,28 @@ const PlanningTable = memo({selectedItem && (<PurchasingPlanningOrderDrawer+ key={drawerKey}+ locationToday={locationToday}locationId={locationId}selectedItem={selectedItem}setSelectedItem={setSelectedItem}selectedSupplier={suppliersMap[selectedItem.id]}orders={selectedItem.id- ? ordersMap[selectedItem.id] ||- getPurchaseOrdersFromPlanning(- selectedItem,- periods,- items,- suppliersMap[selectedItem.id]- )+ ? ordersMap[selectedItem.id] || selectedOrders.inside: []}+ beyondFenceOrders={selectedOrders.beyond}+ timeFenceDate={timeFence.fenceDateFor(selectedItem)}+ isTimeFenceOverridden={timeFence.isOverridden(selectedItem)}+ onTimeFenceChange={onSelectedFenceChange}+ actions={selectedActions}+ actionHandlers={actionHandlers}+ ordersVersion={ordersVersion}setOrders={setOrders}periods={periods}- isOpen={!!selectedItem}- onClose={() => setSelectedItem(null)}+ isOpen={isDrawerOpen}+ onClose={closeDrawer}onSupplierChange={(itemId, supplierId) => {setSuppliersMap((prev) => ({...prev,@@ -713,7 +910,8 @@ const PlanningTable = memo(}}/>)}- </Loading>+ {purchaseOrderDialogs}+ </>);});diff --git a/apps/erp/app/modules/purchasing/ui/Planning/usePurchaseOrderPlanningCommands.tsx b/apps/erp/app/modules/purchasing/ui/Planning/usePurchaseOrderPlanningCommands.tsxnew file mode 100644index 0000000000..973b0348e3--- /dev/null+++ b/apps/erp/app/modules/purchasing/ui/Planning/usePurchaseOrderPlanningCommands.tsx@@ -0,0 +1,191 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useLoaderQuery } from "@carbon/query";+import { DropdownMenuIcon, DropdownMenuItem } from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import { LuCheckCheck, LuGitBranchPlus, LuLoaderCircle } from "react-icons/lu";+import type { FetcherWithComponents } from "react-router";+import { useFetcher } from "react-router";+import Confirm from "~/components/Modals/Confirm/Confirm";+import { usePermissions } from "~/hooks";+import type { PlanningPurchaseOrder } from "~/modules/production/ui/Planning/planning-review";+import { purchaseOrderPlanningMenu } from "~/modules/production/ui/Planning/planning-review";+import type { loader as finalizeDefaultsLoader } from "~/routes/api+/purchasing.purchase-order.$id.finalize";+import { path } from "~/utils/path";+import { isPurchaseOrderLocked } from "../../purchasing.models";+import PurchaseOrderFinalizeModal from "../PurchaseOrder/PurchaseOrderFinalizeModal";++/**+ * The purchasing planning page's commands on a purchase order itself, offered+ * in the ⋯ menu of every row that names one (the expanded action lines and the+ * order drawer's Open Orders):+ *+ * Reopen / Reopen as Revision — a PO planning cannot change (in approval or+ * sent) goes back to PLANNED, not Draft: Draft is not MRP supply, so its+ * lines would leave the plan and the next run would suggest them again as+ * a new order. Planned is also what planning may change, so the row's+ * action turns from Review to Apply as soon as the page reloads.+ * Finalize — a Draft / Planned PO, through the PO page's own modal.+ *+ * Both post to the purchase order's own routes, which hold the permissions,+ * the approval rules and the revision bump; they redirect back here.+ */+export function usePurchaseOrderPlanningCommands(): {+ purchaseOrderMenuItems: (order: PlanningPurchaseOrder) => ReactNode;+ /** Opens the Finalize modal for a PO — a Release action's button. */+ finalizePurchaseOrder: (purchaseOrderId: string) => void;+ purchaseOrderDialogs: ReactNode;+ /** Bumped each time a command settles, so lists read from the database+ * (the drawer's open orders) re-read. */+ ordersVersion: number;+} {+ const { t } = useLingui();+ const permissions = usePermissions();+ const statusFetcher = useFetcher();+ const finalizeFetcher = useFetcher();+ const [revisionOrder, setRevisionOrder] =+ useState<PlanningPurchaseOrder | null>(null);+ const [finalizeOrderId, setFinalizeOrderId] = useState<string | null>(null);+ const [ordersVersion, setOrdersVersion] = useState(0);++ const isBusy =+ statusFetcher.state !== "idle" || finalizeFetcher.state !== "idle";++ // Once per settled command, not per state change.+ const wasBusy = useRef(false);+ useEffect(() => {+ if (isBusy) {+ wasBusy.current = true;+ } else if (wasBusy.current) {+ wasBusy.current = false;+ setOrdersVersion((version) => version + 1);+ }+ }, [isBusy]);++ const reopen = useCallback(+ (purchaseOrderId: string) => {+ statusFetcher.submit(+ { status: "Planned" },+ {+ method: "post",+ action: path.to.purchaseOrderStatus(purchaseOrderId)+ }+ );+ },+ [statusFetcher.submit]+ );++ const canUpdate = permissions.can("update", "purchasing");+ const canDelete = permissions.can("delete", "purchasing");+ const canCreate = permissions.can("create", "purchasing");++ const purchaseOrderMenuItems = useCallback(+ (order: PlanningPurchaseOrder) => {+ const menu = purchaseOrderPlanningMenu(order);+ if (!menu.canReopen && !menu.canFinalize) return null;+ // the status route's rule: reopening a SENT order needs delete+ const mayReopen = isPurchaseOrderLocked(order.status)+ ? canDelete+ : canUpdate;+ return (+ <>+ {menu.canReopen && (+ <DropdownMenuItem+ disabled={isBusy || !mayReopen}+ onSelect={() => reopen(order.id)}+ >+ <DropdownMenuIcon icon={<LuLoaderCircle />} />+ <Trans>Reopen</Trans>+ </DropdownMenuItem>+ )}+ {menu.canReopenAsRevision && (+ <DropdownMenuItem+ disabled={isBusy || !canDelete}+ onSelect={() => setRevisionOrder(order)}+ >+ <DropdownMenuIcon icon={<LuGitBranchPlus />} />+ <Trans>Reopen as Revision</Trans>+ </DropdownMenuItem>+ )}+ {menu.canFinalize && (+ <DropdownMenuItem+ disabled={isBusy || !canCreate}+ onSelect={() => setFinalizeOrderId(order.id)}+ >+ <DropdownMenuIcon icon={<LuCheckCheck />} />+ <Trans>Finalize</Trans>+ </DropdownMenuItem>+ )}+ </>+ );+ },+ [isBusy, reopen, canUpdate, canDelete, canCreate]+ );++ const revisionLabel = revisionOrder?.readableId ?? t`The purchase order`;+ const purchaseOrderDialogs = (+ <>+ {revisionOrder && (+ <Confirm+ action={path.to.purchaseOrderStatus(revisionOrder.id)}+ title={t`Reopen as Revision`}+ text={t`${revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order.`}+ confirmText={t`Create Revision`}+ onCancel={() => setRevisionOrder(null)}+ onSubmit={() => {+ setRevisionOrder(null);+ setOrdersVersion((version) => version + 1);+ }}+ >+ <input type="hidden" name="status" value="Planned" />+ <input type="hidden" name="createRevision" value="true" />+ </Confirm>+ )}+ {finalizeOrderId && (+ <PlanningFinalizeModal+ purchaseOrderId={finalizeOrderId}+ fetcher={finalizeFetcher}+ onClose={() => setFinalizeOrderId(null)}+ />+ )}+ </>+ );++ return {+ purchaseOrderMenuItems,+ finalizePurchaseOrder: setFinalizeOrderId,+ purchaseOrderDialogs,+ ordersVersion+ };+}++/** The PO page's finalize modal, with the order and default CC it reads from+ * that page's loader fetched instead. */+function PlanningFinalizeModal({+ purchaseOrderId,+ fetcher,+ onClose+}: {+ purchaseOrderId: string;+ fetcher: FetcherWithComponents<unknown>;+ onClose: () => void;+}) {+ const defaults = useLoaderQuery<typeof finalizeDefaultsLoader>(+ path.to.api.purchaseOrderFinalize(purchaseOrderId)+ );+ // The modal seeds its form from these on mount: wait for them.+ if (!defaults.data?.purchaseOrder) return null;+ return (+ <PurchaseOrderFinalizeModal+ purchaseOrderId={purchaseOrderId}+ purchaseOrder={defaults.data.purchaseOrder}+ defaultCc={defaults.data.defaultCc}+ fetcher={fetcher}+ onClose={onClose}+ />+ );+}diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsxindex c5ce6ac999..fa395a687d 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx@@ -99,6 +99,11 @@ export default function PurchaseOrderExplorer() {const isDisabled = isLocked? true: purchaseOrderData?.purchaseOrder?.status !== "Draft";+ // A Planned PO is one planning created and nobody has sent yet, so a line+ // can still come off it, the same as on a Draft.+ const isDeleteDisabled = !["Draft", "Planned"].includes(+ purchaseOrderData?.purchaseOrder?.status ?? ""+ );const lines = useMemo(() => purchaseOrderData?.lines ?? [],@@ -159,7 +164,7 @@ export default function PurchaseOrderExplorer() {lines.map((line) => (<PurchaseOrderLineItemkey={line.id}- isDisabled={isDisabled}+ isDeleteDisabled={isDeleteDisabled}line={line}onDelete={onDeleteLine}/>@@ -281,13 +286,13 @@ function PurchaseOrderLineBody({type PurchaseOrderLineItemProps = {line: PurchaseOrderLine;- isDisabled: boolean;+ isDeleteDisabled: boolean;onDelete: (line: PurchaseOrderLine) => void;};function PurchaseOrderLineItem({line,- isDisabled,+ isDeleteDisabled,onDelete}: PurchaseOrderLineItemProps) {const { t } = useLingui();@@ -386,7 +391,7 @@ function PurchaseOrderLineItem({shortcut={MENU_ITEM_SHORTCUTS.delete}destructivedisabled={- isDisabled || !permissions.can("delete", "purchasing")+ isDeleteDisabled || !permissions.can("delete", "purchasing")}onClick={(e) => {e.stopPropagation();diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsxindex 896728b765..9c2836f0e3 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx@@ -33,6 +33,9 @@ import type { PurchaseOrder } from "../../types";type PurchaseOrderFinalizeModalProps = {purchaseOrder?: PurchaseOrder;+ /** The order to finalize when the modal is opened away from its own page+ * (the planning pages); the route's `orderId` otherwise. */+ purchaseOrderId?: string;fetcher: FetcherWithComponents<unknown>;onClose: () => void;defaultCc?: string[];@@ -41,12 +44,14 @@ type PurchaseOrderFinalizeModalProps = {const PurchaseOrderFinalizeModal = ({purchaseOrder,+ purchaseOrderId,onClose,fetcher,defaultCc = [],resolvedAttachments = []}: PurchaseOrderFinalizeModalProps) => {- const { orderId } = useParams();+ const params = useParams();+ const orderId = purchaseOrderId ?? params.orderId;if (!orderId) throw new Error("orderId not found");const { t } = useLingui();diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchasingStatus.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchasingStatus.tsxindex 4f81bffa2c..84b51ec2cd 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchasingStatus.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchasingStatus.tsx@@ -8,31 +8,21 @@ import type { purchaseOrderStatusType } from "~/modules/purchasing";type PurchasingStatusProps = {status?: (typeof purchaseOrderStatusType)[number] | null;+ /** The status as its icon alone, with the name in a tooltip. */+ iconOnly?: boolean;};-const PurchasingStatus = ({ status }: PurchasingStatusProps) => {+const PurchasingStatus = ({ status, iconOnly }: PurchasingStatusProps) => {if (!status) return null;+ // Every status renders the same way; only its colour differs. An unknown+ // status (none today) has no colour and renders nothing, as before.const color = PURCHASE_ORDER_STATUS_COLOR_MAP[status];- switch (status) {- case "Draft":- return <Status color={color}>{status}</Status>;- case "Planned":- case "To Review":- case "Needs Approval":- return <Status color={color}>{status}</Status>;- case "To Receive":- case "To Receive and Invoice":- return <Status color={color}>{status}</Status>;- case "To Invoice":- return <Status color={color}>{status}</Status>;- case "Completed":- return <Status color={color}>{status}</Status>;- case "Closed":- case "Rejected":- return <Status color={color}>{status}</Status>;- default:- return null;- }+ if (!color) return null;+ return (+ <Status color={color} iconOnly={iconOnly}>+ {status}+ </Status>+ );};export default PurchasingStatus;diff --git a/apps/erp/app/modules/settings/AGENTS.md b/apps/erp/app/modules/settings/AGENTS.mdindex e95bcbe48e..8c44bdd98e 100644--- a/apps/erp/app/modules/settings/AGENTS.md+++ b/apps/erp/app/modules/settings/AGENTS.md@@ -62,6 +62,7 @@ pnpm run lint| `apiKey` | Hashed API keys with per-module scopes || `webhook` / `webhookTable` | Outbound webhooks and the tables they may subscribe to || `companyAccountsPayableBillingAddress` / `companyAccountsReceivableBillingAddress` | Remit-to / bill-to addresses printed on documents |+| `itemPostingGroupResponsibility` | Planning ownership: the responsible employee for an item group AT a location (`locationId`, `itemPostingGroupId`; UNIQUE `(companyId, locationId, itemPostingGroupId)`, the upsert's conflict target; RLS employee read, `settings_update` writes — `20261006130100`) — one rung of the MRP action owner ladder (see Planning below) || `employeeType` / `employeeTypePermission` / `employee` | Written only by `updateConsoleSetting` (now in the commercial `@carbon/ee/console.server`, gated to Business via the `PERMISSIONS` feature), which provisions a "Console Operator" type |## Key Service Functions@@ -77,6 +78,7 @@ pnpm run lint- `insertCompany` / `insertSubsidiary` / `updateSubsidiary` / `deleteSubsidiary` / `seedCompany` / `updateCompany` / `updateCompanyPlan`- `updateLogoLight|LightIcon|Dark|DarkIcon|Watermark` — store the storage path on `company`, not a URL (readers prefix it)- `listCompanyBackupFolders` / `deleteCompanyBackup` / `getCompanyRestoreRuns` / `getCompanyExportRun` (`backups.service.ts`); `exportCompanyBackup` (`backups.server.ts`, sends `carbon/company-export`); `getCompanyBackups` — the Backups loader's list, which computes each backup's live compatibility verdict via `@carbon/jobs/backups` — and the restore triggers live in `backups.server.ts`+- Planning (Settings → Planning, `x+/settings+/planning.tsx`, cards in `ui/Planning/`): `setRescheduleToleranceDays` / `setDefaultPlanningHorizonDays` / `setForecastConsumptionWindow` (`companySettings`), and the action owner ladder — `setDefaultResponsibleEmployee` (company), `setLocationResponsibleEmployee` (`location.responsibleEmployee`; returns the row, since a user without `resources_update` matches none under RLS and the route reports that), `upsertItemPostingGroupResponsibility` (item group at a location; updates in place so `createdBy` survives, inserts a new cell, and a null employee deletes the row), read back by `getItemPostingGroupResponsibilities`. The item rung is `itemPlanning.responsibleEmployee`, edited on the item. The scheduled MRP time is `updateMrpRunTimeSetting` (`companySettings.mrpRunTime`, null = every 3 hours), edited on the same page. Cards and intents: `ResponsibleEmployeeCard` (`setCompanyDefault` / `setLocation` / `setItemGroup`), `RescheduleToleranceCard` (`setTolerance`), `PlanningHorizonCard` (`setPlanningHorizon`), `ForecastConsumptionCard` (`setForecastConsumption`), `MrpScheduleCard` (`setMrpSchedule` → `updateMrpRunTimeSetting`); validators `mrpScheduleValidator`, `rescheduleToleranceValidator`, `planningHorizonValidator`, `forecastConsumptionValidator` (`settings.models.ts`; `settings.models.mrp-schedule.test.ts`). The `companySettings` columns: `defaultResponsibleEmployee`, `rescheduleToleranceDays` (default 7), `defaultPlanningHorizonDays` (null = no fence), `forecastConsumptionBackwardPeriods` / `forecastConsumptionForwardPeriods` (defaults 4 / 1), `mrpRunTime` (TIME; null = every 3 hours — `useMrpScheduleDescription` in `~/hooks` renders it). Nav: `useSettingsSubmodules.tsx` → `path.to.planningSettings` (`/x/settings/planning`).- `labelLogo.server.ts` — re-exports `resolveLabelLogo` from `@carbon/documents/labels` unchanged, and adds `getCompanyLogoForLabel`, which reads the company's logo storage paths fresh and expands them against `SUPABASE_INTERNAL_URL`; label routes (`file+/**/$id.labels[.]pdf|zpl`) feed that into `resolveLabelLogo` instead of `getCompany`'s public URLs (MES keeps its own copy at `apps/mes/app/services/labelLogo.server.ts`)## Document Previewdiff --git a/apps/erp/app/modules/settings/settings.models.mrp-schedule.test.ts b/apps/erp/app/modules/settings/settings.models.mrp-schedule.test.tsnew file mode 100644index 0000000000..fdca07dfd0--- /dev/null+++ b/apps/erp/app/modules/settings/settings.models.mrp-schedule.test.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// Isolation mock — see settings.models.sso.test.ts.+vi.mock("@carbon/content/glossary", () => ({+ getDefinitionText: vi.fn(),+ getEntry: vi.fn(),+ getTermText: vi.fn(),+ glossaryEntries: [],+ hasEntry: vi.fn(() => false),+ listEntries: vi.fn(() => []),+ lookupEntry: vi.fn(),+ termSlug: vi.fn(),+ terms: {}+}));++const { mrpScheduleValidator } = await import("./settings.models");++// The form used to carry only the hour, so a time set through the API (14:30)+// was saved back as 14:00 by a Save with no change.+describe("mrpScheduleValidator", () => {+ it("keeps a time that is not on the hour", () => {+ const result = mrpScheduleValidator.safeParse({+ mrpSchedule: "Daily",+ mrpRunTime: "14:30:00"+ });+ expect(result.success && result.data.mrpRunTime).toBe("14:30:00");+ });++ it("accepts a time without seconds", () => {+ expect(+ mrpScheduleValidator.safeParse({+ mrpSchedule: "Daily",+ mrpRunTime: "06:15"+ }).success+ ).toBe(true);+ });++ it("refuses a time that does not exist", () => {+ for (const mrpRunTime of ["24:00", "14:60", "7:00", "14"]) {+ expect(+ mrpScheduleValidator.safeParse({ mrpSchedule: "Daily", mrpRunTime })+ .success+ ).toBe(false);+ }+ });++ it("requires a time only for a daily run", () => {+ expect(+ mrpScheduleValidator.safeParse({ mrpSchedule: "Daily", mrpRunTime: "" })+ .success+ ).toBe(false);+ expect(+ mrpScheduleValidator.safeParse({+ mrpSchedule: "Every 3 Hours",+ mrpRunTime: ""+ }).success+ ).toBe(true);+ });+});diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex f54b07bf52..63e0f95e9d 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -240,6 +240,30 @@ export const jobCompletedValidator = z.object({salesJobCompletedNotificationGroup: z.array(z.string()).optional()});+export const mrpScheduleTypes = ["Every 3 Hours", "Daily"] as const;++// "Every 3 Hours" is the default cadence and ignores the time; "Daily" runs+// once a day at `mrpRunTime` on the company's own clock. The form offers whole+// hours, but the column (and the MCP tool) take any time — the cron checks+// every 15 minutes — so the field is the stored "HH:MM[:SS]" string, and a+// time like 14:30 saves back unchanged instead of being cut to 14:00.+export const mrpScheduleValidator = z+ .object({+ mrpSchedule: z.enum(mrpScheduleTypes),+ mrpRunTime: zfd.text(+ z+ .string()+ .regex(/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/, {+ message: "Choose a time"+ })+ .optional()+ )+ })+ .refine(+ (data) => data.mrpSchedule !== "Daily" || data.mrpRunTime !== undefined,+ { message: "Time is required", path: ["mrpRunTime"] }+ );+export const kanbanOutputValidator = z.object({kanbanOutput: z.enum(kanbanOutputTypes)});@@ -263,6 +287,21 @@ export const expiredEntityPolicies = ["BlockWithOverride"] as const;+// Planning settings (MRP suggestions). Whole days / whole weekly buckets.+export const rescheduleToleranceValidator = z.object({+ days: zfd.numeric(z.number().int().min(0).max(365))+});++// Empty clears the default: items without their own horizon then have no fence.+export const planningHorizonValidator = z.object({+ days: zfd.numeric(z.number().int().min(0).max(3650).optional())+});++export const forecastConsumptionValidator = z.object({+ backwardPeriods: zfd.numeric(z.number().int().min(0).max(52)),+ forwardPeriods: zfd.numeric(z.number().int().min(0).max(52))+});+// Every shelf-life knob lives inside the companySettings.inventoryShelfLife// JSONB blob. The validator below reads/writes that single object so the// settings form can submit one cohesive structure.diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 2a6f34a955..f319734cce 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -23,6 +23,7 @@ import {} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { serverFns } from "@carbon/server-functions";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import type { plmReleaseControl as plmReleaseControlOptions } from "~/modules/items/items.models";@@ -1494,6 +1495,22 @@ export async function updateAutoSelectMaterialWithoutPickingListSetting(.eq("id", companyId);}+/**+ * The time of day scheduled MRP runs, on the company's own clock ("HH:MM:SS").+ * `null` restores the default cadence, every 3 hours.+ * @mcp update+ */+export async function updateMrpRunTimeSetting(+ client: SupabaseClient<Database>,+ companyId: string,+ mrpRunTime: string | null+) {+ return client+ .from("companySettings")+ .update({ mrpRunTime })+ .eq("id", companyId);+}+/** @mcp update */export async function updateIncompletePickingListPolicySetting(client: SupabaseClient<Database>,@@ -1517,3 +1534,146 @@ export async function updateReturnPickedMaterialTimingSetting(.update(sanitize({ returnPickedMaterialTiming })).eq("id", companyId);}++// ── Planning ownership + tolerance (spec §P1.3 / §P1.6) ────────────────────+// The responsibleEmployee ladder's configurable rungs: company default →+// per-location → per-(location, item group). The item-group tier is+// LOCATION-SPECIFIC, stored sparsely in itemPostingGroupResponsibility — an+// inheritance tree (the printer AssignmentsCard model), never a matrix.++export async function getItemPostingGroupResponsibilities(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("itemPostingGroupResponsibility")+ .select("id, locationId, itemPostingGroupId, responsibleEmployee")+ .eq("companyId", companyId);+}++export async function setDefaultResponsibleEmployee(+ client: SupabaseClient<Database>,+ args: { companyId: string; employeeId: string | null }+) {+ return client+ .from("companySettings")+ .update({ defaultResponsibleEmployee: args.employeeId })+ .eq("id", args.companyId);+}++export async function setLocationResponsibleEmployee(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ locationId: string;+ employeeId: string | null;+ userId: string;+ }+) {+ // `location` is a resources table: without resources_update, row-level+ // security matches no row and the update succeeds having changed nothing.+ // Returning the row lets the caller tell the two apart.+ return client+ .from("location")+ .update({ responsibleEmployee: args.employeeId, updatedBy: args.userId })+ .eq("id", args.locationId)+ .eq("companyId", args.companyId)+ .select("id");+}++/**+ * Upsert one (location, item group) ownership cell; clearing the employee+ * DELETES the row (unset → inherit up the tree, matching printers).+ */+export async function upsertItemPostingGroupResponsibility(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ locationId: string;+ itemPostingGroupId: string;+ employeeId: string | null;+ userId: string;+ }+) {+ if (!args.employeeId) {+ return client+ .from("itemPostingGroupResponsibility")+ .delete()+ .eq("companyId", args.companyId)+ .eq("locationId", args.locationId)+ .eq("itemPostingGroupId", args.itemPostingGroupId);+ }+ // Update first, insert only when the cell is new: an upsert would restate+ // `createdBy` on every reassignment.+ const updated = await client+ .from("itemPostingGroupResponsibility")+ .update({+ responsibleEmployee: args.employeeId,+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .eq("companyId", args.companyId)+ .eq("locationId", args.locationId)+ .eq("itemPostingGroupId", args.itemPostingGroupId)+ .select("id");+ if (updated.error || (updated.data?.length ?? 0) > 0) return updated;+ return client+ .from("itemPostingGroupResponsibility")+ .insert({+ companyId: args.companyId,+ locationId: args.locationId,+ itemPostingGroupId: args.itemPostingGroupId,+ responsibleEmployee: args.employeeId,+ createdBy: args.userId+ })+ .select("id");+}++export async function setRescheduleToleranceDays(+ client: SupabaseClient<Database>,+ args: { companyId: string; days: number }+) {+ return client+ .from("companySettings")+ .update({ rescheduleToleranceDays: args.days })+ .eq("id", args.companyId);+}++/**+ * Whether a purchase order the planning pages raised skips the approval rule+ * when it is finalized (`purchaseOrder.createdFromPlanning`, cleared by any+ * manual line change). On by default.+ */+export async function setSkipApprovalForPlanningPurchaseOrders(+ client: SupabaseClient<Database>,+ args: { companyId: string; enabled: boolean }+) {+ return client+ .from("companySettings")+ .update({ skipApprovalForPlanningPurchaseOrders: args.enabled })+ .eq("id", args.companyId);+}++/** The company-wide planning horizon; `null` = no default (no time fence). */+export async function setDefaultPlanningHorizonDays(+ client: SupabaseClient<Database>,+ args: { companyId: string; days: number | null }+) {+ return client+ .from("companySettings")+ .update({ defaultPlanningHorizonDays: args.days })+ .eq("id", args.companyId);+}++export async function setForecastConsumptionWindow(+ client: SupabaseClient<Database>,+ args: { companyId: string; backwardPeriods: number; forwardPeriods: number }+) {+ return client+ .from("companySettings")+ .update({+ forecastConsumptionBackwardPeriods: args.backwardPeriods,+ forecastConsumptionForwardPeriods: args.forwardPeriods+ })+ .eq("id", args.companyId);+}diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsxindex 30cc684df4..873fcb71c8 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx@@ -270,12 +270,12 @@ const StatusBadge = ({ status }: { status: IntegrationHealthStatus }) => {} as const;const labels = {- healthy: t`healthy`,- unhealthy: t`unhealthy`,- inactive: t`inactive`,+ healthy: t`Healthy`,+ unhealthy: t`Unhealthy`,+ inactive: t`Inactive`,// Connected, but the accounting sync switch is off — a new connection// still being set up, or one switched off since.- "sync-off": t`sync off`+ "sync-off": t`Sync Off`} as const;const ping = colors[status] || "text-gray-400";diff --git a/apps/erp/app/modules/settings/ui/Planning/ForecastConsumptionCard.tsx b/apps/erp/app/modules/settings/ui/Planning/ForecastConsumptionCard.tsxnew file mode 100644index 0000000000..44e927c2a4--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/ForecastConsumptionCard.tsx@@ -0,0 +1,93 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { ValidatedForm } from "@carbon/form";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ toast+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect } from "react";+import { useFetcher } from "react-router";+import { Hidden, Number, Submit } from "~/components/Form";+import { forecastConsumptionValidator } from "~/modules/settings";++// The forecast consumption window (weekly buckets). Actual demand that lands+// in a week whose forecast is used up consumes forecast from up to+// `backward` weeks earlier, then `forward` weeks later, instead of being+// double-counted. 0 / 0 restricts netting to the same week.++export function ForecastConsumptionCard({+ backwardPeriods,+ forwardPeriods+}: {+ backwardPeriods: number;+ forwardPeriods: number;+}) {+ const { t } = useLingui();+ const fetcher = useFetcher<{ success: boolean; message: string }>();++ useEffect(() => {+ if (fetcher.state !== "idle" || !fetcher.data?.message) return;+ if (fetcher.data.success) {+ toast.success(fetcher.data.message);+ } else {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.state, fetcher.data]);++ return (+ <Card>+ <ValidatedForm+ method="post"+ validator={forecastConsumptionValidator}+ defaultValues={{ backwardPeriods, forwardPeriods }}+ fetcher={fetcher}+ >+ <Hidden name="intent" value="setForecastConsumption" />+ <CardHeader>+ <CardTitle>+ <Trans>Forecast Consumption</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ When a sales order or job lands in a week with no remaining+ forecast, it consumes forecast from nearby weeks instead of being+ counted on top of it. Set both to 0 to net within the same week+ only.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4 w-full max-w-[640px]">+ <Number+ name="backwardPeriods"+ label={t`Look back (weeks)`}+ minValue={0}+ maxValue={52}+ helperText={t`Earlier weeks are consumed first.`}+ />+ <Number+ name="forwardPeriods"+ label={t`Look ahead (weeks)`}+ minValue={0}+ maxValue={52}+ helperText={t`Later weeks are consumed once earlier ones are used up.`}+ />+ </div>+ </CardContent>+ <CardFooter>+ <Submit isDisabled={fetcher.state !== "idle"}>+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Planning/MrpScheduleCard.tsx b/apps/erp/app/modules/settings/ui/Planning/MrpScheduleCard.tsxnew file mode 100644index 0000000000..bc5de48432--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/MrpScheduleCard.tsx@@ -0,0 +1,130 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { ValidatedForm } from "@carbon/form";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ toast+} from "@carbon/react";+import { formatTimeOfDay } from "@carbon/utils";+import { parseTime, Time } from "@internationalized/date";+import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import { useEffect, useMemo, useState } from "react";+import { useFetcher } from "react-router";+import { Hidden, Select, Submit } from "~/components/Form";+import { useCompanyTimeZone } from "~/hooks";+import { mrpScheduleTypes, mrpScheduleValidator } from "~/modules/settings";++type MrpScheduleType = (typeof mrpScheduleTypes)[number];++// One settings card = one saved concern (archetype F): when MRP runs on its+// own. Every 3 hours, or once a day at `companySettings.mrpRunTime`.++export function MrpScheduleCard({+ mrpRunTime+}: {+ /** The stored "HH:MM:SS", or null for the 3-hourly default. */+ mrpRunTime: string | null;+}) {+ const { t } = useLingui();+ const { locale } = useLocale();+ const companyTimeZone = useCompanyTimeZone();+ const fetcher = useFetcher<{ success: boolean; message: string }>();+ const storedTime = mrpRunTime ? parseTime(mrpRunTime).toString() : null;+ const [schedule, setSchedule] = useState<MrpScheduleType>(+ storedTime ? "Daily" : "Every 3 Hours"+ );++ useEffect(() => {+ if (fetcher.state !== "idle" || !fetcher.data?.message) return;+ if (fetcher.data.success) {+ toast.success(fetcher.data.message);+ } else {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.state, fetcher.data]);++ const scheduleLabels: Record<MrpScheduleType, string> = {+ "Every 3 Hours": t`Every 3 hours`,+ Daily: t`Once a day`+ };++ // Whole hours, plus the stored time when it is not on the hour (set through+ // the API): offering only hours would save it back cut to the hour.+ const timeOptions = useMemo(() => {+ const times = Array.from({ length: 24 }, (_, hour) =>+ new Time(hour).toString()+ );+ if (storedTime && !times.includes(storedTime)) {+ times.push(storedTime);+ // "HH:MM:SS" strings sort chronologically+ times.sort();+ }+ return times.map((time) => ({+ value: time,+ label: formatTimeOfDay(time, locale)+ }));+ }, [storedTime, locale]);++ return (+ <Card>+ <ValidatedForm+ method="post"+ validator={mrpScheduleValidator}+ defaultValues={{+ mrpSchedule: storedTime ? "Daily" : "Every 3 Hours",+ mrpRunTime: storedTime ?? undefined+ }}+ fetcher={fetcher}+ >+ <Hidden name="intent" value="setMrpSchedule" />+ <CardHeader>+ <CardTitle>+ <Trans>MRP Schedule</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Choose when MRP recalculates on its own. You can still run it+ yourself at any time with Recalculate on the planning pages.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <Select+ name="mrpSchedule"+ label={t`Run MRP`}+ options={mrpScheduleTypes.map((type) => ({+ value: type,+ label: scheduleLabels[type]+ }))}+ onChange={(option) => {+ if (option) setSchedule(option.value as MrpScheduleType);+ }}+ />+ {schedule === "Daily" && (+ <Select+ name="mrpRunTime"+ label={t`Time of day`}+ helperText={t`In your company's time zone (${companyTimeZone}).`}+ options={timeOptions}+ />+ )}+ </div>+ </CardContent>+ <CardFooter>+ <Submit isDisabled={fetcher.state !== "idle"}>+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Planning/PlanningHorizonCard.tsx b/apps/erp/app/modules/settings/ui/Planning/PlanningHorizonCard.tsxnew file mode 100644index 0000000000..15d42ba294--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/PlanningHorizonCard.tsx@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { ValidatedForm } from "@carbon/form";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ toast+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect } from "react";+import { useFetcher } from "react-router";+import { Hidden, Number, Submit } from "~/components/Form";+import { planningHorizonValidator } from "~/modules/settings";++// One settings card = one saved concern (archetype F): the company-wide+// planning horizon (time fence). An item's own horizon on its Planning tab+// wins; an item with neither has no fence.++export function PlanningHorizonCard({+ defaultPlanningHorizonDays+}: {+ defaultPlanningHorizonDays: number | null;+}) {+ const { t } = useLingui();+ const fetcher = useFetcher<{ success: boolean; message: string }>();++ useEffect(() => {+ if (fetcher.state !== "idle" || !fetcher.data?.message) return;+ if (fetcher.data.success) {+ toast.success(fetcher.data.message);+ } else {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.state, fetcher.data]);++ return (+ <Card>+ <ValidatedForm+ method="post"+ validator={planningHorizonValidator}+ defaultValues={{ days: defaultPlanningHorizonDays ?? undefined }}+ fetcher={fetcher}+ >+ <Hidden name="intent" value="setPlanningHorizon" />+ <CardHeader>+ <CardTitle>+ <Trans>Planning Horizon</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Material planning shows only the actions and suggested orders due+ within this many days from today, so far-out needs stay out of the+ way until they matter. An item's own planning horizon overrides+ this default.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <Number+ name="days"+ label={t`Default horizon (days)`}+ minValue={0}+ maxValue={3650}+ helperText={t`Leave empty, or enter 0, to show everything MRP plans.`}+ />+ </div>+ </CardContent>+ <CardFooter>+ <Submit isDisabled={fetcher.state !== "idle"}>+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Planning/PlanningPurchaseOrderApprovalCard.tsx b/apps/erp/app/modules/settings/ui/Planning/PlanningPurchaseOrderApprovalCard.tsxnew file mode 100644index 0000000000..edd6491987--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/PlanningPurchaseOrderApprovalCard.tsx@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ HStack,+ Switch,+ toast,+ VStack+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { useEffect, useState } from "react";+import { useFetcher } from "react-router";++// One settings card = one saved concern (archetype F): whether purchase orders+// the planning pages raise skip the approval rule when they are finalized.++export function PlanningPurchaseOrderApprovalCard({+ skipApprovalForPlanningPurchaseOrders+}: {+ skipApprovalForPlanningPurchaseOrders: boolean;+}) {+ const fetcher = useFetcher<{ success: boolean; message: string }>();+ const [enabled, setEnabled] = useState(skipApprovalForPlanningPurchaseOrders);++ useEffect(() => {+ if (fetcher.state !== "idle" || !fetcher.data?.message) return;+ if (fetcher.data.success) {+ toast.success(fetcher.data.message);+ } else {+ // the switch moved before the save: put it back+ setEnabled(skipApprovalForPlanningPurchaseOrders);+ toast.error(fetcher.data.message);+ }+ }, [fetcher.state, fetcher.data, skipApprovalForPlanningPurchaseOrders]);++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Purchase Order Approval</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Purchase orders created from Material Planning can be finalized+ without going through the approval rule. Adding, changing or+ deleting a line on one by hand sends it back through approval.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <HStack className="justify-between items-center">+ <VStack className="items-start" spacing={1}>+ <span className="font-medium">+ {enabled ? (+ <Trans>Planning purchase orders skip approval</Trans>+ ) : (+ <Trans>Planning purchase orders need approval</Trans>+ )}+ </span>+ <span className="text-sm text-muted-foreground">+ {enabled ? (+ <Trans>+ An order raised from Material Planning is released as soon as+ it is finalized, without an approval request.+ </Trans>+ ) : (+ <Trans>+ An order raised from Material Planning follows the same+ approval rule as any other purchase order.+ </Trans>+ )}+ </span>+ </VStack>+ <Switch+ checked={enabled}+ disabled={fetcher.state !== "idle"}+ onCheckedChange={(checked) => {+ setEnabled(checked);+ fetcher.submit(+ {+ intent: "setPlanningPurchaseOrderApproval",+ enabled: checked.toString()+ },+ { method: "post" }+ );+ }}+ />+ </HStack>+ </CardContent>+ </Card>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Planning/RescheduleToleranceCard.tsx b/apps/erp/app/modules/settings/ui/Planning/RescheduleToleranceCard.tsxnew file mode 100644index 0000000000..89d8be1576--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/RescheduleToleranceCard.tsx@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { ValidatedForm } from "@carbon/form";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ toast+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect } from "react";+import { useFetcher } from "react-router";+import { Hidden, Number, Submit } from "~/components/Form";+import { rescheduleToleranceValidator } from "~/modules/settings";++// One settings card = one saved concern (archetype F): the reschedule+// tolerance MRP applies before it raises an Expedite / Defer suggestion.++export function RescheduleToleranceCard({+ rescheduleToleranceDays+}: {+ rescheduleToleranceDays: number;+}) {+ const { t } = useLingui();+ const fetcher = useFetcher<{ success: boolean; message: string }>();++ useEffect(() => {+ if (fetcher.state !== "idle" || !fetcher.data?.message) return;+ if (fetcher.data.success) {+ toast.success(fetcher.data.message);+ } else {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.state, fetcher.data]);++ return (+ <Card>+ <ValidatedForm+ method="post"+ validator={rescheduleToleranceValidator}+ defaultValues={{ days: rescheduleToleranceDays }}+ fetcher={fetcher}+ >+ <Hidden name="intent" value="setTolerance" />+ <CardHeader>+ <CardTitle>+ <Trans>Reschedule Tolerance</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ MRP suggests moving an existing order only when its date is off by+ more than this many days. Smaller gaps are left alone so the+ worklist stays quiet.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <Number+ name="days"+ label={t`Tolerance (days)`}+ minValue={0}+ maxValue={365}+ helperText={t`0 suggests a move for any date difference.`}+ />+ </div>+ </CardContent>+ <CardFooter>+ <Submit isDisabled={fetcher.state !== "idle"}>+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Planning/ResponsibleEmployeeCard.tsx b/apps/erp/app/modules/settings/ui/Planning/ResponsibleEmployeeCard.tsxnew file mode 100644index 0000000000..4e4f13e449--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/ResponsibleEmployeeCard.tsx@@ -0,0 +1,242 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Combobox,+ toast+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useCallback, useEffect, useMemo } from "react";+import { LuFactory, LuMapPin, LuTags } from "react-icons/lu";+import { useFetcher } from "react-router";+import { usePeople } from "~/stores";++// The responsibleEmployee ownership tree (spec §P1.3), configured the way+// printer assignments are (AssignmentsCard): company default → per-location →+// per-(location, item group). Unset rows show the value they inherit. Sparse:+// only configured cells persist; clearing a row returns it to inheritance.++type OwnershipUpdate = {+ intent: "setCompanyDefault" | "setLocation" | "setItemGroup";+ locationId?: string;+ itemPostingGroupId?: string;+ employeeId: string;+};++export function ResponsibleEmployeeCard({+ defaultResponsibleEmployee,+ locations,+ itemGroups,+ responsibilities+}: {+ defaultResponsibleEmployee: string | null;+ locations: { id: string; name: string; responsibleEmployee: string | null }[];+ itemGroups: { id: string; name: string }[];+ responsibilities: {+ locationId: string;+ itemPostingGroupId: string;+ responsibleEmployee: string | null;+ }[];+}) {+ const { t } = useLingui();+ const [people] = usePeople();+ const ownershipFetcher = useFetcher<{ success: boolean; message: string }>();++ const peopleOptions = useMemo(+ () => [+ { value: "", label: t`Unassigned` },+ ...people+ .filter((person) => person.active !== false)+ .map((person) => ({ value: person.id, label: person.name }))+ ],+ [people, t]+ );++ const personName = useCallback(+ (id: string | null | undefined) =>+ id ? (people.find((p) => p.id === id)?.name ?? null) : null,+ [people]+ );++ const responsibilityByCell = useMemo(() => {+ const map = new Map<string, string | null>();+ for (const row of responsibilities) {+ map.set(+ `${row.locationId}:${row.itemPostingGroupId}`,+ row.responsibleEmployee+ );+ }+ return map;+ }, [responsibilities]);++ // On every finished save, as the page's other cards do. Keyed on the+ // message, a second save answering with the same text showed nothing.+ useEffect(() => {+ if (ownershipFetcher.state !== "idle" || !ownershipFetcher.data?.message) {+ return;+ }+ if (ownershipFetcher.data.success) {+ toast.success(ownershipFetcher.data.message);+ } else {+ toast.error(ownershipFetcher.data.message);+ }+ }, [ownershipFetcher.state, ownershipFetcher.data]);++ const submitOwnership = useCallback(+ (update: OwnershipUpdate) => {+ const formData = new FormData();+ formData.set("intent", update.intent);+ if (update.locationId) formData.set("locationId", update.locationId);+ if (update.itemPostingGroupId) {+ formData.set("itemPostingGroupId", update.itemPostingGroupId);+ }+ formData.set("employeeId", update.employeeId);+ ownershipFetcher.submit(formData, { method: "POST" });+ },+ [ownershipFetcher]+ );++ const companyDefaultName = personName(defaultResponsibleEmployee);++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Planning Ownership</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Who owns MRP planning actions. Locations inherit the company+ default; item groups inherit their location. The most specific+ assignment wins, and each item can override on its Planning tab.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col">+ <OwnershipRow+ label={t`Company default`}+ icon={<LuFactory />}+ isBold+ value={defaultResponsibleEmployee}+ inheritedName={null}+ options={peopleOptions}+ onChange={(employeeId) =>+ submitOwnership({ intent: "setCompanyDefault", employeeId })+ }+ />+ {locations.map((location) => {+ const locationInheritedName =+ personName(location.responsibleEmployee) ?? companyDefaultName;+ return (+ <div+ key={location.id}+ className="border-t border-border mt-1 pt-1"+ >+ <OwnershipRow+ label={location.name}+ icon={<LuMapPin />}+ isBold+ value={location.responsibleEmployee}+ inheritedName={companyDefaultName}+ options={peopleOptions}+ onChange={(employeeId) =>+ submitOwnership({+ intent: "setLocation",+ locationId: location.id,+ employeeId+ })+ }+ />+ {itemGroups.map((group) => (+ <OwnershipRow+ key={group.id}+ label={group.name}+ icon={<LuTags />}+ isIndented+ value={+ responsibilityByCell.get(`${location.id}:${group.id}`) ??+ null+ }+ inheritedName={locationInheritedName}+ options={peopleOptions}+ onChange={(employeeId) =>+ submitOwnership({+ intent: "setItemGroup",+ locationId: location.id,+ itemPostingGroupId: group.id,+ employeeId+ })+ }+ />+ ))}+ </div>+ );+ })}+ </div>+ </CardContent>+ </Card>+ );+}++function OwnershipRow({+ label,+ icon,+ isBold,+ isIndented,+ value,+ inheritedName,+ options,+ onChange+}: {+ label: string;+ icon: ReactNode;+ isBold?: boolean;+ isIndented?: boolean;+ value: string | null;+ inheritedName: string | null;+ options: { value: string; label: string }[];+ onChange: (employeeId: string) => void;+}) {+ const { t } = useLingui();+ const placeholder = value+ ? undefined+ : inheritedName+ ? t`inherits ${inheritedName}`+ : t`Unassigned`;++ return (+ <div+ className={`flex items-center justify-between py-2.5 ${isIndented ? "pl-7" : ""} ${!isBold ? "border-t border-border/50" : ""}`}+ >+ <div className="flex items-center gap-2">+ <div className="size-7 bg-muted rounded-lg flex items-center justify-center shrink-0">+ <span className="size-4 text-muted-foreground">{icon}</span>+ </div>+ <span+ className={`text-sm ${isBold ? "font-medium" : "text-muted-foreground"}`}+ >+ {label}+ </span>+ </div>++ <div className="w-[320px]">+ <Combobox+ size="sm"+ value={value ?? ""}+ options={options}+ onChange={(selected) => onChange(selected)}+ isClearable+ placeholder={placeholder}+ />+ </div>+ </div>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Planning/index.ts b/apps/erp/app/modules/settings/ui/Planning/index.tsnew file mode 100644index 0000000000..51bf776aaa--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Planning/index.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++export { ForecastConsumptionCard } from "./ForecastConsumptionCard";+export { MrpScheduleCard } from "./MrpScheduleCard";+export { PlanningHorizonCard } from "./PlanningHorizonCard";+export { PlanningPurchaseOrderApprovalCard } from "./PlanningPurchaseOrderApprovalCard";+export { RescheduleToleranceCard } from "./RescheduleToleranceCard";+export { ResponsibleEmployeeCard } from "./ResponsibleEmployeeCard";diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex 314212a3b5..7cce261743 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -7,6 +7,7 @@ import { useMemo } from "react";import {LuBlocks,LuBox,+ LuCalendarClock,LuCircleCheck,LuClipboardCheck,LuCreditCard,@@ -124,6 +125,12 @@ export default function useSettingsSubmodules() {role: "employee",icon: <LuUsers />},+ {+ name: t`Planning`,+ to: path.to.planningSettings,+ role: "employee",+ icon: <LuCalendarClock />+ },{name: t`Purchasing`,to: path.to.purchasingSettings,diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.tsindex cb65a8d9fd..8dea40218b 100644--- a/apps/erp/app/modules/shared/shared.server.ts+++ b/apps/erp/app/modules/shared/shared.server.ts@@ -668,6 +668,38 @@ export async function requireCompanyRecord(}}+/**+ * Whether `userId` is an ACTIVE employee of `companyId` — the check every+ * user-id field that names a person in the company needs before it is saved+ * (a planning action's assignee, a responsible employee). Those columns+ * reference the global `user` table, so the database accepts anyone's id,+ * including a person from another company or one since deactivated. One query;+ * a failed read is logged and answered false (fail closed).+ */+export async function isActiveCompanyEmployee(+ client: SupabaseClient<Database>,+ companyId: string,+ userId: string+): Promise<boolean> {+ const { data, error } = await client+ .from("employee")+ .select("id")+ .eq("id", userId)+ .eq("companyId", companyId)+ .eq("active", true)+ .maybeSingle();++ if (error) {+ logger.error("Failed to verify employee for company", {+ companyId,+ userId,+ error+ });+ return false;+ }+ return data !== null;+}+/** `quoteLine` → `quote line`, for a message a person reads. */function recordName(table: string): string {return table.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();diff --git a/apps/erp/app/routes/api+/integrations.ramp.oauth.ts b/apps/erp/app/routes/api+/integrations.ramp.oauth.tsindex 161841abf8..1bdeef48c8 100644--- a/apps/erp/app/routes/api+/integrations.ramp.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.ramp.oauth.ts@@ -16,7 +16,7 @@ import {resolveConnectedProviderName} from "@carbon/ee/ramp.server";import { getLogger } from "@carbon/logger";-import { redirectExternal } from "@carbon/utils";+import { isUniqueViolation, redirectExternal } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import type { IntegrationErrorCode } from "~/modules/settings/integration-errors";import { integrationErrorSearch } from "~/modules/settings/integration-errors";@@ -179,10 +179,7 @@ export async function loader({ request }: LoaderFunctionArgs) {// The one-active-per-role trigger raises 23505. Ramp's authorization// already succeeded at this point, so the honest report is "another spend// integration holds the slot", not a generic save failure.- if (- typeof (error as { code?: unknown })?.code === "string" &&- (error as { code: string }).code === "23505"- ) {+ if (isUniqueViolation(error)) {logger.error("Ramp connect refused — a spend integration is active", {companyId});diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.tsindex 1a068f6515..6ae61fcd14 100644--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts@@ -208,9 +208,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {})]);+ // Merge planner-authored projections into the forecast series, NET of MRP+ // forecast consumption: the planning RPCs' demand_data counts+ // GREATEST(forecastQuantity - consumedQuantity, 0) per projection, and the+ // chart must agree with the grid. Netting happens here, before the shared+ // merge, so mergeDemandProjections stays a plain per-period merge.+ const netProjections = demand.projections.map(+ ({ consumedQuantity, ...projection }) => ({+ ...projection,+ forecastQuantity: Math.max(+ (projection.forecastQuantity ?? 0) - (consumedQuantity ?? 0),+ 0+ )+ })+ );const demandForecast = mergeDemandProjections(demand.forecasts,- demand.projections,+ netProjections,periods.map((p) => p.id ?? ""));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.jsonindex 6d27658d29..9b3c7a7505 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": 1484,+ "totalTools": 1485,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -248,7 +248,7 @@{"name":"inventory_getTrackedEntity","classification":"READ","paramCount":1,"schema":"5d58d420052a","response":"d485710baf81","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getTrackedEntityExpirations","classification":"READ","paramCount":1,"schema":"2d3f4e6f5875","response":"fff84b1ee888","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getUnresolvedPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"ce45e49e333f","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getWarehouseTransfer","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"45af922ea324","injectAuth":"companyId","permission":"inventory:view","paginates":false},+ {"name":"inventory_getWarehouseTransfer","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"2234f62ec519","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getWarehouseTransferLine","classification":"READ","paramCount":2,"schema":"31f24bda931b","response":"945dc2c1255f","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getWarehouseTransferLines","classification":"READ","paramCount":1,"schema":"d51f098ead24","response":"8a92aaed64aa","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getWarehouseTransfers","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"66ec9f5f0ca8","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},@@ -408,11 +408,11 @@{"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"37830a1bad13","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemCustomerPart","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4c6e08919580","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemCustomerParts","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"458a8cdb47f2","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"fe98aa635e85","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"20b38721b145","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemFiles","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"ffefd03548aa","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemManufacturing","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemMpnsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3ff28fd20707","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemPlanning","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"dd5cfe4cf204","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getItemPlanning","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"435390ae7550","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemPostingGroup","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"d38ff3570b60","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemPostingGroups","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"5019b8dab137","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},{"name":"items_getItemPostingGroupsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"parts:view","paginates":false},@@ -518,7 +518,7 @@{"name":"items_upsertItemCost","classification":"WRITE","paramCount":5,"schema":"ec5d1c8dde0d","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},{"name":"items_upsertItemCustomerPart","classification":"WRITE","paramCount":5,"schema":"cde0dd9223dd","response":"3797626bd17e","injectAuth":"companyId","permission":"parts:create+update","paginates":false},{"name":"items_upsertItemManufacturing","classification":"WRITE","paramCount":6,"schema":"23bfb7b15eab","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},- {"name":"items_upsertItemPlanning","classification":"WRITE","paramCount":12,"schema":"437b38df79d5","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"itemPlanning(itemId,locationId)"},+ {"name":"items_upsertItemPlanning","classification":"WRITE","paramCount":14,"schema":"df41fcd1ce4f","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"itemPlanning(itemId,locationId)"},{"name":"items_upsertItemPostingGroup","classification":"WRITE","paramCount":4,"schema":"c20041c48790","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"items_upsertItemPurchasing","classification":"WRITE","paramCount":5,"schema":"a2cbed8e5d35","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},{"name":"items_upsertItemSupersession","classification":"DESTRUCTIVE","paramCount":8,"schema":"e50423246d68","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},@@ -656,7 +656,7 @@{"name":"production_getCapacityReservationsForResources","classification":"READ","paramCount":2,"schema":"c0f9784197a0","response":"fc576887f258","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getCompletionJobs","classification":"READ","paramCount":4,"schema":"205595d8458d","response":"c26a96dae780","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getDemandForecasts","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"21892ee9e3b8","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getDemandProjections","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"3f9a097c510e","injectAuth":"companyId","permission":"production:view","paginates":false},+ {"name":"production_getDemandProjections","classification":"READ","paramCount":3,"schema":"c24ad31f1eaa","response":"f963e0e91868","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getFailureMode","classification":"READ","paramCount":1,"schema":"4a3e0384d72f","response":"2f49c8d39495","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getFailureModes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"6fe6b1e0f957","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},{"name":"production_getFailureModesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"production:view","paginates":false},@@ -731,7 +731,7 @@{"name":"production_getProductionEventsByJob","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"0c36813c32a1","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getProductionEventsByOperations","classification":"READ","paramCount":1,"schema":"0715cdbaa5fb","response":"acc5e1d1e2c9","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getProductionEventsPage","classification":"READ","paramCount":3,"schema":"d3ce152358d0","response":"d82d26b306e9","injectAuth":"companyId","permission":"production:view","paginates":true},- {"name":"production_getProductionPlanning","classification":"READ","paramCount":3,"schema":"c3afb01f3040","response":"684c3b20f68c","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},+ {"name":"production_getProductionPlanning","classification":"READ","paramCount":3,"schema":"4d6e5e2b1875","response":"70236c14db92","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},{"name":"production_getProductionProjections","classification":"READ","paramCount":3,"schema":"c3afb01f3040","response":"4973a62dfd1b","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},{"name":"production_getProductionQuantities","classification":"READ","paramCount":2,"schema":"91c6f90c1d2d","response":"3b4cf7a6bc87","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},{"name":"production_getProductionQuantity","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"c506c8c71d8f","injectAuth":"companyId","permission":"production:view","paginates":false},@@ -873,8 +873,8 @@{"name":"purchasing_getPurchaseReturnOrderLineTrackedEntities","classification":"READ","paramCount":1,"schema":"749e5d81384a","response":"75ed48edf5c1","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getPurchaseReturnOrders","classification":"READ","paramCount":5,"schema":"f3468ea9b0a6","response":"de438833d869","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},{"name":"purchasing_getPurchaseReturnOrderShipments","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"08e1b6f03862","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingDocumentsAssignedToMe","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0f0173c85a86","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getPurchasingPlanning","classification":"READ","paramCount":3,"schema":"c3afb01f3040","response":"0cd4f8e33cdc","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},+ {"name":"purchasing_getPurchasingDocumentsAssignedToMe","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"cb047e0da459","injectAuth":"companyId","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getPurchasingPlanning","classification":"READ","paramCount":3,"schema":"4d6e5e2b1875","response":"e09989d16685","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},{"name":"purchasing_getPurchasingRFQ","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"08cb90c207da","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getPurchasingRFQLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"045f66457f11","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getPurchasingRFQLines","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"24a761144b4a","injectAuth":"companyId","permission":"purchasing:view","paginates":false},@@ -924,7 +924,7 @@{"name":"purchasing_insertSupplierContact","classification":"WRITE","paramCount":4,"schema":"987f8dd2f02d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplierLocation","classification":"WRITE","paramCount":4,"schema":"c903cae736f0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplierQuote","classification":"WRITE","paramCount":13,"schema":"aa8560bfb767","response":"77e21c1e2e32","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},- {"name":"purchasing_reopenPurchaseOrderAsRevision","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"cddf8275afa1","injectAuth":"companyId","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_reopenPurchaseOrderAsRevision","classification":"WRITE","paramCount":2,"schema":"ffa38ce5274f","response":"cddf8275afa1","injectAuth":"companyId","permission":"purchasing:update","paginates":false},{"name":"purchasing_reopenPurchaseReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"purchasing:update","paginates":false},{"name":"purchasing_sendSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},{"name":"purchasing_setPurchaseReturnOrderLineTrackedEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"f3f13d81cd8c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},@@ -1074,8 +1074,8 @@{"name":"resources_getFailureMode","classification":"READ","paramCount":1,"schema":"4a3e0384d72f","response":"2f49c8d39495","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getFailureModes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"6fe6b1e0f957","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},{"name":"resources_getFailureModesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"5fe568931f57","injectAuth":"companyId","permission":"resources:view","paginates":false},- {"name":"resources_getLocations","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7df90335f683","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},+ {"name":"resources_getLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"99dfd44b4c2e","injectAuth":"companyId","permission":"resources:view","paginates":false},+ {"name":"resources_getLocations","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cf3608cc2732","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},{"name":"resources_getLocationsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"e19c89c1e8a0","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getMaintenanceDispatch","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"5547ae49213e","injectAuth":"companyId","permission":"resources:view","paginates":false},{"name":"resources_getMaintenanceDispatchComments","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7df6d6b7ba88","injectAuth":"companyId","permission":"resources:view","paginates":false},@@ -1125,7 +1125,7 @@{"name":"resources_upsertContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"6630f8761e37","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"contractor(id)"},{"name":"resources_upsertEmployeeAbilityCell","classification":"WRITE","paramCount":4,"schema":"800b78f5bbae","response":"3797626bd17e","injectAuth":"companyId","permission":"resources:create+update","paginates":false},{"name":"resources_upsertFailureMode","classification":"WRITE","paramCount":4,"schema":"e4d170d8f468","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},- {"name":"resources_upsertLocation","classification":"WRITE","paramCount":13,"schema":"5771361986b6","response":"5fe568931f57","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},+ {"name":"resources_upsertLocation","classification":"WRITE","paramCount":13,"schema":"5771361986b6","response":"99dfd44b4c2e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},{"name":"resources_upsertMaintenanceDispatchComment","classification":"WRITE","paramCount":3,"schema":"15129a94d57d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},{"name":"resources_upsertMaintenanceDispatchEvent","classification":"WRITE","paramCount":7,"schema":"a98569352969","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},{"name":"resources_upsertMaintenanceDispatchItem","classification":"WRITE","paramCount":6,"schema":"41c857266e1d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},@@ -1352,7 +1352,7 @@{"name":"settings_getCompany","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"8abc93835023","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCompanyIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a98b34db51d","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCompanyPlan","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},- {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d401a021a6d8","injectAuth":"companyId","permission":"settings:view","paginates":false},+ {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"b772b13d94c8","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getConfig","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"aa1021ff34cf","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCurrentSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:view","paginates":false},{"name":"settings_getCustomField","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a533a796c094","injectAuth":"companyId","permission":"settings:view","paginates":false},@@ -1411,6 +1411,7 @@{"name":"settings_updateMaintenanceDispatchNotificationSettings","classification":"WRITE","paramCount":4,"schema":"c857a8ae87fd","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateMaterialGeneratedIdsSetting","classification":"WRITE","paramCount":1,"schema":"8de91cc6fb4f","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateMetricSettings","classification":"WRITE","paramCount":1,"schema":"6310a488e8b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},+ {"name":"settings_updateMrpRunTimeSetting","classification":"WRITE","paramCount":1,"schema":"7e0d8d6dda56","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updatePlmReleaseControlSetting","classification":"WRITE","paramCount":1,"schema":"b74d1adb972d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updatePurchasePriceUpdateTimingSetting","classification":"WRITE","paramCount":1,"schema":"6e01697e737c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},{"name":"settings_updateQuoteLineCategoryMarkups","classification":"WRITE","paramCount":1,"schema":"46b636ff84f8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},diff --git a/apps/erp/app/routes/api+/purchasing.purchase-order.$id.finalize.ts b/apps/erp/app/routes/api+/purchasing.purchase-order.$id.finalize.tsnew file mode 100644index 0000000000..e1b628f15a--- /dev/null+++ b/apps/erp/app/routes/api+/purchasing.purchase-order.$id.finalize.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { getLogger } from "@carbon/logger";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getPurchaseOrder, getSupplier } from "~/modules/purchasing";+import { getCompanySettings } from "~/modules/settings";++const logger = getLogger("erp", "api-purchase-order-finalize");++/**+ * What `PurchaseOrderFinalizeModal` needs when it is opened away from the+ * purchase order's own page (the planning pages): the order, and the CC list+ * the PO page would default to — the supplier's own, else the company's.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "purchasing"+ });++ const { id } = params;+ if (!id) {+ return data(+ { purchaseOrder: null, defaultCc: [] as string[] },+ { status: 400 }+ );+ }++ const purchaseOrder = await getPurchaseOrder(client, id);+ if (purchaseOrder.error || purchaseOrder.data?.companyId !== companyId) {+ logger.error("Failed to read the purchase order to finalize", {+ companyId,+ purchaseOrderId: id,+ error: purchaseOrder.error+ });+ return data(+ { purchaseOrder: null, defaultCc: [] as string[] },+ { status: purchaseOrder.error ? 500 : 404 }+ );+ }++ const [supplier, companySettings] = await Promise.all([+ purchaseOrder.data.supplierId+ ? getSupplier(client, purchaseOrder.data.supplierId)+ : null,+ getCompanySettings(getCarbonServiceRole(), companyId)+ ]);++ const defaultCc = supplier?.data?.defaultCc?.length+ ? supplier.data.defaultCc+ : (companySettings.data?.defaultSupplierCc ?? []);++ return { purchaseOrder: purchaseOrder.data, defaultCc };+}++export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsxindex 0c740a6004..f115eae65f 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.planning.tsx@@ -19,6 +19,7 @@ import {import { ItemPlanningForm } from "~/modules/items/ui/Item";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";import { getLocationsList } from "~/modules/resources";+import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";import { getUserDefaults } from "~/modules/users/users.server";import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";@@ -90,7 +91,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -104,6 +105,24 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // The column references the global user table, so the database would take+ // a person from another company, or one since deactivated.+ if (+ validation.data.responsibleEmployee &&+ !(await isActiveCompanyEmployee(+ client,+ companyId,+ validation.data.responsibleEmployee+ ))+ ) {+ return validationError({+ fieldErrors: {+ responsibleEmployee: "Choose an employee of this company"+ },+ formId: validation.formId+ });+ }+const updateConsumablePlanning = await upsertItemPlanning(client, {...validation.data,itemId,diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsxindex 66d8d5d678..1c0e1a6223 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { ConsumableSummary } from "~/modules/items";@@ -90,6 +90,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(updatedSupplierPart.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (updatedSupplierPart.error) {return { success: false, message: "Failed to update supplier part" };}diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsxindex dc2e80c087..6be011eeb4 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx@@ -6,6 +6,7 @@ import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { useNavigate, useParams } from "react-router";import type { ConsumableSummary } from "~/modules/items";@@ -40,6 +41,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(createConsumableSupplier.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (createConsumableSupplier.error) {return {success: false,diff --git a/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx b/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsxindex 55a18cfd6f..601e1dd839 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data, useNavigate, useParams } from "react-router";import {@@ -66,7 +66,7 @@ export async function action({ request, params }: ActionFunctionArgs) {});if (createCustomerContact.error) {let errorMessage = "Failed to create customer contact";- if (createCustomerContact.error.message?.includes("duplicate key value")) {+ if (isUniqueViolation(createCustomerContact.error)) {const contact = await client.from("contact").select("id")diff --git a/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx b/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsxindex d5970c317b..b239b26f82 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx@@ -5,7 +5,7 @@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { deleteCustomerLocation } from "~/modules/sales";import { path } from "~/utils/path";@@ -32,10 +32,11 @@ export async function action({ request, params }: ActionFunctionArgs) {customerLocationId);if (deleteCustomerLocationError) {- const errorMessage =- deleteCustomerLocationError.code === "23503"- ? "Customer location is used elsewhere, cannot delete"- : "Failed to delete customer location";+ const errorMessage = getDatabaseErrorMessage(+ deleteCustomerLocationError,+ "Failed to delete customer location",+ { referenced: "Customer location is used elsewhere, cannot delete" }+ );throw redirect(path.to.customerLocations(customerId),diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsxindex 6c2dedde5b..285e583d42 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { JSONContent } from "@carbon/react";import { VStack } from "@carbon/react";-import { pluckUnique, redirect } from "@carbon/utils";+import { isUniqueViolation, pluckUnique, redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { useStorageUnits } from "~/components/Form/StorageUnit";@@ -119,10 +119,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {createdBy: userId});- if (- insertPickMethod.error &&- !insertPickMethod.error.message.includes("duplicate key value")- ) {+ if (insertPickMethod.error && !isUniqueViolation(insertPickMethod.error)) {throw redirect(path.to.inventory,await flash(diff --git a/apps/erp/app/routes/x+/items+/change-notice-types.delete.$id.tsx b/apps/erp/app/routes/x+/items+/change-notice-types.delete.$id.tsxindex 409e777721..3504a0080a 100644--- a/apps/erp/app/routes/x+/items+/change-notice-types.delete.$id.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice-types.delete.$id.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -57,10 +57,11 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId);if (deleteError) {- const errorMessage =- deleteError.code === "23503"- ? "Change notice category is used elsewhere, cannot delete"- : "Failed to delete change notice category";+ const errorMessage = getDatabaseErrorMessage(+ deleteError,+ "Failed to delete change notice category",+ { referenced: "Change notice category is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.changeNoticeTypes}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx b/apps/erp/app/routes/x+/items+/delete.$itemId.tsxindex 2b6582ff5a..2969485ed7 100644--- a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx+++ b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx@@ -5,7 +5,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { isForeignKeyViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { deleteItem } from "~/modules/items";import { getDatabaseClient } from "~/services/database.server";@@ -45,7 +45,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}function friendlyDeleteItemError(err: { code?: string; message?: string }) {- if (err.code === "23503") {+ if (isForeignKeyViolation(err)) {if (err.message?.includes("trackedEntity_itemId_fkey")) {return "Item has tracked entities linked to it and cannot be deleted. Deactivate the item instead.";}diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.tsindex b9d9fec4f0..c332c50fa3 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts@@ -79,6 +79,8 @@ vi.mock("~/modules/production", () => ({vi.mock("~/modules/production/production.server", async () => {const production = await import("~/modules/production");return {+ // Cancel is delegated whole; its steps live in cancelJob.+ cancelJob: vi.fn(async () => null),releaseJobs: vi.fn(async ({ jobIds, companyId, userId }) => {for (const id of jobIds) {await production.updateJobStatus({} as any, {@@ -103,6 +105,7 @@ import {returnPickedRemaindersForJob,updateJobStatus} from "~/modules/production";+import { cancelJob } from "~/modules/production/production.server";import { requireCompanyRecord } from "~/modules/shared/shared.server";import { action } from "./$jobId.status";@@ -296,7 +299,10 @@ describe("Job status tenancy", () => {});describe("Job cancel status action", () => {- it("returns staged material, then cancels the job's open picking lists", async () => {+ // The steps (return picked material, close picking lists, then cancel) live+ // in cancelJob, shared with planning's Cancel. The route must never set the+ // status itself, which would cancel the job without them.+ it("cancels through cancelJob and never sets the status itself", async () => {await expect(action({request: cancelRequest(),@@ -305,13 +311,13 @@ describe("Job cancel status action", () => {} 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")+ expect(cancelJob).toHaveBeenCalledWith(+ expect.objectContaining({+ jobId: "job-1",+ companyId: "company-1",+ userId: "user-1"+ }));+ expect(updateJobStatus).not.toHaveBeenCalled();});});diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsxindex 982213ef61..5102206569 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx@@ -11,16 +11,14 @@ import { runLocationSchedule } from "@carbon/planning";import { serverFns } from "@carbon/server-functions";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";-import { cancelOpenPickingListsForJob } from "~/modules/inventory";import {getJobReleaseReadiness,jobStatus,recalculateJobRequirements,- returnPickedRemaindersForJob,runMRP,updateJobStatus} from "~/modules/production";-import { releaseJobs } from "~/modules/production/production.server";+import { cancelJob, releaseJobs } from "~/modules/production/production.server";import { requireCompanyRecord } from "~/modules/shared/shared.server";import { getDatabaseClient } from "~/services/database.server";import { path, requestReferrer } from "~/utils/path";@@ -177,57 +175,36 @@ export async function action({ request, params }: ActionFunctionArgs) {// 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(),- getDatabaseClient(),- {- jobId: id,- userId,- companyId- }- );- if (sweep.error) {+ // Returns picked material and closes picking lists before the status+ // changes — the same path the planning Cancel action takes.+ const failed = await cancelJob({+ client,+ db: getDatabaseClient(),+ jobId: id,+ companyId,+ userId+ });+ if (failed) {throw redirect(requestReferrer(request) ?? path.to.job(id),- await flash(- request,- error(sweep.error, "Cancel aborted: returning picked material failed")- )+ await flash(request, error(failed.error, failed.message)));}- const picks = await cancelOpenPickingListsForJob(getDatabaseClient(), {- jobId: id,+ } else {+ const update = await updateJobStatus(client, {+ id,companyId,- userId+ status,+ updatedBy: userId});- if (picks.error) {+ if (update.error) {throw redirect(requestReferrer(request) ?? path.to.job(id),- await flash(- request,- error(- picks.error,- "Cancel aborted: its picking lists could not be closed"- )- )+ await flash(request, error(update.error, "Failed to update job status")));}}- const update = await updateJobStatus(client, {- id,- companyId,- status,- assignee: ["Cancelled"].includes(status) ? null : undefined,- updatedBy: userId- });- if (update.error) {- throw redirect(- requestReferrer(request) ?? path.to.job(id),- await flash(request, error(update.error, "Failed to update job status"))- );- }-if (status === "Planned" && shouldSchedule) {try {const purchaseOrdersBySupplierId = JSON.parse(diff --git a/apps/erp/app/routes/x+/material+/$itemId.planning.tsx b/apps/erp/app/routes/x+/material+/$itemId.planning.tsxindex 4e4ef48a37..367208f397 100644--- a/apps/erp/app/routes/x+/material+/$itemId.planning.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.planning.tsx@@ -19,6 +19,7 @@ import {import { ItemPlanningForm } from "~/modules/items/ui/Item";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";import { getLocationsList } from "~/modules/resources";+import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";import { getUserDefaults } from "~/modules/users/users.server";import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";@@ -90,7 +91,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -104,6 +105,24 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // The column references the global user table, so the database would take+ // a person from another company, or one since deactivated.+ if (+ validation.data.responsibleEmployee &&+ !(await isActiveCompanyEmployee(+ client,+ companyId,+ validation.data.responsibleEmployee+ ))+ ) {+ return validationError({+ fieldErrors: {+ responsibleEmployee: "Choose an employee of this company"+ },+ formId: validation.formId+ });+ }+const updateMateriallanning = await upsertItemPlanning(client, {...validation.data,itemId,diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsxindex 6b0227cc0f..d29cc4f1ed 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { MaterialSummary } from "~/modules/items";@@ -90,6 +90,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(updatedSupplierPart.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (updatedSupplierPart.error) {return { success: false, message: "Failed to update supplier part" };}diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsxindex 97e0431d88..d350962a50 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx@@ -6,6 +6,7 @@ import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { useNavigate, useParams } from "react-router";import type { MaterialSummary } from "~/modules/items";@@ -40,6 +41,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(createMaterialSupplier.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (createMaterialSupplier.error) {return {success: false,diff --git a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx b/apps/erp/app/routes/x+/part+/$itemId.planning.tsxindex 4a6da98b3a..e74b3b6803 100644--- a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.planning.tsx@@ -29,6 +29,7 @@ import {} from "~/modules/items/ui/Item";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";import { getLocationsList } from "~/modules/resources";+import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";import { getUserDefaults } from "~/modules/users/users.server";import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";@@ -234,6 +235,24 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // The column references the global user table, so the database would take+ // a person from another company, or one since deactivated.+ if (+ validation.data.responsibleEmployee &&+ !(await isActiveCompanyEmployee(+ client,+ companyId,+ validation.data.responsibleEmployee+ ))+ ) {+ return validationError({+ fieldErrors: {+ responsibleEmployee: "Choose an employee of this company"+ },+ formId: validation.formId+ });+ }+const updatePartPlanning = await upsertItemPlanning(client, {...validation.data,itemId,diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsxindex 571a4d15ae..6740730e6a 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx@@ -4,8 +4,9 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { validator } from "@carbon/form";+import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { PartSummary } from "~/modules/items";@@ -88,6 +89,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(updatedSupplierPart.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (updatedSupplierPart.error) {return { success: false, message: "Failed to update supplier part" };}diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsxindex cc32805f97..c7325e3a65 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx@@ -4,8 +4,9 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { validator } from "@carbon/form";+import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { useNavigate, useParams } from "react-router";import type { PartSummary } from "~/modules/items";@@ -43,6 +44,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(createPartSupplier.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (createPartSupplier.error) {return {success: false,diff --git a/apps/erp/app/routes/x+/part+/$itemId.sales.customer-parts.new.tsx b/apps/erp/app/routes/x+/part+/$itemId.sales.customer-parts.new.tsxindex bf72d93ac5..aed24ac456 100644--- a/apps/erp/app/routes/x+/part+/$itemId.sales.customer-parts.new.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.sales.customer-parts.new.tsx@@ -6,7 +6,7 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useParams } from "react-router";import {@@ -60,10 +60,12 @@ export async function action({ request, params }: ActionFunctionArgs) {if (createCustomerPart.error) {const flashMessage =- // 23505 means the unique constraint on ("customerId", "itemId") was violated- createCustomerPart.error.code == "23505"- ? "Customer Part record already defined for customer"- : "Failed to create customer part";+ // duplicate = the unique constraint on ("customerId", "itemId")+ getDatabaseErrorMessage(+ createCustomerPart.error,+ "Failed to create customer part",+ { duplicate: "Customer Part record already defined for customer" }+ );throw redirect(path.to.partSales(itemId),diff --git a/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsxindex 6e8051e91b..74b30c903f 100644--- a/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx+++ b/apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx@@ -56,6 +56,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {});}+ // Map MRP-written consumed quantities to week indexes (display-only)+ const consumedValues: Record<number, number> = {};+ periods.forEach((period, index) => {+ const row = existingProjections.data?.find((f) => f.periodId === period.id);+ if (row?.consumedQuantity && row.consumedQuantity > 0) {+ consumedValues[index] = row.consumedQuantity;+ }+ });+const initialValues = {itemId,locationId,@@ -64,7 +73,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {periods,- initialValues+ initialValues,+ consumedValues};}@@ -139,13 +149,14 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function EditProjectionRoute() {- const { initialValues } = useLoaderData<typeof loader>();+ const { initialValues, consumedValues } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();return (<DemandProjectionsForminitialValues={initialValues}+ consumedValues={consumedValues}isEditingonClose={() => closeRoute()}/>diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsxindex 1fb650924f..e90eb7be69 100644--- a/apps/erp/app/routes/x+/production+/planning.tsx+++ b/apps/erp/app/routes/x+/production+/planning.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import {RecordOutlet,ResizablePanel,@@ -16,7 +17,12 @@ import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import type { ProductionPlanningItem } from "~/modules/production";-import { getProductionPlanning } from "~/modules/production";+import {+ getPlanningActions,+ getProductionPlanning,+ PLANNING_DRAWER_PARAM,+ resolvePlanningActionScope+} from "~/modules/production";import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";import { resolveLocationId } from "~/modules/shared/location.server";import { getOrCreatePeriods } from "~/modules/shared/shared.server";@@ -27,6 +33,8 @@ import { getGenericQueryFilters } from "~/utils/query";const WEEKS_TO_PLAN = 12 * 4;+const logger = getLogger("erp", "production", "planning");+export const handle: Handle = {realtime: ["job"],breadcrumb: msg`Material Planning`,@@ -59,19 +67,42 @@ export async function loader({ request }: LoaderFunctionArgs) {);const periods = await getOrCreatePeriods(locationToday, WEEKS_TO_PLAN);- const items = await getProductionPlanning(- client,- locationId,- companyId,- periods.map((p) => p.id),- {+ // The grid's Actions and Assignee filters are not RPC+ // columns: they go to the RPC as arguments, which keeps the items with a+ // matching OPEN action inside each item's planning horizon.+ const { gridFilters, actionTypes, actionAssignees } =+ resolvePlanningActionScope({ filters });++ const periodIds = periods.map((p) => p.id);+ const asOf = locationToday.toString();++ // A link to a row's order drawer (`?item=`) opens it even when the row is+ // not on this page — the plan has changed since the link was made, or it+ // came from another page. That row is read on its own, alongside the page.+ const drawerItemId = searchParams.get(PLANNING_DRAWER_PARAM);++ const [items, drawerItemRead] = await Promise.all([+ getProductionPlanning(client, locationId, companyId, periodIds, {search,limit,offset,sorts,- filters- }- );+ filters: gridFilters,+ asOf,+ actionTypes,+ actionAssignees+ }),+ drawerItemId+ ? getProductionPlanning(client, locationId, companyId, periodIds, {+ search: null,+ limit: 1,+ offset: 0,+ sorts: [],+ filters: [{ column: "id", operator: "eq", value: drawerItemId }],+ asOf+ })+ : null+ ]);if (items.error) {redirect(@@ -80,9 +111,57 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ // A failed read of the linked row only leaves its drawer closed: the grid+ // drops a link it cannot resolve.+ if (drawerItemRead?.error) {+ logger.error("Failed to load the linked planning item", {+ companyId,+ locationId,+ itemId: drawerItemId,+ error: drawerItemRead.error+ });+ }+ const pageItems = (items.data ?? []) as ProductionPlanningItem[];+ const linkedItem = (drawerItemRead?.data?.[0] ??+ null) as ProductionPlanningItem | null;+ const drawerItem =+ linkedItem && !pageItems.some((item) => item.id === linkedItem.id)+ ? linkedItem+ : null;++ // The persisted MRP action worklist for the rows on THIS page (and the+ // drawer's row). Every action is loaded, whatever its date: the grid hides+ // the ones beyond each row's time fence, and a planner can widen one row's+ // fence without a reload.+ const planningActions = await getPlanningActions(client, {+ companyId,+ locationId,+ kind: "Make",+ itemIds: [...pageItems, ...(drawerItem ? [drawerItem] : [])].map(+ (item) => item.id+ )+ });++ // No fallback to an empty list: a grid with no actions reads as "nothing to+ // do", which is the one thing a failed read must not look like.+ if (planningActions.error) {+ logger.error("Failed to load planning actions", {+ companyId,+ locationId,+ error: planningActions.error+ });+ throw new Response("Failed to load planning actions", { status: 500 });+ }+return {- items: (items.data ?? []) as ProductionPlanningItem[],+ items: pageItems,+ // The row a `?item=` link opens the drawer on, when it is not in `items`.+ drawerItem,count: items.count ?? 0,+ planningActions: planningActions.data ?? [],+ // The Actions-column filter the rows were matched on: each row shows only+ // its actions of these types.+ actionTypes: actionTypes ?? null,periods,locationId,// Planned-order date defaults are business dates on the plant's calendar —@@ -92,7 +171,16 @@ export async function loader({ request }: LoaderFunctionArgs) {}export default function ProductionPlanningRoute() {- const { items, count, locationId, periods } = useLoaderData<typeof loader>();+ const {+ items,+ drawerItem,+ count,+ locationId,+ periods,+ planningActions,+ actionTypes,+ locationToday+ } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full ">@@ -105,9 +193,13 @@ export default function ProductionPlanningRoute() {><ProductionPlanningTabledata={items}+ drawerItem={drawerItem}count={count}locationId={locationId}periods={periods}+ planningActions={planningActions}+ actionTypes={actionTypes}+ locationToday={locationToday}/></ResizablePanel><RecordOutlet />diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsxindex d239fba9f4..f6fd8e7043 100644--- a/apps/erp/app/routes/x+/production+/planning.update.tsx+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx@@ -3,21 +3,62 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";+import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";-import { scrapAllowance } from "@carbon/utils";+import { async } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { z } from "zod";import {+ applyProductionPlanningDateActions,+ assignPlanningActions,+ dismissPlanningActions,+ getPlanningActionsByIds,insertJob,+ isJobEditableFromPlanning,+ markPlanningActionsActioned,+ notifyScheduleInputsChanged,+ PLANNING_EDITABLE_JOB_STATUSES,productionOrderValidator,recalculateJobRequirements,+ releasePlanningActionClaim,+ reopenDismissedPlanningActions,+ settleNewSupplyPlanningActions,+ updatePlanningJob,upsertJobMethod} from "~/modules/production";+import { cancelJob } from "~/modules/production/production.server";+import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";import { getDatabaseClient } from "~/services/database.server";const logger = getLogger("erp", "production", "planning");+type PlanningActionRow = NonNullable<+ Awaited<ReturnType<typeof getPlanningActionsByIds>>["data"]+>[number];++// Telling the scheduler is a follow-up to a write that already landed, so its+// failure is logged and reported, never thrown: a throw here used to end an+// Apply loop with a 500 after earlier actions were already applied.+async function notifyScheduleChange(+ companyId: string,+ reason: string,+ jobId?: string+): Promise<boolean> {+ try {+ await notifyScheduleInputsChanged(companyId, "reorder", reason, jobId);+ return true;+ } catch (error) {+ logger.error("Failed to notify the scheduler from planning", {+ companyId,+ jobId,+ reason,+ error+ });+ return false;+ }+}+const itemsValidator = z.object({id: z.string(),@@ -26,21 +67,28 @@ const itemsValidator = z.array();export async function action({ request }: ActionFunctionArgs) {+ const { items, action, locationId, planningActionIds, assignee, job } =+ await request.json();++ // Creating planned jobs is `create`; everything else here changes jobs and+ // actions that already exist (apply, inline edits, dismiss, reopen, assign),+ // which the job screens gate on `update`. The client is the service role, so+ // this check is the only one.const { client, companyId, userId } = await requirePermissions(request, {- create: "production",+ ...(action === "order"+ ? { create: "production" }+ : { update: "production" }),role: "employee",bypassRls: true});- const { items, action, locationId } = await request.json();-if (typeof locationId !== "string") {return data({success: false,message: "Location ID is required and must be a valid string"},- { status: 500 }+ { status: 400 });}@@ -50,7 +98,7 @@ export async function action({ request }: ActionFunctionArgs) {success: false,message: "Action parameter is required and must be a valid string"},- { status: 500 }+ { status: 400 });}@@ -91,7 +139,7 @@ export async function action({ request }: ActionFunctionArgs) {message: `Validation failed: ${errorMessages.join(", ")}`,errors: errorMessages},- { status: 500 }+ { status: 400 });}@@ -102,24 +150,33 @@ export async function action({ request }: ActionFunctionArgs) {success: false,message: "No items were provided to create production orders"},- { status: 500 }+ { status: 400 }+ );+ }++ // `order` only creates jobs. An existing job is edited through+ // `updateJob` or Apply, which carry the Draft / Planned guard, the+ // location check and the priority recalculation; this path had none.+ if (itemsToOrder.some((item) => item.orders.some((o) => o.existingId))) {+ logger.warn("Planning order named an existing job", {+ companyId,+ userId,+ locationId+ });+ return data(+ {+ success: false,+ message: "Existing jobs are changed from the Open Jobs list"+ },+ { status: 400 });}// `client` is the service role (bypassRls) and every id below comes from- // the request body: prove the location, items and existing jobs are this- // company's before any job is created or rewritten. One query per type.+ // the request body: prove the location and items are this company's+ // before any job is created. One query per type.const itemIds = [...new Set(itemsToOrder.map((item) => item.id))];- const existingJobIds = [- ...new Set(- itemsToOrder.flatMap((item) =>- item.orders.flatMap((order) =>- order.existingId ? [order.existingId] : []- )- )- )- ];- const [ownedLocation, ownedItems, ownedJobs] = await Promise.all([+ const [ownedLocation, ownedItems] = await Promise.all([client.from("location").select("id")@@ -130,29 +187,19 @@ export async function action({ request }: ActionFunctionArgs) {.from("item").select("id").in("id", itemIds)- .eq("companyId", companyId),- existingJobIds.length > 0- ? client- .from("job")- .select("id")- .in("id", existingJobIds)- .eq("companyId", companyId)- : Promise.resolve({ data: [] as { id: string }[], error: null })+ .eq("companyId", companyId)]);if (ownedLocation.error ||!ownedLocation.data ||ownedItems.error ||- (ownedItems.data ?? []).length !== itemIds.length ||- ownedJobs.error ||- (ownedJobs.data ?? []).length !== existingJobIds.length+ (ownedItems.data ?? []).length !== itemIds.length) {logger.error("Planning order references records outside the company", {companyId,locationId,itemIds,- existingJobIds,- error: ownedLocation.error ?? ownedItems.error ?? ownedJobs.error+ error: ownedLocation.error ?? ownedItems.error});return data({ success: false, message: "Not found" }, { status: 404 });}@@ -161,7 +208,6 @@ export async function action({ request }: ActionFunctionArgs) {const allJobIds: string[] = [];const createdJobs: { id: string; readableId: string }[] = [];const itemsWithoutOrders: string[] = [];- let updatedJobCount = 0;const allSupplyForecasts: Array<{itemId: string;locationId: string;@@ -175,13 +221,14 @@ export async function action({ request }: ActionFunctionArgs) {let processedItems = 0;let errors: string[] = [];+ // The (item, week) of every order that became a job, so the Make+ // suggestions it answers leave the worklist now, not at the next run.+ const ordered: { itemId: string; periodId: string }[] = [];// Manufacturing data for every item being ordered, in one readconst manufacturingRows = await client.from("itemReplenishment")- .select(- "itemId, manufacturingBlocked, scrapPercentage, requiresConfiguration"- )+ .select("itemId, manufacturingBlocked, requiresConfiguration").in("itemId",itemsToOrder.flatMap((item) =>@@ -239,107 +286,69 @@ export async function action({ request }: ActionFunctionArgs) {// Process each order for this itemfor (const order of orders) {- if (!order.existingId) {- // Create new job- const createJob = await insertJob(- client,- getDatabaseClient(),- {- itemId: item.id,- quantity: order.quantity,- startDate: order.startDate ?? undefined,- dueDate: order.dueDate ?? undefined,- deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",- status: "Planned",- locationId,- companyId,- createdBy: userId,- unitOfMeasureCode: "EA"- },- { skipMethod: true, skipRecalculate: true, source: "mrp" }- );-- if (createJob.error) {- const errorMsg = `Failed to create job for item ${item.id}: ${createJob.error.message}`;- logger.error(errorMsg);- errors.push(errorMsg);- continue;- }+ // Create new job+ const createJob = await insertJob(+ client,+ getDatabaseClient(),+ {+ itemId: item.id,+ quantity: order.quantity,+ startDate: order.startDate ?? undefined,+ dueDate: order.dueDate ?? undefined,+ deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",+ status: "Planned",+ locationId,+ companyId,+ createdBy: userId,+ unitOfMeasureCode: "EA"+ },+ { skipMethod: true, skipRecalculate: true, source: "mrp" }+ );- const id = createJob.data?.id;- const readableId = createJob.data?.jobId ?? "";- if (!id) {- const errorMsg = `Job was not returned after creation for item ${item.id}`;- logger.error(errorMsg);- errors.push(errorMsg);- continue;- }+ if (createJob.error) {+ const errorMsg = `Failed to create job for item ${item.id}: ${createJob.error.message}`;+ logger.error(errorMsg);+ errors.push(errorMsg);+ continue;+ }- const upsertMethod = await upsertJobMethod(- client,- getDatabaseClient(),- "itemToJob",- {- sourceId: item.id,- targetId: id,- companyId,- userId- }- );-- if (upsertMethod.error) {- const errorMsg = `Failed to create job method for item ${item.id}: ${upsertMethod.error.message}`;- logger.error(errorMsg);- errors.push(errorMsg);- continue;- }+ const id = createJob.data?.id;+ const readableId = createJob.data?.jobId ?? "";+ if (!id) {+ const errorMsg = `Job was not returned after creation for item ${item.id}`;+ logger.error(errorMsg);+ errors.push(errorMsg);+ continue;+ }- jobIds.push(id);- createdJobs.push({ id, readableId });- itemProcessed = true;- } else {- // Update existing job- jobIds.push(order.existingId);-- // Calculate scrap quantity based on scrap percentage- const updateScrapPercentage =- manufacturing.data?.scrapPercentage ?? 0;- const updateScrapQuantity = scrapAllowance(- order.quantity,- updateScrapPercentage- );-- const updateJob = await client- .from("job")- .update({- dueDate: order.dueDate ?? undefined,- deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",- quantity: order.quantity,- scrapQuantity: updateScrapQuantity,- startDate: order.startDate ?? undefined,- status: "Planned",- updatedAt: new Date().toISOString(),- updatedBy: userId- })- .eq("id", order.existingId)- .eq("companyId", companyId);-- if (updateJob.error) {- const errorMsg = `Failed to update job ${order.existingId} for item ${item.id}: ${updateJob.error.message}`;- logger.error(errorMsg);- errors.push(errorMsg);- continue;+ const upsertMethod = await upsertJobMethod(+ client,+ getDatabaseClient(),+ "itemToJob",+ {+ sourceId: item.id,+ targetId: id,+ companyId,+ userId}+ );- updatedJobCount++;- itemProcessed = true;+ if (upsertMethod.error) {+ const errorMsg = `Failed to create job method for item ${item.id}: ${upsertMethod.error.message}`;+ logger.error(errorMsg);+ errors.push(errorMsg);+ continue;}+ jobIds.push(id);+ createdJobs.push({ id, readableId });+ itemProcessed = true;+// Track supply forecast by periodconst periodId = order.periodId;+ ordered.push({ itemId: item.id, periodId });supplyForecastByPeriod[periodId] =- (supplyForecastByPeriod[periodId] || 0) +- (order.quantity - (order.existingQuantity ?? 0));+ (supplyForecastByPeriod[periodId] || 0) + order.quantity;}if (itemProcessed) {@@ -365,6 +374,20 @@ export async function action({ request }: ActionFunctionArgs) {}}+ const settled = await settleNewSupplyPlanningActions(+ getDatabaseClient(),+ { companyId, locationId, userId, type: "Make", ordered }+ );+ if (settled.error) {+ // The jobs stand; the suggestions clear on the next MRP run.+ logger.error("Failed to settle ordered planning actions", {+ companyId,+ userId,+ locationId,+ error: settled.error+ });+ }+// Insert all supply forecasts using upsert to handle duplicatesif (allSupplyForecasts.length > 0) {// Group supply forecasts by unique key to avoid duplicate conflicts@@ -401,11 +424,16 @@ export async function action({ request }: ActionFunctionArgs) {// Trigger recalculation for all jobsif (allJobIds.length > 0) {for (const jobId of allJobIds) {- await recalculateJobRequirements(client, getDatabaseClient(), {- id: jobId,- companyId,- userId- });+ const recalc = await recalculateJobRequirements(+ client,+ getDatabaseClient(),+ { id: jobId, companyId, userId }+ );+ if (recalc.error) {+ const errorMsg = `Created job ${jobId}, but its requirements could not be recalculated`;+ logger.error(errorMsg, { companyId, jobId, error: recalc.error });+ errors.push(errorMsg);+ }}}@@ -448,7 +476,7 @@ export async function action({ request }: ActionFunctionArgs) {}const message =- processedItems === itemsToOrder.length+ processedItems === itemsToOrder.length && errors.length === 0? `Successfully processed all ${processedItems} items with ${allJobIds.length} jobs`: `Processed ${processedItems} of ${itemsToOrder.length} items. ${errors.length@@ -460,7 +488,6 @@ export async function action({ request }: ActionFunctionArgs) {success: processedItems > 0 || errors.length === 0,message,jobs: createdJobs,- updatedJobCount,alreadyPlannedItemCount: alreadyPlannedItemIds.size,noDemandItemCount:itemsWithoutOrders.length - alreadyPlannedItemIds.size,@@ -483,13 +510,722 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // ── Save ONE field of ONE existing job: the planning drawer's Open Jobs+ // table autosaves a quantity or due date cell here. The job is re-read+ // under companyId (the client is the service role and the id comes from+ // the body), and the same commitment gate as Apply holds: a job released+ // to the floor is never edited from planning. The writes mirror Apply's —+ // a new date re-queues the schedule, a new quantity re-derives the job's+ // requirements.+ case "updateJob": {+ const parsedJob = z+ .discriminatedUnion("field", [+ z.object({+ id: z.string().min(1),+ field: z.literal("quantity"),+ value: z.number().positive()+ }),+ z.object({+ id: z.string().min(1),+ field: z.literal("dueDate"),+ value: z.string().regex(/^\d{4}-\d{2}-\d{2}$/)+ })+ ])+ .safeParse(job);+ if (!parsedJob.success) {+ return data(+ {+ success: false,+ message: "A job needs a quantity above zero or a valid date"+ },+ { status: 400 }+ );+ }++ const target = await client+ .from("job")+ .select("id, status, locationId")+ .eq("id", parsedJob.data.id)+ .eq("companyId", companyId)+ .maybeSingle();+ if (target.error || !target.data) {+ return data(+ { success: false, message: "Job not found" },+ { status: 404 }+ );+ }+ // The drawer lists one location's jobs; a request for another+ // location's job did not come from it.+ if (target.data.locationId !== locationId) {+ return data(+ { success: false, message: "This job is for another location." },+ { status: 409 }+ );+ }+ if (!isJobEditableFromPlanning(target.data.status)) {+ return data(+ {+ success: false,+ message:+ "This job is no longer Draft or Planned. Change it on the job."+ },+ { status: 409 }+ );+ }++ const saved = await updatePlanningJob(client, {+ id: target.data.id,+ companyId,+ updatedBy: userId,+ ...(parsedJob.data.field === "quantity"+ ? { quantity: parsedJob.data.value }+ : { dueDate: parsedJob.data.value })+ });+ if (saved.error) {+ logger.error("Failed to save job from planning", {+ companyId,+ userId,+ jobId: target.data.id,+ field: parsedJob.data.field,+ error: saved.error+ });+ return data(+ { success: false, message: "Failed to update job" },+ { status: 500 }+ );+ }+ if (!saved.updated) {+ // Released (or finished) after the status check above.+ return data(+ {+ success: false,+ message:+ "This job is no longer Draft or Planned. Change it on the job."+ },+ { status: 409 }+ );+ }++ // The field is saved from here on, so a failure below is a warning on a+ // saved edit, never a failure — the drawer keeps the new value.+ if (parsedJob.data.field === "quantity") {+ const recalc = await recalculateJobRequirements(+ client,+ getDatabaseClient(),+ { id: target.data.id, companyId, userId }+ );+ if (recalc.error) {+ logger.error("Failed to recalculate job requirements from planning", {+ companyId,+ userId,+ jobId: target.data.id,+ error: recalc.error+ });+ return {+ success: true,+ message: "Updated job",+ warning:+ "The quantity is saved, but the job's materials and operations were not recalculated. Recalculate the job."+ };+ }+ } else {+ const notified = await notifyScheduleChange(+ companyId,+ "Planning changed a job's due date",+ target.data.id+ );+ if (!notified) {+ return {+ success: true,+ message: "Updated job",+ warning:+ "The due date is saved, but the schedule was not refreshed. Reschedule the location."+ };+ }+ }++ return { success: true, message: "Updated job" };+ }++ // ── Apply a persisted planning action to its target job (spec §P1.5).+ // IDOR guard: the request carries ONLY planningActionIds — the type, target+ // and proposal values come from the persisted row, loaded by id+companyId+ // and required to be Open. The commitment gate re-reads the job status; a+ // released job (Ready or later) is never silently edited. Job dates flow+ // through updateJob (recomputes priority) + notifyScheduleInputsChanged —+ // never jobOperation date writes.+ // "apply" batches a mixed selection in ONE request (the client has a+ // single fetcher, so per-type requests would supersede each other) — each+ // row's own persisted type decides what happens to it.+ case "apply":+ case "expedite":+ case "defer":+ case "increase":+ case "decrease":+ case "cancel": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }++ const wireToType: Record<string, string> = {+ expedite: "Expedite",+ defer: "Defer",+ increase: "Increase",+ decrease: "Decrease",+ cancel: "Cancel"+ };+ const changeActionTypes = new Set(Object.values(wireToType));++ const db = getDatabaseClient();+ const applied: string[] = [];+ const requiresManualAction: { id: string; jobId: string | null }[] = [];+ const errors: string[] = [];+ // Applied, but a follow-up step failed: reported, never rolled back.+ const warnings: string[] = [];++ // A claim that is not given back leaves the action Actioned with nothing+ // applied, so a failed release is reported, never swallowed.+ const releaseClaim = async (planningActionId: string) => {+ const released = await releasePlanningActionClaim(client, {+ id: planningActionId,+ companyId,+ userId+ });+ if (released.error) {+ logger.error("Failed to release a planning action claim", {+ companyId,+ planningActionId,+ error: released.error+ });+ errors.push(+ `Planning action ${planningActionId} could not be reopened: ${released.error}`+ );+ }+ };++ // Two reads for the whole batch, then one claim and one change per+ // action: each job gets its own value, and a cancel has several steps.+ // The batch used to read the action and read its job one at a time —+ // three round trips per action before anything changed.+ const actionRows = await getPlanningActionsByIds(db, {+ ids: parsedIds.data,+ companyId+ });+ if (actionRows.error) {+ logger.error("Failed to read planning actions", {+ companyId,+ error: actionRows.error+ });+ return data(+ { success: false, message: "Failed to read planning actions" },+ { status: 500 }+ );+ }+ const rowById = new Map(actionRows.data.map((row) => [row.id, row]));++ const eligible: { planningActionId: string; row: PlanningActionRow }[] =+ [];+ for (const planningActionId of parsedIds.data) {+ const row = rowById.get(planningActionId);+ if (!row) {+ errors.push(`Planning action ${planningActionId} not found`);+ continue;+ }+ if (row.status !== "Open") {+ errors.push(`Planning action ${planningActionId} is not open`);+ continue;+ }+ if (+ action === "apply"+ ? !changeActionTypes.has(row.type)+ : wireToType[action] !== row.type+ ) {+ errors.push(+ action === "apply"+ ? `Planning action ${planningActionId} is a ${row.type}, which Apply cannot batch`+ : `Planning action ${planningActionId} is a ${row.type}, not ${wireToType[action]}`+ );+ continue;+ }+ if (!row.jobId) {+ errors.push(+ `Planning action ${planningActionId} does not target a job`+ );+ continue;+ }+ eligible.push({ planningActionId, row });+ }++ // One statement, like the reads above: the id list goes to Postgres as a+ // parameter, never into a PostgREST URL.+ const jobIds = [...new Set(eligible.map(({ row }) => row.jobId!))];+ let jobStatusById: Map<string, Database["public"]["Enums"]["jobStatus"]>;+ try {+ const jobs =+ jobIds.length > 0+ ? await db+ .selectFrom("job")+ .select(["id", "status"])+ .where("id", "in", jobIds)+ .where("companyId", "=", companyId)+ .execute()+ : [];+ jobStatusById = new Map(jobs.map((job) => [job.id, job.status]));+ } catch (err) {+ logger.error("Failed to read jobs for planning actions", {+ companyId,+ error: err+ });+ return data(+ {+ success: false,+ message: "Failed to read the planning actions' jobs"+ },+ { status: 500 }+ );+ }++ const toClaim: { planningActionId: string; row: PlanningActionRow }[] =+ [];+ for (const target of eligible) {+ const jobId = target.row.jobId!;+ const status = jobStatusById.get(jobId);+ if (status === undefined) {+ errors.push(+ `Job for planning action ${target.planningActionId} not found`+ );+ continue;+ }+ if (!isJobEditableFromPlanning(status)) {+ // Past Planned (on the floor, finished, closed or cancelled since+ // MRP ran) — surface "Review on Job" instead of editing it+ requiresManualAction.push({ id: target.planningActionId, jobId });+ continue;+ }+ toClaim.push(target);+ }++ // Dates: ONE transaction for every Expedite / Defer — the claim, two+ // reads and one UPDATE for the whole batch, then ONE scheduler event+ // (a "reorder" event re-stamps the whole company whatever its job id;+ // one per action sent the same company-wide replan N times).+ const dateActions = toClaim.filter(+ ({ row }) =>+ (row.type === "Expedite" || row.type === "Defer") && row.suggestedDate+ );+ if (dateActions.length > 0) {+ let outcome: Awaited<+ ReturnType<typeof applyProductionPlanningDateActions>+ >;+ try {+ outcome = await applyProductionPlanningDateActions(db, {+ companyId,+ userId,+ actions: dateActions.map(({ planningActionId, row }) => ({+ planningActionId,+ jobId: row.jobId!,+ suggestedDate: row.suggestedDate+ }))+ });+ } catch (err) {+ logger.error("Failed to reschedule jobs for planning actions", {+ companyId,+ userId,+ planningActionIds: dateActions.map((t) => t.planningActionId),+ error: err+ });+ return data(+ {+ success: false,+ message: `Failed to reschedule jobs: ${+ err instanceof Error ? err.message : "unknown error"+ }`+ },+ { status: 500 }+ );+ }+ applied.push(...outcome.applied);+ requiresManualAction.push(...outcome.refused);+ for (const id of outcome.alreadyApplied) {+ errors.push(`Planning action ${id} was already applied`);+ }+ if (outcome.applied.length > 0) {+ const notified = await notifyScheduleChange(+ companyId,+ `Planning rescheduled ${outcome.applied.length} job(s)`+ );+ if (!notified) {+ warnings.push(+ `${outcome.applied.length} due date(s) are saved, but the schedule was not refreshed`+ );+ }+ }+ }++ // Quantities and cancels call server functions with their own+ // transactions (recalculate, the cancel sweep), so they stay one job at+ // a time — but a few jobs at once, since each targets a different job.+ // Each action is claimed right before its own change: a request that+ // dies here strands at most the actions in flight, which the next MRP+ // run re-emits as fresh Open actions (the natural-key index ignores+ // Actioned rows).+ // Resolves to the claimed suggestion (see claimPlanningActions), or+ // null when the claim did not land.+ const claim = async (+ planningActionId: string+ ): Promise<{ suggestedQuantity: number | null } | null> => {+ const claimed = await markPlanningActionsActioned(db, {+ ids: [planningActionId],+ companyId,+ userId+ });+ if (claimed.error) {+ logger.error("Failed to claim a planning action", {+ companyId,+ planningActionId,+ error: claimed.error+ });+ errors.push(+ `Planning action ${planningActionId} could not be claimed: ${claimed.error.message}`+ );+ return null;+ }+ const [row] = claimed.data;+ if (!row) {+ errors.push(+ `Planning action ${planningActionId} was already applied`+ );+ return null;+ }+ return {+ suggestedQuantity:+ row.suggestedQuantity === null ||+ row.suggestedQuantity === undefined+ ? null+ : Number(row.suggestedQuantity)+ };+ };++ const perJobActions = toClaim.filter(+ ({ row }) =>+ row.type === "Cancel" ||+ row.type === "Increase" ||+ row.type === "Decrease"+ );+ // Two actions on one job (an Increase and a Cancel) must not run at+ // once: group by job, run the groups 3 at a time, each group in order.+ const byJob = new Map<string, typeof perJobActions>();+ for (const target of perJobActions) {+ const list = byJob.get(target.row.jobId!) ?? [];+ list.push(target);+ byJob.set(target.row.jobId!, list);+ }+ await async.map(+ [...byJob.values()],+ async (group) => {+ for (const { planningActionId, row } of group) {+ const claimedRow = await claim(planningActionId);+ if (!claimedRow) continue;+ const jobId = row.jobId!;++ if (row.type === "Cancel") {+ // The job status route's cancel: picked material goes back and+ // the job's picking lists close before the status changes.+ const failed = await cancelJob({+ client,+ db,+ jobId,+ companyId,+ userId,+ // Read Draft / Planned above; released since, it goes to review+ // instead of losing its picks.+ fromStatuses: [...PLANNING_EDITABLE_JOB_STATUSES]+ });+ if (failed?.refused) {+ await releaseClaim(planningActionId);+ requiresManualAction.push({ id: planningActionId, jobId });+ continue;+ }+ if (failed) {+ await releaseClaim(planningActionId);+ errors.push(+ `Failed to cancel job for planning action ${planningActionId}: ${failed.message}`+ );+ continue;+ }+ } else {+ const update = await updatePlanningJob(client, {+ id: jobId,+ companyId,+ updatedBy: userId,+ quantity: Number(+ claimedRow.suggestedQuantity ?? row.suggestedQuantity+ )+ });+ if (update.error) {+ await releaseClaim(planningActionId);+ errors.push(+ `Failed to update job quantity for planning action ${planningActionId}: ${update.error.message}`+ );+ continue;+ }+ if (!update.updated) {+ // Released (or finished) since it was read.+ await releaseClaim(planningActionId);+ requiresManualAction.push({ id: planningActionId, jobId });+ continue;+ }+ const recalc = await recalculateJobRequirements(client, db, {+ id: jobId,+ companyId,+ userId+ });+ if (recalc.error) {+ // The quantity change stands (and the action stays Actioned):+ // undoing it would be a second write that can fail the same way.+ logger.error(+ "Failed to recalculate job requirements after a planning action",+ {+ companyId,+ userId,+ jobId,+ planningActionId,+ error: recalc.error+ }+ );+ warnings.push(+ `Planning action ${planningActionId}: the quantity is saved, but the job's materials and operations were not recalculated`+ );+ }+ }++ applied.push(planningActionId);+ }+ },+ { concurrency: 3 }+ );++ // Committed targets are not failures, but "Applied 0" with a success+ // toast is a lie — surface the manual-review count, and only report+ // success when something was actually applied (or nothing needed review).+ const manualCount = requiresManualAction.length;+ const messageParts = [+ `Applied ${applied.length} planning action${applied.length === 1 ? "" : "s"}`+ ];+ if (manualCount > 0) {+ messageParts.push(+ `${manualCount} target${manualCount === 1 ? " is" : "s are"} committed — review on the order`+ );+ }+ if (warnings.length > 0) {+ messageParts.push(`${warnings.length} need a follow-up`);+ }+ if (errors.length > 0) {+ messageParts.push(`${errors.length} failed`);+ }+ return {+ success:+ errors.length === 0 &&+ warnings.length === 0 &&+ !(applied.length === 0 && manualCount > 0),+ message: messageParts.join("; "),+ applied,+ requiresManualAction,+ warnings: warnings.length > 0 ? warnings : undefined,+ errors: errors.length > 0 ? errors : undefined+ };+ }++ // ── Worklist mutations: dismiss suppresses a persisting need until it+ // changes materially; assign sets assigneeOverridden so the next MRP+ // diff-write never re-resolves the owner from the ladder.+ case "dismiss": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }+ const result = await dismissPlanningActions(getDatabaseClient(), {+ ids: parsedIds.data,+ companyId,+ userId,+ kind: "Make"+ });+ if (result.error) {+ logger.error("Failed to dismiss planning actions", {+ companyId,+ userId,+ planningActionIds: parsedIds.data,+ error: result.error+ });+ return data(+ { success: false, message: "Failed to dismiss planning actions" },+ { status: 500 }+ );+ }+ // The rows actually changed: an action applied or changed since the+ // page loaded is skipped, and the count says so.+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return {+ success: false,+ message:+ "Nothing to dismiss — these actions changed since the page loaded"+ };+ }+ return {+ success: true,+ message: `Dismissed ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < parsedIds.data.length+ ? `; ${parsedIds.data.length - changed} changed since the page loaded`+ : ""+ }`+ };+ }+ case "reopen": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }+ const result = await reopenDismissedPlanningActions(getDatabaseClient(), {+ ids: parsedIds.data,+ companyId,+ userId,+ kind: "Make"+ });+ if (result.error) {+ logger.error("Failed to reopen planning actions", {+ companyId,+ userId,+ planningActionIds: parsedIds.data,+ error: result.error+ });+ return data(+ { success: false, message: "Failed to reopen planning actions" },+ { status: 500 }+ );+ }+ // The rows actually changed: an action applied or changed since the+ // page loaded is skipped, and the count says so.+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return {+ success: false,+ message:+ "Nothing to reopen — these actions changed since the page loaded"+ };+ }+ return {+ success: true,+ message: `Reopened ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < parsedIds.data.length+ ? `; ${parsedIds.data.length - changed} changed since the page loaded`+ : ""+ }`+ };+ }+ case "assign": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }+ const parsedAssignee = z+ .string()+ .optional()+ .safeParse(assignee ?? undefined);+ if (!parsedAssignee.success) {+ return data(+ { success: false, message: "Invalid assignee" },+ { status: 400 }+ );+ }+ if (+ parsedAssignee.data &&+ !(await isActiveCompanyEmployee(client, companyId, parsedAssignee.data))+ ) {+ return data(+ { success: false, message: "Choose an employee of this company" },+ { status: 400 }+ );+ }+ const result = await assignPlanningActions(getDatabaseClient(), {+ ids: parsedIds.data,+ companyId,+ assignee: parsedAssignee.data || null,+ userId,+ kind: "Make"+ });+ if (result.error) {+ logger.error("Failed to assign planning actions", {+ companyId,+ userId,+ planningActionIds: parsedIds.data,+ error: result.error+ });+ return data(+ { success: false, message: "Failed to assign planning actions" },+ { status: 500 }+ );+ }+ // The rows actually changed: an action applied or changed since the+ // page loaded is skipped, and the count says so.+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return {+ success: false,+ message:+ "Nothing to assign — these actions changed since the page loaded"+ };+ }+ return {+ success: true,+ message: `Assigned ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < parsedIds.data.length+ ? `; ${parsedIds.data.length - changed} changed since the page loaded`+ : ""+ }`+ };+ }+default:return data({success: false,- message: `Unknown action '${action}'. Expected action: 'order'`+ message: `Unknown action '${action}'. Expected one of: 'order', 'updateJob', 'apply', 'expedite', 'defer', 'increase', 'decrease', 'cancel', 'dismiss', 'reopen', 'assign'`},- { status: 500 }+ { status: 400 });}}diff --git a/apps/erp/app/routes/x+/production+/scrap-reasons.delete.$scrapReasonId.tsx b/apps/erp/app/routes/x+/production+/scrap-reasons.delete.$scrapReasonId.tsxindex 886a15568b..753e3d73a9 100644--- a/apps/erp/app/routes/x+/production+/scrap-reasons.delete.$scrapReasonId.tsx+++ b/apps/erp/app/routes/x+/production+/scrap-reasons.delete.$scrapReasonId.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -53,10 +53,11 @@ export async function action({ request, params }: ActionFunctionArgs) {scrapReasonId);if (deleteScrapReasonError) {- const errorMessage =- deleteScrapReasonError.code === "23503"- ? "Scrap reason is used elsewhere, cannot delete"- : "Failed to delete scrap reason";+ const errorMessage = getDatabaseErrorMessage(+ deleteScrapReasonError,+ "Failed to delete scrap reason",+ { referenced: "Scrap reason is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.scrapReasons}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsxindex 2477be12af..3c2c9aaa50 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx@@ -128,13 +128,42 @@ export async function action(args: ActionFunctionArgs) {}}+ // A PO raised by the planning pages, untouched by hand since, skips the+ // approval rule when the company allows it (Settings → Planning). Fail+ // closed: a failed read of either is an ordinary approval check.+ const [planningOrigin, planningSettings] = await Promise.all([+ serviceRole+ .from("purchaseOrder")+ .select("createdFromPlanning")+ .eq("id", orderId)+ .eq("companyId", companyId)+ .maybeSingle(),+ serviceRole+ .from("companySettings")+ .select("skipApprovalForPlanningPurchaseOrders")+ .eq("id", companyId)+ .maybeSingle()+ ]);+ if (planningOrigin.error || planningSettings.error) {+ logger.error("Failed to read the planning approval bypass", {+ companyId,+ purchaseOrderId: orderId,+ error: planningOrigin.error ?? planningSettings.error+ });+ }+ const skipsApproval =+ planningOrigin.data?.createdFromPlanning === true &&+ planningSettings.data?.skipApprovalForPlanningPurchaseOrders === true;+const orderAmount = purchaseOrder.data.orderTotal ?? 0;- const approvalRequired = await isApprovalRequired(- serviceRole,- "purchaseOrder",- companyId,- orderAmount- );+ const approvalRequired = skipsApproval+ ? false+ : await isApprovalRequired(+ serviceRole,+ "purchaseOrder",+ companyId,+ orderAmount+ );const finalize = await finalizePurchaseOrder(client, orderId, userId);if (finalize.error) {diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsxindex 5bebb101bf..5abfe9b040 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx@@ -14,6 +14,7 @@ import { runMRP } from "~/modules/production";import {canCreatePurchaseOrderRevision,isPurchaseOrderLocked,+ isPurchaseOrderReopenStatus,purchaseOrderStatusType,reopenPurchaseOrderAsRevision,updatePurchaseOrderStatus@@ -24,6 +25,14 @@ import { path, requestReferrer } from "~/utils/path";const logger = getLogger("erp", "orderid-status");+/** The PO statuses whose open lines MRP counts as supply+ * (`openPurchaseOrderLines`). */+const MRP_SUPPLY_STATUSES = new Set<string>([+ "Planned",+ "To Receive",+ "To Receive and Invoice"+]);+export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -56,11 +65,16 @@ export async function action({ request, params }: ActionFunctionArgs) {const currentStatus = currentPo.data?.status;const isCurrentlyLocked = isPurchaseOrderLocked(currentStatus);+ // A reopen moves the PO back to an editable status: Draft from the PO page,+ // Planned from the planning pages (Draft is not MRP supply). Both are the+ // same operation — permission, pending approvals and revision alike.+ const isReopen = isPurchaseOrderReopenStatus(status);+// Explicit request only — a plain Reopen never bumps.const createRevisionRequested =- status === "Draft" && formData.get("createRevision") === "true";+ isReopen && formData.get("createRevision") === "true";- // Reject an ineligible revision BEFORE the Draft branch below cancels pending+ // Reject an ineligible revision BEFORE the reopen branch below cancels pending// approvals: those side effects must not be applied for a request that is// about to fail. reopenPurchaseOrderAsRevision re-checks the same conditions// in SQL, so this is a pre-flight, not the authority.@@ -82,11 +96,12 @@ export async function action({ request, params }: ActionFunctionArgs) {}// Determine required permission:- // - Reopening (Draft) from a locked status requires delete permission+ // - Reopening (Draft or Planned) from a locked status requires delete+ // permission// - Closing from any status requires delete permission// - Other status changes require update permissionconst requiresDeletePermission =- (status === "Draft" && isCurrentlyLocked) || status === "Closed";+ (isReopen && isCurrentlyLocked) || status === "Closed";const { client, userId, companyId } = await requirePermissions(request, {...(requiresDeletePermission@@ -126,9 +141,9 @@ export async function action({ request, params }: ActionFunctionArgs) {}}- // Cancel pending approval requests when reopening to Draft+ // Cancel pending approval requests when reopening (to Draft or Planned)// This handles reopening from both "Needs Approval" and "Closed" statuses- if (status === "Draft") {+ if (isReopen) {// Find all pending approval requests for this POconst pendingApprovals = await serviceRole.from("approvalRequest")@@ -204,7 +219,8 @@ export async function action({ request, params }: ActionFunctionArgs) {rowsUpdated = await reopenPurchaseOrderAsRevision(getDatabaseClient(), {id,companyId,- updatedBy: userId+ updatedBy: userId,+ status: isReopen ? status : "Draft"});} catch (err) {logger.error("Failed to create purchase order revision", { error: err });@@ -246,7 +262,10 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- if (status === "Planned") {+ // Planned makes the PO's lines MRP supply. A PO that already was supply (a+ // released one reopened from planning) changes nothing MRP reads, so the+ // reopen does not wait on a company-wide run.+ if (status === "Planned" && !MRP_SUPPLY_STATUSES.has(currentStatus ?? "")) {await runMRP(serviceRole, getDatabaseClient(), {type: "purchaseOrder",id,diff --git a/apps/erp/app/routes/x+/purchasing+/planning.tsx b/apps/erp/app/routes/x+/purchasing+/planning.tsxindex 826218b8f9..d361ac2a55 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import {RecordOutlet,ResizablePanel,@@ -15,6 +16,11 @@ import { datetime, redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";+import {+ getPlanningActions,+ PLANNING_DRAWER_PARAM,+ resolvePlanningActionScope+} from "~/modules/production";import type { PurchasingPlanningItem } from "~/modules/purchasing";import { getPurchasingPlanning } from "~/modules/purchasing";import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";@@ -27,6 +33,8 @@ import { getGenericQueryFilters } from "~/utils/query";const WEEKS_TO_PLAN = 12 * 4;+const logger = getLogger("erp", "purchasing", "planning");+export const handle: Handle = {breadcrumb: msg`Material Planning`,to: path.to.purchasingPlanning@@ -58,19 +66,42 @@ export async function loader({ request }: LoaderFunctionArgs) {);const periods = await getOrCreatePeriods(locationToday, WEEKS_TO_PLAN);- const items = await getPurchasingPlanning(- client,- locationId,- companyId,- periods.map((p) => p.id),- {+ // The grid's Actions and Assignee filters are not RPC+ // columns: they go to the RPC as arguments, which keeps the items with a+ // matching OPEN action inside each item's planning horizon.+ const { gridFilters, actionTypes, actionAssignees } =+ resolvePlanningActionScope({ filters });++ const periodIds = periods.map((p) => p.id);+ const asOf = locationToday.toString();++ // A link to a row's order drawer (`?item=`) opens it even when the row is+ // not on this page — the plan has changed since the link was made, or it+ // came from another page. That row is read on its own, alongside the page.+ const drawerItemId = searchParams.get(PLANNING_DRAWER_PARAM);++ const [items, drawerItemRead] = await Promise.all([+ getPurchasingPlanning(client, locationId, companyId, periodIds, {search,limit,offset,sorts,- filters- }- );+ filters: gridFilters,+ asOf,+ actionTypes,+ actionAssignees+ }),+ drawerItemId+ ? getPurchasingPlanning(client, locationId, companyId, periodIds, {+ search: null,+ limit: 1,+ offset: 0,+ sorts: [],+ filters: [{ column: "id", operator: "eq", value: drawerItemId }],+ asOf+ })+ : null+ ]);if (items.error) {redirect(@@ -79,9 +110,57 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ // A failed read of the linked row only leaves its drawer closed: the grid+ // drops a link it cannot resolve.+ if (drawerItemRead?.error) {+ logger.error("Failed to load the linked planning item", {+ companyId,+ locationId,+ itemId: drawerItemId,+ error: drawerItemRead.error+ });+ }+ const pageItems = (items.data ?? []) as PurchasingPlanningItem[];+ const linkedItem = (drawerItemRead?.data?.[0] ??+ null) as PurchasingPlanningItem | null;+ const drawerItem =+ linkedItem && !pageItems.some((item) => item.id === linkedItem.id)+ ? linkedItem+ : null;++ // The persisted MRP action worklist for the rows on THIS page (and the+ // drawer's row). Every action is loaded, whatever its date: the grid hides+ // the ones beyond each row's time fence, and a planner can widen one row's+ // fence without a reload.+ const planningActions = await getPlanningActions(client, {+ companyId,+ locationId,+ kind: "Buy",+ itemIds: [...pageItems, ...(drawerItem ? [drawerItem] : [])].map(+ (item) => item.id+ )+ });++ // No fallback to an empty list: a grid with no actions reads as "nothing to+ // do", which is the one thing a failed read must not look like.+ if (planningActions.error) {+ logger.error("Failed to load planning actions", {+ companyId,+ locationId,+ error: planningActions.error+ });+ throw new Response("Failed to load planning actions", { status: 500 });+ }+return {- items: (items.data ?? []) as PurchasingPlanningItem[],+ items: pageItems,+ // The row a `?item=` link opens the drawer on, when it is not in `items`.+ drawerItem,count: items.count ?? 0,+ planningActions: planningActions.data ?? [],+ // The Actions-column filter the rows were matched on: each row shows only+ // its actions of these types.+ actionTypes: actionTypes ?? null,periods,locationId,// Planned-order date defaults are business dates on the plant's calendar —@@ -91,7 +170,16 @@ export async function loader({ request }: LoaderFunctionArgs) {}export default function PurchasingPlanningRoute() {- const { items, count, locationId, periods } = useLoaderData<typeof loader>();+ const {+ items,+ drawerItem,+ count,+ locationId,+ periods,+ planningActions,+ actionTypes,+ locationToday+ } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full ">@@ -104,9 +192,13 @@ export default function PurchasingPlanningRoute() {><PurchasingPlanningTabledata={items}+ drawerItem={drawerItem}count={count}locationId={locationId}periods={periods}+ planningActions={planningActions}+ actionTypes={actionTypes}+ locationToday={locationToday}/></ResizablePanel><RecordOutlet />diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsxindex 6482b3b000..fb21842e3c 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx@@ -2,21 +2,71 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { hasPermission } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getUserClaims } from "@carbon/auth/users.server";+import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";-import { applyRate, SCALE, taxableBase } from "@carbon/utils";+import { applyRate, datetime, SCALE, taxableBase } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { z } from "zod";import {+ assignPlanningActions,+ dismissPlanningActions,+ getPlanningActionsByIds,+ reopenDismissedPlanningActions,+ settleNewSupplyPlanningActions+} from "~/modules/production";+import {+ applyPurchasingPlanningActions,+ findPlanningPurchaseOrder,insertPurchaseOrder,+ isPurchaseOrderEditableFromPlanning,plannedOrderValidator,+ planningPurchaseOrderWeek,+ taxPairForQuantity,+ updatePurchaseOrderLineSchedule,upsertPurchaseOrderLine} from "~/modules/purchasing";-import { requireCompanyRecord } from "~/modules/shared/shared.server";+import {+ isActiveCompanyEmployee,+ requireCompanyRecord+} from "~/modules/shared/shared.server";+import { getLocationTimeZone } from "~/modules/shared/timezone.server";+import { getDatabaseClient } from "~/services/database.server";const logger = getLogger("erp", "purchasing", "planning");+type PlanningActionRow = NonNullable<+ Awaited<ReturnType<typeof getPlanningActionsByIds>>["data"]+>[number];++/**+ * The date the supplier promised for a PO line: the line's own, else its+ * order's delivery date — the same COALESCE the `openPurchaseOrderLines` view+ * gives MRP. MRP dates the line by this ahead of the required date, so a+ * planning date change (which writes the required date) cannot move it.+ */+function promisedDateOf(line: {+ promisedDate: string | null;+ receiptPromisedDate: string | null | undefined;+}): string | null {+ return line.promisedDate ?? line.receiptPromisedDate ?? null;+}++/** A PO line an Apply targets, with its order's status and delivery promise. */+type PlanningLine = {+ id: string;+ purchaseOrderId: string;+ conversionFactor: number | null;+ promisedDate: string | null;+ purchaseOrderStatus:+ | Database["public"]["Enums"]["purchaseOrderStatus"]+ | null;+ receiptPromisedDate: string | null;+};+const itemsValidator = z.object({id: z.string(),@@ -25,15 +75,22 @@ const itemsValidator = z.array();export async function action({ request }: ActionFunctionArgs) {+ const { items, action, locationId, planningActionIds, assignee, line } =+ await request.json();++ // Creating planned orders is `create`; everything else here changes records+ // that already exist (apply, inline edits, dismiss, reopen, assign), which+ // the purchase order screens gate on `update`. The client is the service+ // role, so this check is the only one.const { client, companyId, companyGroupId, userId } =await requirePermissions(request, {- create: "purchasing",+ ...(action === "order"+ ? { create: "purchasing" }+ : { update: "purchasing" }),role: "employee",bypassRls: true});- const { items, action, locationId } = await request.json();-if (typeof locationId !== "string") {logger.warn("Planning update rejected: locationId missing", {companyId,@@ -46,7 +103,7 @@ export async function action({ request }: ActionFunctionArgs) {success: false,message: "Location ID is required and must be a valid string"},- { status: 500 }+ { status: 400 });}@@ -62,7 +119,7 @@ export async function action({ request }: ActionFunctionArgs) {success: false,message: "Action parameter is required and must be a valid string"},- { status: 500 }+ { status: 400 });}@@ -112,7 +169,7 @@ export async function action({ request }: ActionFunctionArgs) {message: `Validation failed: ${errorMessages.join(", ")}`,errors: errorMessages},- { status: 500 }+ { status: 400 });}@@ -128,7 +185,29 @@ export async function action({ request }: ActionFunctionArgs) {success: false,message: "No items were provided to create purchase orders"},- { status: 500 }+ { status: 400 }+ );+ }++ // `order` only creates PO lines. An existing line is changed through+ // `updateLine` or Apply, which carry the status, promised-date and+ // tax-pair guards; a stale client naming one here would get a duplicate.+ if (+ itemsToOrder.some((item) =>+ item.orders.some((o) => o.existingLineId || o.existingId)+ )+ ) {+ logger.warn("Planning order named an existing purchase order line", {+ companyId,+ userId,+ locationId+ });+ return data(+ {+ success: false,+ message: "Existing orders are changed from the Open Orders list"+ },+ { status: 400 });}@@ -147,17 +226,21 @@ export async function action({ request }: ActionFunctionArgs) {updatedBy: string;}> = [];- // Separate existing-line updates from new orders, and group new- // orders by supplier so every supplier gets exactly one PO per- // submit. Each line keeps its own requiredDate, so per-period timing- // lives on the lines rather than on separate headers.+ // Group new orders by supplier; below, each supplier's orders are+ // split again by week, so a supplier gets one PO per week. An+ // existing line is never edited here except to add a same-item,+ // same-date order to it: the drawer's inline edit and Apply go+ // through updatePurchaseOrderLineSchedule, which carries the status,+ // promised-date and tax-pair guards.type OrderEntry = {itemId: string;order: (typeof itemsToOrder)[0]["orders"][0];};- const existingLineUpdates: OrderEntry[] = [];const ordersBySupplier = new Map<string, OrderEntry[]>();const errors: string[] = [];+ // The (item, week) of every order that became a PO line, so the Order+ // suggestions it answers leave the worklist now, not at the next run.+ const ordered: { itemId: string; periodId: string }[] = [];for (const item of itemsToOrder) {itemIds.add(item.id);@@ -166,10 +249,7 @@ export async function action({ request }: ActionFunctionArgs) {if (order.supplierId) supplierIds.add(order.supplierId);if (order.periodId) periodIds.add(order.periodId);- if (order.existingLineId) {- existingLineUpdates.push({ itemId: item.id, order });- itemHasUsableOrder = true;- } else if (order.supplierId && order.periodId) {+ if (order.supplierId && order.periodId) {if (!ordersBySupplier.has(order.supplierId)) {ordersBySupplier.set(order.supplierId, []);}@@ -192,7 +272,6 @@ export async function action({ request }: ActionFunctionArgs) {userId,locationId,itemCount: itemsToOrder.length,- existingLineUpdates: existingLineUpdates.length,suppliers: Array.from(ordersBySupplier, ([supplierId, orders]) => ({supplierId,orderCount: orders.length@@ -200,48 +279,30 @@ export async function action({ request }: ActionFunctionArgs) {});// bypassRls hands back the service role, and every id below comes- // from the request body: the location, items and existing lines must- // belong to this company before anything is read or written by them+ // from the request body: the location and items must belong to this+ // company before anything is read or written by them// (supplyForecast upserts on (itemId, locationId, periodId) alone).- const existingLineIds = existingLineUpdates.map(- ({ order }) => order.existingLineId!- );await requireCompanyRecord(client, "location", companyId, {id: locationId});- const [ownedItems, ownedLines] = await Promise.all([- client- .from("item")- .select("id")- .in("id", Array.from(itemIds))- .eq("companyId", companyId),- existingLineIds.length > 0- ? client- .from("purchaseOrderLine")- .select("id")- .in("id", existingLineIds)- .eq("companyId", companyId)- : Promise.resolve({ data: [] as { id: string }[], error: null })- ]);+ const ownedItems = await client+ .from("item")+ .select("id")+ .in("id", Array.from(itemIds))+ .eq("companyId", companyId);if (ownedItems.error ||- ownedLines.error ||- (ownedItems.data?.length ?? 0) !== itemIds.size ||- (ownedLines.data?.length ?? 0) !== new Set(existingLineIds).size+ (ownedItems.data?.length ?? 0) !== itemIds.size) {logger.error("Planning order references records outside company", {companyId,userId,locationId,itemIds: Array.from(itemIds),- existingLineIds,- error: ownedItems.error ?? ownedLines.error+ error: ownedItems.error});return data(- {- success: false,- message: "Item or purchase order line not found"- },+ { success: false, message: "Item not found" },{ status: 404 });}@@ -319,32 +380,7 @@ export async function action({ request }: ActionFunctionArgs) {let processedItems = 0;- // ── UPDATE existing draft/planned lines ──- for (const { order } of existingLineUpdates) {- const updateLine = await client- .from("purchaseOrderLine")- .update({- purchaseQuantity: order.quantity,- requiredDate: order.dueDate ?? null,- updatedBy: userId- })- .eq("id", order.existingLineId!)- .eq("companyId", companyId);- if (updateLine.error) {- logger.error("Failed to update existing PO line", {- companyId,- userId,- locationId,- purchaseOrderLineId: order.existingLineId,- error: updateLine.error- });- errors.push(- `Failed to update existing PO line ${order.existingLineId}: ${updateLine.error.message}`- );- }- }-- // ── CREATE new PO lines, one PO per supplier ──+ // ── CREATE new PO lines, one PO per supplier per week ──// Track readable id too so the client can present a clickable toast.const poCache = new Map<string, { id: string; readableId: string }>();@@ -358,7 +394,61 @@ export async function action({ request }: ActionFunctionArgs) {(purchasingRows.data ?? []).map((row) => [row.itemId, row]));- for (const [supplierId, ordersInGroup] of ordersBySupplier) {+ // Weeks are counted from the location's today, as the planning+ // grid's are.+ const asOf = datetime.today(+ await getLocationTimeZone(client, locationId, companyId)+ );++ // Every open PO an order may join, with its lines, in one read: the+ // suppliers' Draft / Planned purchase orders at this location, oldest+ // first. The lines tell which weeks a PO already covers, and which+ // line a same-item, same-date order adds its quantity to.+ const openPurchaseOrders = await client+ .from("purchaseOrder")+ .select(+ "id, purchaseOrderId, supplierId, currencyCode, createdFromPlanning, purchaseOrderDelivery!inner(locationId), purchaseOrderLine(id, itemId, requiredDate, purchaseQuantity, supplierUnitPrice, supplierShippingCost, taxPercent, supplierTaxAmount)"+ )+ .eq("companyId", companyId)+ .in("supplierId", Array.from(ordersBySupplier.keys()))+ .eq("purchaseOrderType", "Purchase")+ .in("status", ["Draft", "Planned"])+ .eq("purchaseOrderDelivery.locationId", locationId)+ .order("createdAt", { ascending: true });++ if (openPurchaseOrders.error) {+ logger.error("Failed to look up open POs for planning orders", {+ companyId,+ userId,+ locationId,+ supplierIds: Array.from(ordersBySupplier.keys()),+ error: openPurchaseOrders.error+ });+ return data(+ {+ success: false,+ message: "Failed to retrieve open purchase orders from database"+ },+ { status: 500 }+ );+ }++ const candidatePurchaseOrders = openPurchaseOrders.data.map((po) => ({+ id: po.id,+ purchaseOrderId: po.purchaseOrderId,+ supplierId: po.supplierId,+ currencyCode: po.currencyCode,+ createdFromPlanning: po.createdFromPlanning,+ purchaseOrderLine: po.purchaseOrderLine ?? []+ }));++ // The POs this submit raised, and the planning POs it added to: their+ // approval bypass (`createdFromPlanning`) is restored once their lines+ // are written, since the shared line writer clears it on any change.+ // A Draft / Planned PO someone created by hand stays unflagged.+ const planningPurchaseOrderIds = new Set<string>();++ for (const [supplierId, ordersForSupplier] of ordersBySupplier) {const supplier = suppliersById.get(supplierId);if (!supplier) {logger.warn("Planning order supplier not found", {@@ -371,278 +461,293 @@ export async function action({ request }: ActionFunctionArgs) {continue;}- // Reuse the supplier's open Planned/Draft PO for this location,- // else create one. Looking up the header directly (rather than a- // line whose requiredDate falls in a period) means a null or- // overdue due date can no longer miss the match and spawn a- // duplicate PO.- let purchaseOrderId: string | undefined;- let purchaseOrderReadableId: string | undefined;+ const currencyCode = supplier.currencyCode ?? baseCurrencyCode;+ const decimals = currencyDecimals.get(currencyCode) ?? SCALE;- const existingPO = await client- .from("purchaseOrder")- .select(- "id, purchaseOrderId, purchaseOrderDelivery!inner(locationId)"- )- .eq("companyId", companyId)- .eq("supplierId", supplierId)- .eq("purchaseOrderType", "Purchase")- .in("status", ["Draft", "Planned"])- .eq("purchaseOrderDelivery.locationId", locationId)- .order("createdAt", { ascending: true })- .limit(1)- .maybeSingle();-- if (existingPO.error) {- logger.error("Failed to look up existing PO for supplier", {- companyId,- userId,- locationId,- supplierId,- error: existingPO.error- });- errors.push(- `Failed to look up existing PO for supplier ${supplierId}: ${existingPO.error.message}`- );- continue;+ // One PO per supplier per week, so each week's PO is finalized and+ // sent on its own and the later weeks stay Planned, where MRP can+ // still move, resize or cancel them.+ const ordersByWeek = new Map<string, OrderEntry[]>();+ for (const entry of ordersForSupplier) {+ const week = planningPurchaseOrderWeek(entry.order.dueDate, asOf);+ ordersByWeek.set(week, [...(ordersByWeek.get(week) ?? []), entry]);}- if (existingPO.data) {- purchaseOrderId = existingPO.data.id;- purchaseOrderReadableId = existingPO.data.purchaseOrderId;- logger.info("Reusing open PO for supplier", {- companyId,- userId,- locationId,- supplierId,- purchaseOrderId,- readableId: purchaseOrderReadableId,- orderCount: ordersInGroup.length- });- } else {- const createPO = await insertPurchaseOrder(client, {- status: "Planned",- supplierId,- purchaseOrderType: "Purchase",- currencyCode: supplier.currencyCode ?? baseCurrencyCode,- locationId,- companyId,- companyGroupId,- createdBy: userId- });+ for (const [week, ordersInGroup] of ordersByWeek) {+ // Reuse the supplier's open Draft / Planned PO whose lines are all+ // in this week, in the supplier's currency, else create one.+ let purchaseOrder = findPlanningPurchaseOrder(+ candidatePurchaseOrders,+ { supplierId, currencyCode, week },+ asOf+ );- if (createPO.error || !createPO.data) {- logger.error("Failed to create PO for supplier", {+ if (purchaseOrder) {+ if (purchaseOrder.createdFromPlanning) {+ planningPurchaseOrderIds.add(purchaseOrder.id);+ }+ logger.info("Reusing open PO for supplier week", {companyId,userId,locationId,supplierId,- error: createPO.error+ week,+ purchaseOrderId: purchaseOrder.id,+ readableId: purchaseOrder.purchaseOrderId,+ orderCount: ordersInGroup.length});- errors.push(- `Failed to create PO for supplier ${supplierId}: ${createPO.error?.message ?? "no data returned"}`- );- continue;- }-- purchaseOrderId = createPO.data.id;- purchaseOrderReadableId = createPO.data.purchaseOrderId;- logger.info("Created PO for supplier", {- companyId,- userId,- locationId,- supplierId,- purchaseOrderId,- readableId: purchaseOrderReadableId,- orderCount: ordersInGroup.length- });- }-- poCache.set(supplierId, {- id: purchaseOrderId,- readableId: purchaseOrderReadableId ?? purchaseOrderId- });-- // Create one line per order for this supplier- for (const { itemId, order } of ordersInGroup) {- const supplierPart = supplierParts?.data?.find(- (sp) => sp.itemId === itemId && sp.supplierId === supplierId- );-- const purchasing = {- data: purchasingByItem.get(itemId),- error:- purchasingRows.error ??- (purchasingByItem.has(itemId)- ? null- : { message: "No replenishment record" })- };-- if (purchasing.error) {- logger.error("Failed to retrieve item replenishment", {- companyId,- userId,- locationId,+ } else {+ const createPO = await insertPurchaseOrder(client, {+ status: "Planned",supplierId,- purchaseOrderId,- itemId,- error: purchasing.error+ purchaseOrderType: "Purchase",+ currencyCode,+ locationId,+ companyId,+ companyGroupId,+ createdBy: userId});- errors.push(- `Failed to retrieve purchasing data for item ${itemId}: ${purchasing.error.message}`- );- continue;- }- if (purchasing.data?.purchasingBlocked) {- logger.warn("Planning order skipped: purchasing blocked", {+ if (createPO.error || !createPO.data) {+ logger.error("Failed to create PO for supplier", {+ companyId,+ userId,+ locationId,+ supplierId,+ week,+ error: createPO.error+ });+ errors.push(+ `Failed to create PO for supplier ${supplierId}: ${createPO.error?.message ?? "no data returned"}`+ );+ continue;+ }++ purchaseOrder = {+ id: createPO.data.id,+ purchaseOrderId: createPO.data.purchaseOrderId,+ supplierId,+ currencyCode,+ createdFromPlanning: true,+ purchaseOrderLine: []+ };+ planningPurchaseOrderIds.add(createPO.data.id);+ candidatePurchaseOrders.push(purchaseOrder);+ logger.info("Created PO for supplier week", {companyId,userId,locationId,supplierId,- purchaseOrderId,- itemId+ week,+ purchaseOrderId: purchaseOrder.id,+ readableId: purchaseOrder.purchaseOrderId,+ orderCount: ordersInGroup.length});- errors.push(`Purchasing is blocked for item ${itemId}`);- continue;}- const minimumOrderQuantity =- supplierPart?.minimumOrderQuantity ?? 0;- let adjustedQuantity = order.quantity;- if (- minimumOrderQuantity > 0 &&- adjustedQuantity < minimumOrderQuantity- ) {- adjustedQuantity = minimumOrderQuantity;- }+ const purchaseOrderId = purchaseOrder.id;+ poCache.set(`${supplierId}:${week}`, {+ id: purchaseOrderId,+ readableId: purchaseOrder.purchaseOrderId ?? purchaseOrderId+ });++ // Create one line per order for this supplier and week+ for (const { itemId, order } of ordersInGroup) {+ const supplierPart = supplierParts?.data?.find(+ (sp) => sp.itemId === itemId && sp.supplierId === supplierId+ );++ const purchasing = {+ data: purchasingByItem.get(itemId),+ error:+ purchasingRows.error ??+ (purchasingByItem.has(itemId)+ ? null+ : { message: "No replenishment record" })+ };- // Check if this PO already has a line for the same item due on- // the same date. Orders for different weeks stay on separate- // lines so each keeps its own required date.- let existingLineQuery = client- .from("purchaseOrderLine")- .select("id, purchaseQuantity")- .eq("purchaseOrderId", purchaseOrderId)- .eq("itemId", itemId)- .eq("companyId", companyId);- existingLineQuery = order.dueDate- ? existingLineQuery.eq("requiredDate", order.dueDate)- : existingLineQuery.is("requiredDate", null);- const { data: existingLines } = await existingLineQuery.limit(1);-- if (existingLines?.[0]) {- const existing = existingLines[0];- const updateLine = await client- .from("purchaseOrderLine")- .update({- purchaseQuantity:- (existing.purchaseQuantity ?? 0) + adjustedQuantity,- updatedBy: userId- })- .eq("id", existing.id)- .eq("companyId", companyId);-- if (updateLine.error) {- logger.error("Failed to merge PO line", {+ if (purchasing.error) {+ logger.error("Failed to retrieve item replenishment", {companyId,userId,locationId,+ supplierId,purchaseOrderId,- purchaseOrderLineId: existing.id,itemId,- error: updateLine.error+ error: purchasing.error});errors.push(- `Failed to update PO line for item ${itemId}: ${updateLine.error.message}`+ `Failed to retrieve purchasing data for item ${itemId}: ${purchasing.error.message}`);continue;}- logger.info("Merged planned order into existing PO line", {- companyId,- userId,- locationId,- purchaseOrderId,- purchaseOrderLineId: existing.id,- itemId,- requiredDate: order.dueDate ?? null,- previousQuantity: existing.purchaseQuantity ?? 0,- addedQuantity: adjustedQuantity- });- } else {- const createLine = await upsertPurchaseOrderLine(client, {- purchaseOrderId,- itemId,- description: order.description,- purchaseOrderLineType: "Part",- purchaseQuantity: adjustedQuantity,- purchaseUnitOfMeasureCode:- supplierPart?.supplierUnitOfMeasureCode ??- order.unitOfMeasureCode,- inventoryUnitOfMeasureCode: order.unitOfMeasureCode,- conversionFactor: supplierPart?.conversionFactor ?? 1,- supplierUnitPrice: supplierPart?.unitPrice ?? 0,++ if (purchasing.data?.purchasingBlocked) {+ logger.warn("Planning order skipped: purchasing blocked", {+ companyId,+ userId,+ locationId,+ supplierId,+ purchaseOrderId,+ itemId+ });+ errors.push(`Purchasing is blocked for item ${itemId}`);+ continue;+ }++ const minimumOrderQuantity =+ supplierPart?.minimumOrderQuantity ?? 0;+ let adjustedQuantity = order.quantity;+ if (+ minimumOrderQuantity > 0 &&+ adjustedQuantity < minimumOrderQuantity+ ) {+ adjustedQuantity = minimumOrderQuantity;+ }++ // An order for an item the PO already has on the same date adds+ // to that line. Orders for different dates stay on separate+ // lines so each keeps its own required date.+ const requiredDate = order.dueDate ?? null;+ const existing = purchaseOrder.purchaseOrderLine.find(+ (line) =>+ line.itemId === itemId && line.requiredDate === requiredDate+ );++ if (existing) {+ const purchaseQuantity =+ (existing.purchaseQuantity ?? 0) + adjustedQuantity;+ // The extended price follows the quantity on its own; the tax+ // amount is stored, so it is restated at the line's rate.+ const tax = taxPairForQuantity(+ existing,+ purchaseQuantity,+ decimals+ );+ const updateLine = await client+ .from("purchaseOrderLine")+ .update({+ purchaseQuantity,+ taxPercent: tax.percent,+ supplierTaxAmount: tax.amount,+ updatedBy: userId+ })+ .eq("id", existing.id)+ .eq("companyId", companyId);++ if (updateLine.error) {+ logger.error("Failed to merge PO line", {+ companyId,+ userId,+ locationId,+ purchaseOrderId,+ purchaseOrderLineId: existing.id,+ itemId,+ error: updateLine.error+ });+ errors.push(+ `Failed to update PO line for item ${itemId}: ${updateLine.error.message}`+ );+ continue;+ }+ logger.info("Merged planned order into existing PO line", {+ companyId,+ userId,+ locationId,+ purchaseOrderId,+ purchaseOrderLineId: existing.id,+ itemId,+ requiredDate,+ previousQuantity: existing.purchaseQuantity ?? 0,+ addedQuantity: adjustedQuantity+ });+ existing.purchaseQuantity = purchaseQuantity;+ existing.taxPercent = tax.percent;+ existing.supplierTaxAmount = tax.amount;+ } else {+ const supplierUnitPrice = supplierPart?.unitPrice ?? 0;+ const taxPercent = supplier.taxPercent ?? 0;// supplier.taxPercent is a 0..1 fraction; the amount follows// the canonical denominator. Shipping is hardcoded 0 on this// path, so it is passed explicitly rather than omitted.- taxPercent: supplier.taxPercent ?? 0,- supplierTaxAmount: applyRate(- taxableBase(- supplierPart?.unitPrice ?? 0,- adjustedQuantity,- 0- ),- supplier.taxPercent ?? 0,- currencyDecimals.get(- supplier.currencyCode ?? baseCurrencyCode- ) ?? SCALE- ),- supplierShippingCost: 0,- requiredDate: order.dueDate ?? undefined,- locationId,- companyId,- createdBy: userId- });+ const supplierTaxAmount = applyRate(+ taxableBase(supplierUnitPrice, adjustedQuantity, 0),+ taxPercent,+ decimals+ );+ const createLine = await upsertPurchaseOrderLine(client, {+ purchaseOrderId,+ itemId,+ description: order.description,+ purchaseOrderLineType: "Part",+ purchaseQuantity: adjustedQuantity,+ purchaseUnitOfMeasureCode:+ supplierPart?.supplierUnitOfMeasureCode ??+ order.unitOfMeasureCode,+ inventoryUnitOfMeasureCode: order.unitOfMeasureCode,+ conversionFactor: supplierPart?.conversionFactor ?? 1,+ supplierUnitPrice,+ taxPercent,+ supplierTaxAmount,+ supplierShippingCost: 0,+ requiredDate: order.dueDate ?? undefined,+ locationId,+ companyId,+ createdBy: userId+ });- if (createLine.error) {- logger.error("Failed to create PO line", {+ if (createLine.error) {+ logger.error("Failed to create PO line", {+ companyId,+ userId,+ locationId,+ purchaseOrderId,+ itemId,+ error: createLine.error+ });+ errors.push(+ `Failed to create PO line for item ${itemId}: ${createLine.error.message}`+ );+ continue;+ }+ logger.info("Created PO line from planned order", {companyId,userId,locationId,purchaseOrderId,itemId,- error: createLine.error+ requiredDate,+ quantity: adjustedQuantity,+ minimumOrderQuantityApplied:+ adjustedQuantity !== order.quantity+ });+ purchaseOrder.purchaseOrderLine.push({+ id: createLine.data.id,+ itemId,+ requiredDate,+ purchaseQuantity: adjustedQuantity,+ supplierUnitPrice,+ supplierShippingCost: 0,+ taxPercent,+ supplierTaxAmount});- errors.push(- `Failed to create PO line for item ${itemId}: ${createLine.error.message}`- );- continue;}- logger.info("Created PO line from planned order", {- companyId,- userId,- locationId,- purchaseOrderId,++ processedItems++;+ ordered.push({ itemId, periodId: order.periodId });++ const conversionFactor = supplierPart?.conversionFactor ?? 1;+ allSupplyForecasts.push({itemId,- requiredDate: order.dueDate ?? null,- quantity: adjustedQuantity,- minimumOrderQuantityApplied: adjustedQuantity !== order.quantity+ locationId,+ sourceType: "Purchase Order" as const,+ forecastQuantity: order.quantity * conversionFactor,+ periodId: order.periodId,+ companyId,+ createdBy: userId,+ updatedBy: userId});}-- processedItems++;-- const conversionFactor = supplierPart?.conversionFactor ?? 1;- allSupplyForecasts.push({- itemId,- locationId,- sourceType: "Purchase Order" as const,- forecastQuantity: order.quantity * conversionFactor,- periodId: order.periodId,- companyId,- createdBy: userId,- updatedBy: userId- });}}@@ -664,6 +769,37 @@ export async function action({ request }: ActionFunctionArgs) {}}+ if (planningPurchaseOrderIds.size > 0) {+ const flagged = await client+ .from("purchaseOrder")+ .update({ createdFromPlanning: true })+ .in("id", [...planningPurchaseOrderIds])+ .eq("companyId", companyId);+ if (flagged.error) {+ // The orders stand; they go through approval like any other PO.+ logger.error("Failed to mark planning purchase orders", {+ companyId,+ userId,+ purchaseOrderIds: [...planningPurchaseOrderIds],+ error: flagged.error+ });+ }+ }++ const settled = await settleNewSupplyPlanningActions(+ getDatabaseClient(),+ { companyId, locationId, userId, type: "Order", ordered }+ );+ if (settled.error) {+ // The PO lines stand; the suggestions clear on the next MRP run.+ logger.error("Failed to settle ordered planning actions", {+ companyId,+ userId,+ locationId,+ error: settled.error+ });+ }+if (errors.length > 0 && processedItems === 0) {logger.error("Failed to process any planning orders", {companyId,@@ -697,8 +833,8 @@ export async function action({ request }: ActionFunctionArgs) {errors.length > 2 ? "..." : ""}`;- // Dedupe by PO id — multiple supplier+period buckets can land on- // the same PO when an existing Draft/Planned PO covers them.+ // Dedupe by PO id. Each supplier week has its own PO, so this is+ // only a guard.const purchaseOrders = Array.from(new Map(Array.from(poCache.values()).map((po) => [po.id, po])@@ -752,13 +888,595 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // ── Save ONE field of ONE existing PO line: the planning drawer's Open+ // Orders table autosaves a quantity or due date cell here. The line is+ // re-read under companyId (the client is the service role and the id comes+ // from the body), and the same commitment gate as Apply holds: a PO that+ // has been sent is never edited from planning.+ case "updateLine": {+ const parsedLine = z+ .discriminatedUnion("field", [+ z.object({+ id: z.string().min(1),+ field: z.literal("quantity"),+ value: z.number().positive()+ }),+ z.object({+ id: z.string().min(1),+ field: z.literal("dueDate"),+ value: z.string().regex(/^\d{4}-\d{2}-\d{2}$/)+ })+ ])+ .safeParse(line);+ if (!parsedLine.success) {+ return data(+ {+ success: false,+ message:+ "A purchase order line needs a quantity above zero or a valid date"+ },+ { status: 400 }+ );+ }++ const target = await client+ .from("purchaseOrderLine")+ .select(+ "id, locationId, promisedDate, purchaseOrder!inner(id, status, purchaseOrderDelivery(receiptPromisedDate))"+ )+ .eq("id", parsedLine.data.id)+ .eq("companyId", companyId)+ .maybeSingle();+ if (target.error || !target.data) {+ return data(+ { success: false, message: "Purchase order line not found" },+ { status: 404 }+ );+ }++ // The drawer lists one location's orders; a request for another+ // location's line did not come from it.+ if (target.data.locationId !== locationId) {+ return data(+ {+ success: false,+ message: "This purchase order line is for another location."+ },+ { status: 409 }+ );+ }++ const targetStatus = target.data.purchaseOrder?.status;+ if (!isPurchaseOrderEditableFromPlanning(targetStatus)) {+ return data(+ {+ success: false,+ message:+ "This purchase order is in approval or has been sent to the supplier. Change it on the order."+ },+ { status: 409 }+ );+ }++ if (+ parsedLine.data.field === "dueDate" &&+ promisedDateOf({+ promisedDate: target.data.promisedDate,+ receiptPromisedDate:+ target.data.purchaseOrder?.purchaseOrderDelivery+ ?.receiptPromisedDate+ }) !== null+ ) {+ return data(+ {+ success: false,+ message:+ "The supplier has promised a date for this line. Change it on the order."+ },+ { status: 409 }+ );+ }++ const saved = await updatePurchaseOrderLineSchedule(+ client,+ getDatabaseClient(),+ {+ lineId: target.data.id,+ companyId,+ companyGroupId,+ userId,+ ...(parsedLine.data.field === "quantity"+ ? { purchaseQuantity: parsedLine.data.value }+ : { requiredDate: parsedLine.data.value })+ }+ );+ if (saved.error) {+ logger.error("Failed to save PO line from planning", {+ companyId,+ userId,+ purchaseOrderLineId: target.data.id,+ field: parsedLine.data.field,+ error: saved.error+ });+ return data(+ { success: false, message: "Failed to update purchase order line" },+ { status: 500 }+ );+ }++ if (!saved.updated) {+ // Sent or put in approval after the status check above.+ return data(+ {+ success: false,+ message:+ "This purchase order is in approval or has been sent to the supplier. Change it on the order."+ },+ { status: 409 }+ );+ }++ return { success: true, message: "Updated purchase order line" };+ }++ // ── Apply a persisted planning action to its target PO line (spec §P1.5).+ // IDOR guard: the request carries ONLY planningActionIds — the type, target+ // and proposal values come from the persisted row, loaded by id+companyId+ // and required to be Open. The commitment gate re-reads the parent PO+ // status; a locked (sent) PO is never silently edited.+ // "apply" batches a mixed selection in ONE request (the client has a+ // single fetcher, so per-type requests would supersede each other) — each+ // row's own persisted type decides what happens to it.+ case "apply":+ case "expedite":+ case "defer":+ case "increase":+ case "decrease":+ case "cancel": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }++ const wireToType: Record<string, string> = {+ expedite: "Expedite",+ defer: "Defer",+ increase: "Increase",+ decrease: "Decrease",+ cancel: "Cancel"+ };+ const changeActionTypes = new Set(Object.values(wireToType));++ const db = getDatabaseClient();+ const applied: string[] = [];+ const requiresManualAction: {+ id: string;+ purchaseOrderId: string | null;+ }[] = [];+ const errors: string[] = [];++ // Cancel DELETES the PO line, which the purchase order screen gates on+ // `delete`. Read once, only when a Cancel is in the batch.+ let canDeleteLines: boolean | undefined;+ const mayDeleteLines = async () => {+ canDeleteLines ??= hasPermission(+ (await getUserClaims(userId, companyId))?.permissions,+ "purchasing",+ "delete",+ companyId+ );+ return canDeleteLines;+ };++ // Two reads for the whole batch to decide what is eligible, then ONE+ // transaction that applies all of it (applyPurchasingPlanningActions).+ // The batch used to read the action and read its line one at a time —+ // three round trips per action before anything changed.+ const actionRows = await getPlanningActionsByIds(db, {+ ids: parsedIds.data,+ companyId+ });+ if (actionRows.error) {+ logger.error("Failed to read planning actions", {+ companyId,+ error: actionRows.error+ });+ return data(+ { success: false, message: "Failed to read planning actions" },+ { status: 500 }+ );+ }+ const rowById = new Map(actionRows.data.map((row) => [row.id, row]));++ const eligible: { planningActionId: string; row: PlanningActionRow }[] =+ [];+ for (const planningActionId of parsedIds.data) {+ const row = rowById.get(planningActionId);+ if (!row) {+ errors.push(`Planning action ${planningActionId} not found`);+ continue;+ }+ if (row.status !== "Open") {+ errors.push(`Planning action ${planningActionId} is not open`);+ continue;+ }+ if (+ action === "apply"+ ? !changeActionTypes.has(row.type)+ : wireToType[action] !== row.type+ ) {+ errors.push(+ action === "apply"+ ? `Planning action ${planningActionId} is a ${row.type}, which Apply cannot batch`+ : `Planning action ${planningActionId} is a ${row.type}, not ${wireToType[action]}`+ );+ continue;+ }+ if (!row.purchaseOrderLineId) {+ errors.push(+ `Planning action ${planningActionId} does not target a purchase order line`+ );+ continue;+ }+ eligible.push({ planningActionId, row });+ }++ // One statement, like the reads above: the id list goes to Postgres as a+ // parameter, never into a PostgREST URL. The order's status and delivery+ // promise come with the line, as the embed gave them.+ const lineIds = [+ ...new Set(eligible.map(({ row }) => row.purchaseOrderLineId!))+ ];+ let lineById: Map<string, PlanningLine>;+ try {+ const lines =+ lineIds.length > 0+ ? await db+ .selectFrom("purchaseOrderLine as pol")+ .innerJoin("purchaseOrder as po", (join) =>+ join+ .onRef("po.id", "=", "pol.purchaseOrderId")+ .on("po.companyId", "=", companyId)+ )+ .leftJoin("purchaseOrderDelivery as pod", "pod.id", "po.id")+ .select([+ "pol.id",+ "pol.purchaseOrderId",+ "pol.conversionFactor",+ "pol.promisedDate",+ "po.status as purchaseOrderStatus",+ "pod.receiptPromisedDate"+ ])+ .where("pol.id", "in", lineIds)+ .where("pol.companyId", "=", companyId)+ .execute()+ : [];+ lineById = new Map(lines.map((line) => [line.id, line]));+ } catch (err) {+ logger.error(+ "Failed to read purchase order lines for planning actions",+ {+ companyId,+ error: err+ }+ );+ return data(+ {+ success: false,+ message: "Failed to read the planning actions' purchase order lines"+ },+ { status: 500 }+ );+ }++ const toClaim: {+ planningActionId: string;+ row: PlanningActionRow;+ line: PlanningLine;+ }[] = [];+ for (const { planningActionId, row } of eligible) {+ const line = lineById.get(row.purchaseOrderLineId!);+ if (!line) {+ errors.push(+ `Purchase order line for planning action ${planningActionId} not found`+ );+ continue;+ }++ const datePromised =+ (row.type === "Expedite" || row.type === "Defer") &&+ promisedDateOf(line) !== null;+ if (+ !isPurchaseOrderEditableFromPlanning(line.purchaseOrderStatus) ||+ datePromised+ ) {+ // In approval or sent, or a date the supplier promised (which Apply's+ // required date cannot move) — surface "Review on PO" instead.+ requiresManualAction.push({+ id: planningActionId,+ purchaseOrderId: line.purchaseOrderId+ });+ continue;+ }++ if (row.type === "Cancel" && !(await mayDeleteLines())) {+ errors.push(+ `Planning action ${planningActionId} deletes a purchase order line, which needs delete permission`+ );+ continue;+ }+ toClaim.push({ planningActionId, row, line });+ }++ // One transaction for the whole batch, set-based: the claim, the dates,+ // the quantities and the cancels are one statement each, and a refused+ // write un-claims its action inside the same transaction. A failure+ // rolls everything back; the previous loop applied one action at a time+ // and could run into the request's time limit with the rest unapplied.+ let outcome: Awaited<ReturnType<typeof applyPurchasingPlanningActions>>;+ try {+ outcome = await applyPurchasingPlanningActions(db, {+ companyId,+ companyGroupId,+ userId,+ actions: toClaim.map(({ planningActionId, row, line }) => ({+ planningActionId,+ type: row.type as+ | "Expedite"+ | "Defer"+ | "Increase"+ | "Decrease"+ | "Cancel",+ lineId: line.id,+ purchaseOrderId: line.purchaseOrderId,+ suggestedDate: row.suggestedDate ?? null,+ suggestedQuantity:+ row.suggestedQuantity === null ||+ row.suggestedQuantity === undefined+ ? null+ : Number(row.suggestedQuantity)+ }))+ });+ } catch (err) {+ logger.error("Failed to apply planning actions", {+ companyId,+ userId,+ planningActionIds: toClaim.map((t) => t.planningActionId),+ error: err+ });+ return data(+ {+ success: false,+ message: `Failed to apply planning actions: ${+ err instanceof Error ? err.message : "unknown error"+ }`+ },+ { status: 500 }+ );+ }+ applied.push(...outcome.applied);+ requiresManualAction.push(...outcome.refused);+ for (const id of outcome.alreadyApplied) {+ errors.push(`Planning action ${id} was already applied`);+ }+ for (const failure of outcome.failed) {+ errors.push(`Planning action ${failure.id}: ${failure.message}`);+ }++ // Committed targets are not failures, but "Applied 0" with a success+ // toast is a lie — surface the manual-review count, and only report+ // success when something was actually applied (or nothing needed review).+ const manualCount = requiresManualAction.length;+ const messageParts = [+ `Applied ${applied.length} planning action${applied.length === 1 ? "" : "s"}`+ ];+ if (manualCount > 0) {+ messageParts.push(+ `${manualCount} target${manualCount === 1 ? " is" : "s are"} committed — review on the order`+ );+ }+ if (errors.length > 0) {+ messageParts.push(`${errors.length} failed`);+ }+ return {+ success:+ errors.length === 0 && !(applied.length === 0 && manualCount > 0),+ message: messageParts.join("; "),+ applied,+ requiresManualAction,+ errors: errors.length > 0 ? errors : undefined+ };+ }++ // ── Worklist mutations: dismiss suppresses a persisting need until it+ // changes materially; assign sets assigneeOverridden so the next MRP+ // diff-write never re-resolves the owner from the ladder.+ case "dismiss": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }+ const result = await dismissPlanningActions(getDatabaseClient(), {+ ids: parsedIds.data,+ companyId,+ userId,+ kind: "Buy"+ });+ if (result.error) {+ logger.error("Failed to dismiss planning actions", {+ companyId,+ userId,+ planningActionIds: parsedIds.data,+ error: result.error+ });+ return data(+ { success: false, message: "Failed to dismiss planning actions" },+ { status: 500 }+ );+ }+ // The rows actually changed: an action applied or changed since the+ // page loaded is skipped, and the count says so.+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return {+ success: false,+ message:+ "Nothing to dismiss — these actions changed since the page loaded"+ };+ }+ return {+ success: true,+ message: `Dismissed ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < parsedIds.data.length+ ? `; ${parsedIds.data.length - changed} changed since the page loaded`+ : ""+ }`+ };+ }+ case "reopen": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }+ const result = await reopenDismissedPlanningActions(getDatabaseClient(), {+ ids: parsedIds.data,+ companyId,+ userId,+ kind: "Buy"+ });+ if (result.error) {+ logger.error("Failed to reopen planning actions", {+ companyId,+ userId,+ planningActionIds: parsedIds.data,+ error: result.error+ });+ return data(+ { success: false, message: "Failed to reopen planning actions" },+ { status: 500 }+ );+ }+ // The rows actually changed: an action applied or changed since the+ // page loaded is skipped, and the count says so.+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return {+ success: false,+ message:+ "Nothing to reopen — these actions changed since the page loaded"+ };+ }+ return {+ success: true,+ message: `Reopened ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < parsedIds.data.length+ ? `; ${parsedIds.data.length - changed} changed since the page loaded`+ : ""+ }`+ };+ }+ case "assign": {+ // The same id twice (a row selected in two places) is one action.+ const parsedIds = z+ .array(z.string().min(1))+ .min(1)+ .transform((ids) => [...new Set(ids)])+ .safeParse(planningActionIds);+ if (!parsedIds.success) {+ return data(+ { success: false, message: "planningActionIds is required" },+ { status: 400 }+ );+ }+ const parsedAssignee = z+ .string()+ .optional()+ .safeParse(assignee ?? undefined);+ if (!parsedAssignee.success) {+ return data(+ { success: false, message: "Invalid assignee" },+ { status: 400 }+ );+ }+ if (+ parsedAssignee.data &&+ !(await isActiveCompanyEmployee(client, companyId, parsedAssignee.data))+ ) {+ return data(+ { success: false, message: "Choose an employee of this company" },+ { status: 400 }+ );+ }+ const result = await assignPlanningActions(getDatabaseClient(), {+ ids: parsedIds.data,+ companyId,+ assignee: parsedAssignee.data || null,+ userId,+ kind: "Buy"+ });+ if (result.error) {+ logger.error("Failed to assign planning actions", {+ companyId,+ userId,+ planningActionIds: parsedIds.data,+ error: result.error+ });+ return data(+ { success: false, message: "Failed to assign planning actions" },+ { status: 500 }+ );+ }+ // The rows actually changed: an action applied or changed since the+ // page loaded is skipped, and the count says so.+ const changed = result.data?.length ?? 0;+ if (changed === 0) {+ return {+ success: false,+ message:+ "Nothing to assign — these actions changed since the page loaded"+ };+ }+ return {+ success: true,+ message: `Assigned ${changed} planning action${changed === 1 ? "" : "s"}${+ changed < parsedIds.data.length+ ? `; ${parsedIds.data.length - changed} changed since the page loaded`+ : ""+ }`+ };+ }+default:return data({success: false,- message: `Unknown action '${action}'. Expected action: 'order'`+ message: `Unknown action '${action}'. Expected one of: 'order', 'updateLine', 'apply', 'expedite', 'defer', 'increase', 'decrease', 'cancel', 'dismiss', 'reopen', 'assign'`},- { status: 500 }+ { status: 400 });}}diff --git a/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsxindex ed577084f1..4cc7d6c694 100644--- a/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/gauge-types.delete.$id.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -47,10 +47,11 @@ export async function action({ request, params }: ActionFunctionArgs) {const { error: deleteGaugeTypeError } = await deleteGaugeType(client, id);if (deleteGaugeTypeError) {- const errorMessage =- deleteGaugeTypeError.code === "23503"- ? "Gauge type is used elsewhere, cannot delete"- : "Failed to delete gauge type";+ const errorMessage = getDatabaseErrorMessage(+ deleteGaugeTypeError,+ "Failed to delete gauge type",+ { referenced: "Gauge type is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.gaugeTypes}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/quality+/gauges.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/gauges.delete.$id.tsxindex 680eea28bf..3577aab2d4 100644--- a/apps/erp/app/routes/x+/quality+/gauges.delete.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/gauges.delete.$id.tsx@@ -5,7 +5,7 @@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { deleteGauge } from "~/modules/quality";@@ -31,9 +31,9 @@ export async function action({ request, params }: ActionFunctionArgs) {error(mutation.error,// A gauge recorded on a closed inspection is kept for traceability.- mutation.error.code === "23503"- ? "Gauge is used elsewhere. Set it to Inactive instead."- : "Failed to delete gauge"+ getDatabaseErrorMessage(mutation.error, "Failed to delete gauge", {+ referenced: "Gauge is used elsewhere. Set it to Inactive instead."+ }))));diff --git a/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx b/apps/erp/app/routes/x+/quality+/issue-types.$id.tsxindex 3c210fd924..7cdc2f30d9 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {@@ -81,7 +81,7 @@ export async function action({ request }: ActionFunctionArgs) {updatedBy: userId});- if (updateIssueType.error?.code === "23505") {+ if (isUniqueViolation(updateIssueType.error)) {return validationError({fieldErrors: { name: "An issue type with this name already exists" }});diff --git a/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsxindex a94373085b..265cdaaed9 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -50,10 +50,11 @@ export async function action({ request, params }: ActionFunctionArgs) {const { error: deleteIssueTypeError } = await deleteIssueType(client, id);if (deleteIssueTypeError) {- const errorMessage =- deleteIssueTypeError.code === "23503"- ? "Non-conformance type is used elsewhere, cannot delete"- : "Failed to delete issue type";+ const errorMessage = getDatabaseErrorMessage(+ deleteIssueTypeError,+ "Failed to delete issue type",+ { referenced: "Non-conformance type is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.issueTypes}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/quality+/issue-types.new.tsx b/apps/erp/app/routes/x+/quality+/issue-types.new.tsxindex 617eea22d1..5a83d255c1 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.new.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.new.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import {getIssueTypeByName,@@ -61,7 +61,7 @@ export async function action({ request }: ActionFunctionArgs) {createdBy: userId,customFields: setCustomFields(formData)});- if (insertIssueType.error?.code === "23505") {+ if (isUniqueViolation(insertIssueType.error)) {return validationError({fieldErrors: { name: "An issue type with this name already exists" }});diff --git a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsxindex add5144526..94dc2e900c 100644--- a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx+++ b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx@@ -7,6 +7,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Json } from "@carbon/database";import { getLogger } from "@carbon/logger";import type { TrackedEntityAttributes } from "@carbon/utils";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { requireCompanyRecord } from "~/modules/shared/shared.server";@@ -174,7 +175,7 @@ export async function action({ request, context }: ActionFunctionArgs) {if (error) {logger.error("Failed to update serial tracking", { error });// Check if error is due to unique constraint violation- if (error.message?.includes("duplicate key value")) {+ if (isUniqueViolation(error)) {return data({ error: "Serial number already exists for this item" },{ status: 400 }diff --git a/apps/erp/app/routes/x+/resources+/failure-modes.delete.$failureModeId.tsx b/apps/erp/app/routes/x+/resources+/failure-modes.delete.$failureModeId.tsxindex cb3c62c011..2c1c177265 100644--- a/apps/erp/app/routes/x+/resources+/failure-modes.delete.$failureModeId.tsx+++ b/apps/erp/app/routes/x+/resources+/failure-modes.delete.$failureModeId.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -53,10 +53,11 @@ export async function action({ request, params }: ActionFunctionArgs) {failureModeId);if (deleteFailureModeError) {- const errorMessage =- deleteFailureModeError.code === "23503"- ? "Failure mode is used elsewhere, cannot delete"- : "Failed to delete failure mode";+ const errorMessage = getDatabaseErrorMessage(+ deleteFailureModeError,+ "Failed to delete failure mode",+ { referenced: "Failure mode is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.failureModes}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx b/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsxindex c914cc5033..f85f868afb 100644--- a/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx+++ b/apps/erp/app/routes/x+/resources+/maintenance.delete.$dispatchId.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -56,10 +56,11 @@ export async function action({ request, params }: ActionFunctionArgs) {dispatchId);if (deleteError) {- const errorMessage =- deleteError.code === "23503"- ? "Dispatch has related records, cannot delete"- : "Failed to delete maintenance dispatch";+ const errorMessage = getDatabaseErrorMessage(+ deleteError,+ "Failed to delete maintenance dispatch",+ { referenced: "Dispatch has related records, cannot delete" }+ );throw redirect(`${path.to.maintenanceDispatches}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.delete.$scheduleId.tsx b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.delete.$scheduleId.tsxindex 7d2cd821eb..10edd9bda2 100644--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.delete.$scheduleId.tsx+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.delete.$scheduleId.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -56,10 +56,11 @@ export async function action({ request, params }: ActionFunctionArgs) {scheduleId);if (deleteError) {- const errorMessage =- deleteError.code === "23503"- ? "Schedule has related dispatches, cannot delete"- : "Failed to delete maintenance schedule";+ const errorMessage = getDatabaseErrorMessage(+ deleteError,+ "Failed to delete maintenance schedule",+ { referenced: "Schedule has related dispatches, cannot delete" }+ );throw redirect(`${path.to.maintenanceSchedules}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx b/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsxindex 501a8cd6f8..98cfb07666 100644--- a/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-portals.delete.$id.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { deleteCustomerPortal } from "@carbon/ee/customer-portals.server";import { requireFeature } from "@carbon/ee/plan.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -64,10 +64,11 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId);if (deleteCustomerPortalError) {- const errorMessage =- deleteCustomerPortalError.code === "23503"- ? "Customer portal is used elsewhere, cannot delete"- : "Failed to delete customer portal";+ const errorMessage = getDatabaseErrorMessage(+ deleteCustomerPortalError,+ "Failed to delete customer portal",+ { referenced: "Customer portal is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.customerPortals}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/sales+/no-quote-reasons.delete.$id.tsx b/apps/erp/app/routes/x+/sales+/no-quote-reasons.delete.$id.tsxindex 9f3b205263..0afbf23447 100644--- a/apps/erp/app/routes/x+/sales+/no-quote-reasons.delete.$id.tsx+++ b/apps/erp/app/routes/x+/sales+/no-quote-reasons.delete.$id.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -53,10 +53,11 @@ export async function action({ request, params }: ActionFunctionArgs) {id);if (deleteNoQuoteReasonError) {- const errorMessage =- deleteNoQuoteReasonError.code === "23503"- ? "No quote reason is used elsewhere, cannot delete"- : "Failed to delete noQuote reason";+ const errorMessage = getDatabaseErrorMessage(+ deleteNoQuoteReasonError,+ "Failed to delete noQuote reason",+ { referenced: "No quote reason is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.noQuoteReasons}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/sales+/return-reasons.delete.$id.tsx b/apps/erp/app/routes/x+/sales+/return-reasons.delete.$id.tsxindex 022eff8a05..35c3d3a00c 100644--- a/apps/erp/app/routes/x+/sales+/return-reasons.delete.$id.tsx+++ b/apps/erp/app/routes/x+/sales+/return-reasons.delete.$id.tsx@@ -5,7 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";@@ -53,10 +53,11 @@ export async function action({ request, params }: ActionFunctionArgs) {id);if (deleteReturnReasonError) {- const errorMessage =- deleteReturnReasonError.code === "23503"- ? "Return reason is used elsewhere, cannot delete"- : "Failed to delete return reason";+ const errorMessage = getDatabaseErrorMessage(+ deleteReturnReasonError,+ "Failed to delete return reason",+ { referenced: "Return reason is used elsewhere, cannot delete" }+ );throw redirect(`${path.to.returnReasons}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsxindex cf7ac5a470..bee24174ae 100644--- a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx@@ -5,9 +5,9 @@import { assertIsPost, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { validator } from "@carbon/form";+import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { ServiceSummary } from "~/modules/items";@@ -90,6 +90,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(updatedSupplierPart.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (updatedSupplierPart.error) {return { success: false, message: "Failed to update supplier part" };}diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsxindex e2a22ef914..fa5cdfbe1b 100644--- a/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx@@ -4,8 +4,9 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { validator } from "@carbon/form";+import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { useNavigate, useParams } from "react-router";import type { ServiceSummary } from "~/modules/items";@@ -43,6 +44,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(createServiceSupplier.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (createServiceSupplier.error) {return {success: false,diff --git a/apps/erp/app/routes/x+/settings+/planning.tsx b/apps/erp/app/routes/x+/settings+/planning.tsxnew file mode 100644index 0000000000..0f51c742f5--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/planning.tsx@@ -0,0 +1,455 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validator } from "@carbon/form";+import { getLogger } from "@carbon/logger";+import { Heading, ScrollArea, VStack } from "@carbon/react";+import { redirect } from "@carbon/utils";+import { parseTime } from "@internationalized/date";+import { msg } from "@lingui/core/macro";+import { Trans } from "@lingui/react/macro";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, useLoaderData } from "react-router";+import { z } from "zod";+import SettingsSectionHeader from "~/components/SettingsSectionHeader";+import {+ forecastConsumptionValidator,+ getCompanySettings,+ getItemPostingGroupResponsibilities,+ mrpScheduleValidator,+ planningHorizonValidator,+ rescheduleToleranceValidator,+ setDefaultPlanningHorizonDays,+ setDefaultResponsibleEmployee,+ setForecastConsumptionWindow,+ setLocationResponsibleEmployee,+ setRescheduleToleranceDays,+ setSkipApprovalForPlanningPurchaseOrders,+ updateMrpRunTimeSetting,+ upsertItemPostingGroupResponsibility+} from "~/modules/settings";+import {+ ForecastConsumptionCard,+ MrpScheduleCard,+ PlanningHorizonCard,+ PlanningPurchaseOrderApprovalCard,+ RescheduleToleranceCard,+ ResponsibleEmployeeCard+} from "~/modules/settings/ui/Planning";+import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++const logger = getLogger("erp", "settings", "planning");++export const handle: Handle = {+ breadcrumb: msg`Planning`,+ to: path.to.planningSettings+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings"+ });++ const [companySettings, locations, itemGroups, responsibilities] =+ await Promise.all([+ getCompanySettings(client, companyId),+ client+ .from("location")+ .select("id, name, responsibleEmployee")+ .eq("companyId", companyId)+ .order("name"),+ client+ .from("itemPostingGroup")+ .select("id, name")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name"),+ getItemPostingGroupResponsibilities(client, companyId)+ ]);++ if (!companySettings.data) {+ throw redirect(+ path.to.settings,+ await flash(+ request,+ error(companySettings.error, "Failed to get company settings")+ )+ );+ }++ // A failed list read renders as "no locations / groups / owners", which+ // reads as a clean company; log it so it is not silent.+ for (const [name, read] of [+ ["location", locations],+ ["itemPostingGroup", itemGroups],+ ["itemPostingGroupResponsibility", responsibilities]+ ] as const) {+ if (read.error) {+ logger.error("Failed to load planning settings", {+ companyId,+ table: name,+ error: read.error+ });+ }+ }++ return {+ defaultResponsibleEmployee:+ companySettings.data.defaultResponsibleEmployee ?? null,+ rescheduleToleranceDays: companySettings.data.rescheduleToleranceDays ?? 7,+ defaultPlanningHorizonDays:+ companySettings.data.defaultPlanningHorizonDays ?? null,+ forecastConsumptionBackwardPeriods:+ companySettings.data.forecastConsumptionBackwardPeriods ?? 4,+ forecastConsumptionForwardPeriods:+ companySettings.data.forecastConsumptionForwardPeriods ?? 1,+ mrpRunTime: companySettings.data.mrpRunTime ?? null,+ skipApprovalForPlanningPurchaseOrders:+ companySettings.data.skipApprovalForPlanningPurchaseOrders ?? true,+ locations: locations.data ?? [],+ itemGroups: itemGroups.data ?? [],+ responsibilities: responsibilities.data ?? []+ };+}++const employeeIdValidator = z.string().optional();++export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "settings"+ });++ const formData = await request.formData();+ const intent = formData.get("intent");++ switch (intent) {+ case "setCompanyDefault": {+ const parsedEmployeeId = employeeIdValidator.safeParse(+ formData.get("employeeId") ?? undefined+ );+ if (!parsedEmployeeId.success) {+ return data(+ { success: false, message: "Invalid employee" },+ { status: 400 }+ );+ }+ const employeeId = parsedEmployeeId.data;+ if (+ employeeId &&+ !(await isActiveCompanyEmployee(client, companyId, employeeId))+ ) {+ return {+ success: false,+ message: "Choose an employee of this company"+ };+ }+ const result = await setDefaultResponsibleEmployee(client, {+ companyId,+ employeeId: employeeId || null+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return { success: false, message: "Failed to update company default" };+ }+ return { success: true, message: "Company default updated" };+ }+ case "setLocation": {+ const locationId = formData.get("locationId");+ if (typeof locationId !== "string" || !locationId) {+ return { success: false, message: "Location is required" };+ }+ const parsedEmployeeId = employeeIdValidator.safeParse(+ formData.get("employeeId") ?? undefined+ );+ if (!parsedEmployeeId.success) {+ return data(+ { success: false, message: "Invalid employee" },+ { status: 400 }+ );+ }+ const employeeId = parsedEmployeeId.data;+ if (+ employeeId &&+ !(await isActiveCompanyEmployee(client, companyId, employeeId))+ ) {+ return {+ success: false,+ message: "Choose an employee of this company"+ };+ }+ const result = await setLocationResponsibleEmployee(client, {+ companyId,+ locationId,+ employeeId: employeeId || null,+ userId+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return {+ success: false,+ message: "Failed to update location ownership"+ };+ }+ // No row back: the location is not this company's, or the user lacks+ // resources_update and row-level security matched nothing.+ if ((result.data?.length ?? 0) === 0) {+ return {+ success: false,+ message: "You do not have permission to change this location"+ };+ }+ return { success: true, message: "Location ownership updated" };+ }+ case "setItemGroup": {+ const locationId = formData.get("locationId");+ const itemPostingGroupId = formData.get("itemPostingGroupId");+ if (+ typeof locationId !== "string" ||+ !locationId ||+ typeof itemPostingGroupId !== "string" ||+ !itemPostingGroupId+ ) {+ return {+ success: false,+ message: "Location and item group are required"+ };+ }+ const parsedEmployeeId = employeeIdValidator.safeParse(+ formData.get("employeeId") ?? undefined+ );+ if (!parsedEmployeeId.success) {+ return data(+ { success: false, message: "Invalid employee" },+ { status: 400 }+ );+ }+ const employeeId = parsedEmployeeId.data;+ if (+ employeeId &&+ !(await isActiveCompanyEmployee(client, companyId, employeeId))+ ) {+ return {+ success: false,+ message: "Choose an employee of this company"+ };+ }+ const result = await upsertItemPostingGroupResponsibility(client, {+ companyId,+ locationId,+ itemPostingGroupId,+ employeeId: employeeId || null,+ userId+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return {+ success: false,+ message: "Failed to update item group ownership"+ };+ }+ return { success: true, message: "Item group ownership updated" };+ }+ case "setPlanningPurchaseOrderApproval": {+ const enabled = formData.get("enabled") === "true";+ const result = await setSkipApprovalForPlanningPurchaseOrders(client, {+ companyId,+ enabled+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return { success: false, message: "Failed to update the setting" };+ }+ return {+ success: true,+ message: enabled+ ? "Planning purchase orders skip approval"+ : "Planning purchase orders need approval"+ };+ }+ case "setTolerance": {+ const validation = await validator(rescheduleToleranceValidator).validate(+ formData+ );+ if (validation.error) {+ return {+ success: false,+ message: "Tolerance must be between 0 and 365 days"+ };+ }+ const result = await setRescheduleToleranceDays(client, {+ companyId,+ days: validation.data.days+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return { success: false, message: "Failed to update tolerance" };+ }+ return { success: true, message: "Reschedule tolerance updated" };+ }+ case "setPlanningHorizon": {+ const validation = await validator(planningHorizonValidator).validate(+ formData+ );+ if (validation.error) {+ return {+ success: false,+ message: "Planning horizon must be a whole number of days"+ };+ }+ const result = await setDefaultPlanningHorizonDays(client, {+ companyId,+ days: validation.data.days ?? null+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return { success: false, message: "Failed to update planning horizon" };+ }+ return { success: true, message: "Planning horizon updated" };+ }+ case "setForecastConsumption": {+ const validation = await validator(forecastConsumptionValidator).validate(+ formData+ );+ if (validation.error) {+ return {+ success: false,+ message: "Consumption window must be between 0 and 52 weeks"+ };+ }+ const result = await setForecastConsumptionWindow(client, {+ companyId,+ backwardPeriods: validation.data.backwardPeriods,+ forwardPeriods: validation.data.forwardPeriods+ });+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return {+ success: false,+ message: "Failed to update forecast consumption"+ };+ }+ return { success: true, message: "Forecast consumption updated" };+ }+ case "setMrpSchedule": {+ const validation =+ await validator(mrpScheduleValidator).validate(formData);+ if (validation.error) {+ return {+ success: false,+ message: "Choose a time for the daily MRP run"+ };+ }+ const { mrpSchedule, mrpRunTime } = validation.data;+ const result = await updateMrpRunTimeSetting(+ client,+ companyId,+ mrpSchedule === "Daily" && mrpRunTime+ ? parseTime(mrpRunTime).toString()+ : null+ );+ if (result.error) {+ logger.error("Failed to save planning setting", {+ companyId,+ intent,+ error: result.error+ });+ return { success: false, message: "Failed to update MRP schedule" };+ }+ return { success: true, message: "MRP schedule updated" };+ }+ default:+ return { success: false, message: `Unknown intent '${String(intent)}'` };+ }+}++export default function PlanningSettingsRoute() {+ const {+ defaultResponsibleEmployee,+ rescheduleToleranceDays,+ defaultPlanningHorizonDays,+ forecastConsumptionBackwardPeriods,+ forecastConsumptionForwardPeriods,+ mrpRunTime,+ skipApprovalForPlanningPurchaseOrders,+ locations,+ itemGroups,+ responsibilities+ } = useLoaderData<typeof loader>();++ return (+ <ScrollArea className="w-full h-[calc(100dvh-var(--topbar-height)-var(--content-inset))]">+ <VStack+ spacing={4}+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"+ >+ <Heading size="h3">+ <Trans>Planning</Trans>+ </Heading>++ <SettingsSectionHeader>+ <Trans>MRP Suggestions</Trans>+ </SettingsSectionHeader>+ <MrpScheduleCard mrpRunTime={mrpRunTime} />+ <RescheduleToleranceCard+ rescheduleToleranceDays={rescheduleToleranceDays}+ />+ <PlanningHorizonCard+ defaultPlanningHorizonDays={defaultPlanningHorizonDays}+ />+ <ForecastConsumptionCard+ backwardPeriods={forecastConsumptionBackwardPeriods}+ forwardPeriods={forecastConsumptionForwardPeriods}+ />+ <PlanningPurchaseOrderApprovalCard+ skipApprovalForPlanningPurchaseOrders={+ skipApprovalForPlanningPurchaseOrders+ }+ />++ <SettingsSectionHeader>+ <Trans>Ownership</Trans>+ </SettingsSectionHeader>+ <ResponsibleEmployeeCard+ defaultResponsibleEmployee={defaultResponsibleEmployee}+ locations={locations}+ itemGroups={itemGroups}+ responsibilities={responsibilities}+ />+ </VStack>+ </ScrollArea>+ );+}diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsxindex c2ec023ed2..4072d622c2 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx@@ -7,7 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { data, useNavigate, useParams } from "react-router";import {@@ -67,7 +67,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (createSupplierContact.error) {let errorMessage = "Failed to create supplier contact";- if (createSupplierContact.error?.message?.includes("duplicate key value")) {+ if (isUniqueViolation(createSupplierContact.error)) {const contact = await client.from("contact").select("id")diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsxindex 8dc5a77ac7..b4fb901d80 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx@@ -5,7 +5,7 @@import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";+import { getDatabaseErrorMessage, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { deleteSupplierLocation } from "~/modules/purchasing";import { path } from "~/utils/path";@@ -32,10 +32,11 @@ export async function action({ request, params }: ActionFunctionArgs) {supplierLocationId);if (deleteSupplierLocationError) {- const errorMessage =- deleteSupplierLocationError.code === "23503"- ? "Supplier location is used elsewhere, cannot delete"- : "Failed to delete supplier location";+ const errorMessage = getDatabaseErrorMessage(+ deleteSupplierLocationError,+ "Failed to delete supplier location",+ { referenced: "Supplier location is used elsewhere, cannot delete" }+ );throw redirect(path.to.supplierLocations(supplierId),await flash(request, error(deleteSupplierLocationError, errorMessage))diff --git a/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx b/apps/erp/app/routes/x+/tool+/$itemId.planning.tsxindex 55cb9cfd3d..78a70ed22b 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.planning.tsx@@ -19,6 +19,7 @@ import {import { ItemPlanningForm } from "~/modules/items/ui/Item";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";import { getLocationsList } from "~/modules/resources";+import { isActiveCompanyEmployee } from "~/modules/shared/shared.server";import { getUserDefaults } from "~/modules/users/users.server";import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";@@ -90,7 +91,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts"});@@ -104,6 +105,24 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}+ // The column references the global user table, so the database would take+ // a person from another company, or one since deactivated.+ if (+ validation.data.responsibleEmployee &&+ !(await isActiveCompanyEmployee(+ client,+ companyId,+ validation.data.responsibleEmployee+ ))+ ) {+ return validationError({+ fieldErrors: {+ responsibleEmployee: "Choose an employee of this company"+ },+ formId: validation.formId+ });+ }+const updateToolPlanning = await upsertItemPlanning(client, {...validation.data,itemId,diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsxindex bf568f7b52..f038ca2189 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx@@ -5,9 +5,9 @@import { assertIsPost, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { validator } from "@carbon/form";+import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { redirect } from "@carbon/utils";+import { isUniqueViolation, redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { ToolSummary } from "~/modules/items";@@ -90,6 +90,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(updatedSupplierPart.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (updatedSupplierPart.error) {return { success: false, message: "Failed to update supplier part" };}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsxindex 230b36b262..c187c07789 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx@@ -4,8 +4,9 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { validator } from "@carbon/form";+import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { useNavigate, useParams } from "react-router";import type { ToolSummary } from "~/modules/items";@@ -43,6 +44,15 @@ export async function action({ request, params }: ActionFunctionArgs) {customFields: setCustomFields(formData)});+ // buyMethod_part_supplier_unique: one supplier part per item and supplier+ if (isUniqueViolation(createToolSupplier.error)) {+ return validationError({+ fieldErrors: {+ supplierId: "This item already has a supplier part for this supplier"+ }+ });+ }+if (createToolSupplier.error) {return {success: false,diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex bb0bb2d6bc..0d1eb42360 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -250,6 +250,8 @@ export const path = {generatePath(`${api}/production/kpi/${key}`),purchaseInvoice: (id: string) =>generatePath(`${api}/purchase-invoice/${id}`),+ purchaseOrderFinalize: (id: string) =>+ generatePath(`${api}/purchasing/purchase-order/${id}/finalize`),purchasesReportLines: `${api}/accounting/purchase-lines`,purchasingKpi: (key: string) =>generatePath(`${api}/purchasing/kpi/${key}`),@@ -1840,6 +1842,7 @@ export const path = {pickingListTracked: (pickingListId: string, lineId: string) =>generatePath(`${x}/picking-list/${pickingListId}/tracked/${lineId}`),pickingSchedule: `${x}/picking-list/schedule`,+ planningSettings: `${x}/settings/planning`,postJournalEntry: (id: string) =>generatePath(`${x}/journal-entry/${id}/post`),priceOverride: (id: string) => generatePath(`${x}/sales/price-list/${id}`),diff --git a/apps/erp/test/apply-production-planning-date-actions.test.ts b/apps/erp/test/apply-production-planning-date-actions.test.tsnew file mode 100644index 0000000000..532ddc17a4--- /dev/null+++ b/apps/erp/test/apply-production-planning-date-actions.test.ts@@ -0,0 +1,288 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely as KyselyClient,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";+import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>+ Array.isArray(strings)+ ? strings.reduce(+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),+ ""+ )+ : String(strings)+}));++const { applyProductionPlanningDateActions, nextJobPriority } = await import(+ "../app/modules/production/production.service"+);++// The Postgres wire is the boundary: each statement is recorded, and the rows+// "the database" answers with are chosen by what the statement is.+type Responder = (query: CompiledQuery) => unknown[];++class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ constructor(private readonly respond: Responder) {+ super();+ }+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ this.sent.push(query);+ return { rows: this.respond(query) as R[] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+}++function database(respond: Responder) {+ const driver = new RecordingDriver(respond);+ const db = new KyselyClient<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ }) as unknown as Kysely<KyselyDatabase>;+ return { db, driver };+}++const is = {+ claim: (q: CompiledQuery) =>+ /^update "planningAction" set "status" = \$1/.test(q.sql) &&+ q.parameters.includes("Actioned"),+ jobs: (q: CompiledQuery) =>+ /^select "id", "locationId", "deadlineType" from "job"/.test(q.sql),+ siblings: (q: CompiledQuery) =>+ /^select "id", "locationId", "dueDate", "priority", "deadlineType" from "job"/.test(+ q.sql+ ),+ dates: (q: CompiledQuery) => /UPDATE "job" AS j\s+SET "dueDate"/.test(q.sql),+ reopen: (q: CompiledQuery) =>+ /UPDATE "planningAction" AS a\s+SET "status" = 'Open'/.test(q.sql)+};++const ids = (rows: string[]) => rows.map((id) => ({ id }));+const scope = { companyId: "c1", userId: "u1" };++const moveA = {+ planningActionId: "a1",+ jobId: "job-a",+ suggestedDate: "2026-11-02"+};+const moveB = {+ planningActionId: "a2",+ jobId: "job-b",+ suggestedDate: "2026-11-02"+};++function everythingLands(q: CompiledQuery): unknown[] {+ if (is.claim(q)) return ids(["a1", "a2"]);+ if (is.jobs(q)) {+ return [+ { id: "job-a", locationId: "loc", deadlineType: "Soft Deadline" },+ { id: "job-b", locationId: "loc", deadlineType: "ASAP" }+ ];+ }+ if (is.siblings(q)) {+ // one job already on the target date+ return [+ {+ id: "job-x",+ locationId: "loc",+ dueDate: "2026-11-02",+ priority: 4,+ deadlineType: "Soft Deadline"+ }+ ];+ }+ if (is.dates(q)) return ids(["job-a", "job-b"]);+ return [];+}++describe("nextJobPriority", () => {+ it("starts at 0 with no siblings, goes after the last, or before a lower rank", () => {+ expect(nextJobPriority([], "Soft Deadline")).toBe(0);+ expect(+ nextJobPriority(+ [{ priority: 4, deadlineType: "Soft Deadline" }],+ "Soft Deadline"+ )+ ).toBe(5);+ expect(+ nextJobPriority([{ priority: 4, deadlineType: "Soft Deadline" }], "ASAP")+ ).toBe(2);+ expect(+ nextJobPriority(+ [+ { priority: 2, deadlineType: "ASAP" },+ { priority: 4, deadlineType: "Soft Deadline" }+ ],+ "Hard Deadline"+ )+ ).toBe(3);+ });+});++describe("applyProductionPlanningDateActions", () => {+ it("claims, reads twice and writes every date and priority in one statement", async () => {+ const { db, driver } = database(everythingLands);+ const result = await applyProductionPlanningDateActions(db, {+ ...scope,+ actions: [moveA, moveB]+ });+ expect(result).toEqual({+ applied: ["a1", "a2"],+ alreadyApplied: [],+ refused: []+ });+ expect(driver.sent.filter(is.claim)).toHaveLength(1);+ expect(driver.sent.filter(is.jobs)).toHaveLength(1);+ expect(driver.sent.filter(is.siblings)).toHaveLength(1);+ expect(driver.sent.filter(is.dates)).toHaveLength(1);+ expect(driver.sent).toHaveLength(4);+ });++ // job-a (Soft Deadline) goes after the sibling at 4 → 5; job-b (ASAP) goes+ // before both → half of the first priority, 2. Each placement sees the one+ // before it, as the sequential writes did.+ it("ranks moved jobs among the jobs already on the date, in turn", async () => {+ const { db, driver } = database(everythingLands);+ await applyProductionPlanningDateActions(db, {+ ...scope,+ actions: [moveA, moveB]+ });+ const write = driver.sent.find(is.dates)!;+ expect(write.parameters).toEqual(+ expect.arrayContaining(["job-a", "2026-11-02", 5, "job-b", 2])+ );+ expect(write.parameters).toEqual(+ expect.arrayContaining(["Draft", "Planned", "c1"])+ );+ });++ // An MRP run between the page's read and the claim can move an Open action's+ // date in place. The claim RETURNS the row's date, and that is what is+ // written; the page's date is only the fallback for a row that has none.+ it("applies the date from the claim, not from the page", async () => {+ const { db, driver } = database((q) =>+ is.claim(q)+ ? [+ { id: "a1", suggestedDate: "2026-11-09", suggestedQuantity: null },+ { id: "a2", suggestedDate: null, suggestedQuantity: null }+ ]+ : everythingLands(q)+ );+ await applyProductionPlanningDateActions(db, {+ ...scope,+ actions: [moveA, moveB]+ });+ const write = driver.sent.find(is.dates)!;+ expect(write.parameters).toEqual(+ expect.arrayContaining(["job-a", "2026-11-09", "job-b", "2026-11-02"])+ );+ expect(write.parameters).not.toContain("2026-11-02\u0000");+ // The siblings read asks for the claimed date, not the page's.+ const siblings = driver.sent.find(is.siblings)!;+ expect(siblings.parameters).toContain("2026-11-09");+ });++ // The job form hides the due-date field for "No Deadline", so a date written+ // under that type could be neither seen nor edited on the job, and the+ // priority would carry the undated weight. The date apply restates the type+ // as the Order path does.+ it("gives a No Deadline job a Soft Deadline with its date", async () => {+ const { db, driver } = database((q) =>+ is.jobs(q)+ ? [+ { id: "job-a", locationId: "loc", deadlineType: "No Deadline" },+ { id: "job-b", locationId: "loc", deadlineType: "ASAP" }+ ]+ : everythingLands(q)+ );+ await applyProductionPlanningDateActions(db, {+ ...scope,+ actions: [moveA, moveB]+ });+ const write = driver.sent.find(is.dates)!;+ expect(write.sql).toContain(+ `"deadlineType" = v."deadlineType"::"deadlineType"`+ );+ // job-a ranks as a Soft Deadline: after the sibling at 4 → 5, not before it.+ expect(write.parameters).toEqual(+ expect.arrayContaining(["job-a", "2026-11-02", "Soft Deadline", 5])+ );+ expect(write.parameters).not.toContain("No Deadline");+ // A job that already has a dated type keeps it.+ expect(write.parameters).toEqual(+ expect.arrayContaining(["job-b", "ASAP", 2])+ );+ });++ it("leaves an action another apply already claimed alone", async () => {+ const { db, driver } = database((q) =>+ is.claim(q) ? ids(["a2"]) : everythingLands(q)+ );+ const result = await applyProductionPlanningDateActions(db, {+ ...scope,+ actions: [moveA, moveB]+ });+ expect(result.alreadyApplied).toEqual(["a1"]);+ expect(result.applied).toEqual(["a2"]);+ const write = driver.sent.find(is.dates)!;+ expect(write.parameters).not.toContain("job-a");+ });++ // job-a was released to the floor after the page loaded: the guarded UPDATE+ // leaves it, and its action goes back to Open for review.+ it("un-claims an action whose job left Draft / Planned", async () => {+ const { db, driver } = database((q) => {+ if (is.dates(q)) return ids(["job-b"]);+ if (is.reopen(q)) return ids(["a1"]);+ return everythingLands(q);+ });+ const result = await applyProductionPlanningDateActions(db, {+ ...scope,+ actions: [moveA, moveB]+ });+ expect(result.refused).toEqual([{ id: "a1", jobId: "job-a" }]);+ expect(result.applied).toEqual(["a2"]);+ expect(driver.sent.find(is.reopen)!.parameters).toEqual(+ expect.arrayContaining(["a1", "c1"])+ );+ });++ it("sends nothing for an empty batch", async () => {+ const { db, driver } = database(everythingLands);+ await applyProductionPlanningDateActions(db, { ...scope, actions: [] });+ expect(driver.sent).toHaveLength(0);+ });+});diff --git a/apps/erp/test/apply-purchasing-planning-actions.test.ts b/apps/erp/test/apply-purchasing-planning-actions.test.tsnew file mode 100644index 0000000000..b78b610b78--- /dev/null+++ b/apps/erp/test/apply-purchasing-planning-actions.test.ts@@ -0,0 +1,353 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely as KyselyClient,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";+import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));+vi.mock("@carbon/server-functions", () => ({ serverFns: {} }));+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>+ Array.isArray(strings)+ ? strings.reduce(+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),+ ""+ )+ : String(strings)+}));++const { applyPurchasingPlanningActions } = await import(+ "../app/modules/purchasing/purchasing.service"+);++// The Postgres wire is the boundary. Each statement the apply sends is+// recorded, and the rows "the database" answers with are chosen by what the+// statement is — the claim, a line write, a read, the un-claim.+type Responder = (query: CompiledQuery) => unknown[];++class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ constructor(private readonly respond: Responder) {+ super();+ }+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ this.sent.push(query);+ return { rows: this.respond(query) as R[] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+}++function database(respond: Responder) {+ const driver = new RecordingDriver(respond);+ const db = new KyselyClient<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ }) as unknown as Kysely<KyselyDatabase>;+ return { db, driver };+}++const is = {+ claim: (q: CompiledQuery) =>+ /^update "planningAction" set "status" = \$1/.test(q.sql) &&+ q.parameters.includes("Actioned"),+ dates: (q: CompiledQuery) =>+ /UPDATE "purchaseOrderLine" AS l\s+SET "requiredDate"/.test(q.sql),+ quantities: (q: CompiledQuery) =>+ /UPDATE "purchaseOrderLine" AS l\s+SET "purchaseQuantity"/.test(q.sql),+ lines: (q: CompiledQuery) => /^select .* from "purchaseOrderLine" as "pol"/.test(q.sql),+ currencies: (q: CompiledQuery) => /^select .* from "currencies"/.test(q.sql),+ cancels: (q: CompiledQuery) => /^delete from "purchaseOrderLine"/.test(q.sql),+ reopen: (q: CompiledQuery) =>+ /UPDATE "planningAction" AS a\s+SET "status" = 'Open'/.test(q.sql),+ drop: (q: CompiledQuery) => /^delete from "planningAction"/.test(q.sql)+};++const ids = (rows: string[]) => rows.map((id) => ({ id }));++const scope = { companyId: "c1", companyGroupId: "g1", userId: "u1" };++const expedite = {+ planningActionId: "a-date",+ type: "Expedite" as const,+ lineId: "pol-date",+ purchaseOrderId: "po1",+ suggestedDate: "2026-11-02",+ suggestedQuantity: null+};+const increase = {+ planningActionId: "a-qty",+ type: "Increase" as const,+ lineId: "pol-qty",+ purchaseOrderId: "po2",+ suggestedDate: null,+ // inventory units; the line below converts at 10 per purchase unit+ suggestedQuantity: 55+};+const cancel = {+ planningActionId: "a-cancel",+ type: "Cancel" as const,+ lineId: "pol-cancel",+ purchaseOrderId: "po3",+ suggestedDate: null,+ suggestedQuantity: null+};++const qtyLine = {+ id: "pol-qty",+ supplierUnitPrice: 2,+ supplierShippingCost: 0,+ purchaseQuantity: 4,+ taxPercent: 0.1,+ supplierTaxAmount: 0.8,+ conversionFactor: 10,+ currencyCode: "USD"+};++// Answers as if every write lands: the claim takes every id, each line write+// returns its lines, the quantity read returns the line and its currency.+function everythingLands(q: CompiledQuery): unknown[] {+ if (is.claim(q)) return ids(["a-date", "a-qty", "a-cancel"]);+ if (is.dates(q)) return ids(["pol-date"]);+ if (is.lines(q)) return [qtyLine];+ if (is.currencies(q)) return [{ code: "USD", decimalPlaces: 2 }];+ if (is.quantities(q)) return ids(["pol-qty"]);+ if (is.cancels(q)) return ids(["pol-cancel"]);+ return [];+}++describe("applyPurchasingPlanningActions", () => {+ it("applies a mixed batch as one statement per kind, inside one transaction", async () => {+ const { db, driver } = database(everythingLands);+ const result = await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [expedite, increase, cancel]+ });++ expect(result).toEqual({+ applied: ["a-date", "a-qty", "a-cancel"],+ alreadyApplied: [],+ refused: [],+ failed: []+ });+ // one claim, one date write, one lines read, one currency read, one+ // quantity write, one cancel — and nothing per action+ expect(driver.sent.filter(is.claim)).toHaveLength(1);+ expect(driver.sent.filter(is.dates)).toHaveLength(1);+ expect(driver.sent.filter(is.quantities)).toHaveLength(1);+ expect(driver.sent.filter(is.cancels)).toHaveLength(1);+ expect(driver.sent.filter(is.reopen)).toHaveLength(0);+ expect(driver.sent).toHaveLength(6);+ });++ it("claims only Open rows, and every write keeps the Draft / Planned guard", async () => {+ const { db, driver } = database(everythingLands);+ await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [expedite, increase, cancel]+ });+ const claim = driver.sent.find(is.claim)!;+ expect(claim.parameters).toEqual(+ expect.arrayContaining(["Open", "c1", "a-date", "a-qty", "a-cancel"])+ );+ for (const write of driver.sent.filter(+ (q) => is.dates(q) || is.quantities(q) || is.cancels(q)+ )) {+ expect(write.sql).toMatch(+ /"purchaseOrderId" in \(+select "id" from "purchaseOrder"/i+ );+ expect(write.parameters).toEqual(+ expect.arrayContaining(["Draft", "Planned", "c1"])+ );+ }+ const cancels = driver.sent.find(is.cancels)!;+ expect(cancels.sql).toContain('coalesce("quantityReceived"');+ expect(cancels.sql).toContain('coalesce("quantityInvoiced"');+ // a draft invoice line's RESTRICT reference refuses the line, not the batch+ expect(cancels.sql).toMatch(+ /not exists \(select "purchaseInvoiceLine"\."id" from "purchaseInvoiceLine"/+ );+ });++ // 55 inventory units at 10 per purchase unit is 5.5 → 6 purchase units, and+ // the stored tax amount follows the new base (2 × 6 at 10% = 1.20).+ it("converts a quantity to whole purchase units and restates the tax pair", async () => {+ const { db, driver } = database(everythingLands);+ await applyPurchasingPlanningActions(db, { ...scope, actions: [increase] });+ const write = driver.sent.find(is.quantities)!;+ expect(write.parameters).toEqual(+ expect.arrayContaining(["pol-qty", 6, 0.1, 1.2])+ );+ });++ // MRP measures a line by what it still has to bring (`quantityToReceive`). A+ // PO reopened from planning can carry a receipt: 55 inventory units still to+ // come is 6 purchase units ON TOP of the 2 received — 8 on the line, tax+ // 2 × 8 at 10% = 1.60. Writing 6 would have dropped what arrived.+ it("adds what was already received to the quantity still to come", async () => {+ const { db, driver } = database((q) =>+ is.lines(q) ? [{ ...qtyLine, quantityReceived: 2 }] : everythingLands(q)+ );+ await applyPurchasingPlanningActions(db, { ...scope, actions: [increase] });+ const write = driver.sent.find(is.quantities)!;+ expect(write.parameters).toEqual(+ expect.arrayContaining(["pol-qty", 8, 0.1, 1.6])+ );+ });++ // A PO with no currency is in the company's base currency. It used to fail+ // every quantity change with "Currency (none) has no precision".+ it("prices a PO with no currency in the company's base currency", async () => {+ const { db, driver } = database((q) =>+ is.lines(q)+ ? [{ ...qtyLine, currencyCode: null, baseCurrencyCode: "USD" }]+ : everythingLands(q)+ );+ const result = await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [increase]+ });+ expect(result.failed).toEqual([]);+ expect(result.applied).toEqual(["a-qty"]);+ expect(driver.sent.find(is.currencies)!.parameters).toContain("USD");+ });++ // An MRP run between the page's read and the claim can move an Open action's+ // quantity or date in place. The claim RETURNS the row's values, and those+ // are what is written: 75 inventory units at 10 per purchase unit is+ // 7.5 → 8, tax 2 × 8 at 10% = 1.60 — not the page's 55.+ it("applies the quantity and date from the claim, not from the page", async () => {+ const { db, driver } = database((q) =>+ is.claim(q)+ ? [+ { id: "a-date", suggestedDate: "2026-11-09", suggestedQuantity: null },+ { id: "a-qty", suggestedDate: null, suggestedQuantity: 75 }+ ]+ : everythingLands(q)+ );+ await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [expedite, increase]+ });+ const dates = driver.sent.find(is.dates)!;+ expect(dates.parameters).toEqual(+ expect.arrayContaining(["pol-date", "2026-11-09"])+ );+ expect(dates.parameters).not.toContain("2026-11-02");+ const quantities = driver.sent.find(is.quantities)!;+ expect(quantities.parameters).toEqual(+ expect.arrayContaining(["pol-qty", 8, 0.1, 1.6])+ );+ expect(quantities.parameters).not.toContain(6);+ });++ // Another apply took the row first: its line is never written here.+ it("leaves an action another apply already claimed alone", async () => {+ const { db, driver } = database((q) =>+ is.claim(q) ? ids(["a-qty"]) : everythingLands(q)+ );+ const result = await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [expedite, increase]+ });+ expect(result.alreadyApplied).toEqual(["a-date"]);+ expect(result.applied).toEqual(["a-qty"]);+ expect(driver.sent.filter(is.dates)).toHaveLength(0);+ });++ // The PO was sent after the page loaded: the guarded write changes nothing,+ // the action goes back to Open for review, in the same transaction.+ it("un-claims an action whose write was refused", async () => {+ const { db, driver } = database((q) => {+ if (is.dates(q)) return [];+ if (is.reopen(q)) return ids(["a-date"]);+ return everythingLands(q);+ });+ const result = await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [expedite, increase]+ });+ expect(result.refused).toEqual([{ id: "a-date", purchaseOrderId: "po1" }]);+ expect(result.applied).toEqual(["a-qty"]);+ const reopen = driver.sent.find(is.reopen)!;+ expect(reopen.parameters).toEqual(expect.arrayContaining(["a-date", "c1"]));+ expect(driver.sent.filter(is.drop)).toHaveLength(0);+ });++ // An MRP run meanwhile wrote a fresh Open row for the same need, so the+ // un-claim would collide with the natural-key index: the claimed row is+ // deleted instead, as releasePlanningActionClaim does.+ it("deletes a refused action that a fresh MRP row has replaced", async () => {+ const { db, driver } = database((q) => {+ if (is.dates(q)) return [];+ if (is.reopen(q)) return [];+ return everythingLands(q);+ });+ await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [expedite]+ });+ const drop = driver.sent.find(is.drop)!;+ expect(drop.parameters).toEqual(+ expect.arrayContaining(["a-date", "c1", "Actioned"])+ );+ });++ it("reports a line whose currency has no precision, and un-claims it", async () => {+ const { db, driver } = database((q) => {+ if (is.currencies(q)) return [];+ if (is.reopen(q)) return ids(["a-qty"]);+ return everythingLands(q);+ });+ const result = await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: [increase]+ });+ expect(result.failed).toEqual([+ { id: "a-qty", message: "Currency USD has no precision" }+ ]);+ expect(result.applied).toEqual([]);+ expect(driver.sent.filter(is.quantities)).toHaveLength(0);+ expect(driver.sent.filter(is.reopen)).toHaveLength(1);+ });++ it("sends nothing for an empty batch", async () => {+ const { db, driver } = database(everythingLands);+ const result = await applyPurchasingPlanningActions(db, {+ ...scope,+ actions: []+ });+ expect(result.applied).toEqual([]);+ expect(driver.sent).toHaveLength(0);+ });+});diff --git a/apps/erp/test/planned-orders-from-actions.test.ts b/apps/erp/test/planned-orders-from-actions.test.tsnew file mode 100644index 0000000000..fdaefff263--- /dev/null+++ b/apps/erp/test/planned-orders-from-actions.test.ts@@ -0,0 +1,196 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));++import {+ openNewSupplyActions,+ plannedOrdersFromActions,+ productionOrdersFromActions,+ supplierConversionFactor+} from "../app/modules/production/ui/Planning/planned-orders-from-actions";++type Action = Parameters<typeof plannedOrdersFromActions>[0][number];++const action = (overrides: Partial<Action> = {}): Action => ({+ type: "Order",+ status: "Open",+ purchaseOrderLineId: null,+ jobId: null,+ periodId: "w1",+ suggestedQuantity: 10,+ suggestedDate: "2026-10-05",+ latestOrderDate: "2026-07-07",+ isASAP: true,+ supplierId: "sup1",+ policyName: "Fixed Reorder Quantity",+ reason: null,+ triggerValues: null,+ ...overrides+});++// RW-010: the drawer sized ten-unit orders per day in the browser while MRP+// wrote one action per week, after folding the first shortfall into PO000001+// as an Increase. The drawer now lists exactly the item's Order actions.+describe("openNewSupplyActions", () => {+ it("keeps only the open suggestions for new supply of the kind asked", () => {+ const order = action({ periodId: "w1" });+ const later = action({ periodId: "w2", suggestedDate: "2026-10-11" });+ const actions = [+ order,+ action({ type: "Increase", purchaseOrderLineId: "pol1" }),+ action({ type: "Expedite", purchaseOrderLineId: "pol4" }),+ action({ status: "Dismissed", periodId: "w3" }),+ action({ type: "Make", periodId: "w4" }),+ later+ ];+ expect(openNewSupplyActions(actions, "Order")).toEqual([order, later]);+ });++ it("treats an item with no actions as nothing to order", () => {+ expect(openNewSupplyActions(undefined, "Make")).toEqual([]);+ });+});++describe("plannedOrdersFromActions", () => {+ it("lists one order per weekly action, on the action's own week", () => {+ const orders = plannedOrdersFromActions(+ [+ action({ suggestedQuantity: 40 }),+ action({+ periodId: "w2",+ suggestedQuantity: 50,+ suggestedDate: "2026-10-11",+ latestOrderDate: "2026-07-13",+ isASAP: false+ })+ ],+ { conversionFactor: 1, supplierId: "sup1" }+ );+ expect(+ orders.map(({ quantity, dueDate, startDate, periodId }) => ({+ quantity,+ dueDate,+ startDate,+ periodId+ }))+ ).toEqual([+ {+ quantity: 40,+ dueDate: "2026-10-05",+ startDate: "2026-07-07",+ periodId: "w1"+ },+ {+ quantity: 50,+ dueDate: "2026-10-11",+ startDate: "2026-07-13",+ periodId: "w2"+ }+ ]);+ });++ it("converts inventory units to whole purchase units, rounding up", () => {+ const [order] = plannedOrdersFromActions(+ [action({ suggestedQuantity: 40 })],+ { conversionFactor: 12 }+ );+ expect(order.quantity).toBe(4);+ });++ it("keeps the quantity when the conversion factor is not usable", () => {+ const [order] = plannedOrdersFromActions(+ [action({ suggestedQuantity: 40 })],+ { conversionFactor: 0 }+ );+ expect(order.quantity).toBe(40);+ });++ it("orders from the row's supplier, else the action's", () => {+ const [chosen] = plannedOrdersFromActions([action()], {+ conversionFactor: 1,+ supplierId: "sup2"+ });+ const [fallback] = plannedOrdersFromActions([action()], {+ conversionFactor: 1+ });+ expect(chosen.supplierId).toBe("sup2");+ expect(fallback.supplierId).toBe("sup1");+ });++ it("dates an action with no order-by date from its due date", () => {+ const [order] = plannedOrdersFromActions(+ [action({ latestOrderDate: null })],+ { conversionFactor: 1 }+ );+ expect(order.startDate).toBe("2026-10-05");+ });++ it("carries the policy attribution, numbers only", () => {+ const [order] = plannedOrdersFromActions(+ [+ action({+ reason: "Below reorder point",+ triggerValues: { reorderPoint: 5, reorderQuantity: 10, note: "x" }+ })+ ],+ { conversionFactor: 1 }+ );+ expect(order.policyName).toBe("Fixed Reorder Quantity");+ expect(order.reason).toBe("Below reorder point");+ expect(order.triggerValues).toEqual({+ reorderPoint: 5,+ reorderQuantity: 10+ });+ });+});++describe("productionOrdersFromActions", () => {+ it("lists one job per Make action in the item's own units", () => {+ expect(+ productionOrdersFromActions([+ action({+ type: "Make",+ suggestedQuantity: 5,+ suggestedDate: "2026-10-04",+ latestOrderDate: "2026-09-20",+ isASAP: true+ })+ ])+ ).toEqual([+ {+ startDate: "2026-09-20",+ dueDate: "2026-10-04",+ periodId: "w1",+ quantity: 5,+ isASAP: true+ }+ ]);+ });+});++describe("supplierConversionFactor", () => {+ const suppliers = [+ { supplierId: "sup1", conversionFactor: 12 },+ { supplierId: "sup2", conversionFactor: 1 }+ ];++ it("reads the chosen supplier's factor", () => {+ expect(supplierConversionFactor(suppliers, "sup1")).toBe(12);+ });++ it("is 1 for a supplier with no part, or no supplier data", () => {+ expect(supplierConversionFactor(suppliers, "sup3")).toBe(1);+ expect(supplierConversionFactor(null, "sup1")).toBe(1);+ });+});diff --git a/apps/erp/test/planning-action-scope.test.ts b/apps/erp/test/planning-action-scope.test.tsnew file mode 100644index 0000000000..eabb85241a--- /dev/null+++ b/apps/erp/test/planning-action-scope.test.ts@@ -0,0 +1,145 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ actionsOfTypes,+ PLANNING_ACTIONS_COLUMN,+ PLANNING_ASSIGNEE_COLUMN,+ resolvePlanningActionScope+} from "../app/modules/production/ui/Planning/planning-action-scope";++describe("resolvePlanningActionScope", () => {+ it("passes the grid's own filters through untouched and restricts nothing", () => {+ const filters = [{ column: "type", operator: "eq", value: "Part" }];+ expect(+ resolvePlanningActionScope({ filters })+ ).toEqual({+ gridFilters: filters,+ actionTypes: undefined,+ actionAssignees: undefined+ });+ });++ it("strips the Actions-column filter and returns it as the RPC's type argument", () => {+ const { gridFilters, actionTypes } = resolvePlanningActionScope({+ filters: [+ { column: "type", operator: "eq", value: "Part" },+ { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" }+ ],+ });+ expect(gridFilters).toEqual([+ { column: "type", operator: "eq", value: "Part" }+ ]);+ expect(actionTypes).toEqual(["Cancel"]);+ });++ it("accepts the multi-value `in` encoding, without duplicates", () => {+ expect(+ resolvePlanningActionScope({+ filters: [+ {+ column: PLANNING_ACTIONS_COLUMN,+ operator: "in",+ value: "Cancel,Order"+ },+ { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" }+ ],+ }).actionTypes+ ).toEqual(["Cancel", "Order"]);+ });++ it("strips the Assignee filter and returns its people as the RPC's assignees argument", () => {+ expect(+ resolvePlanningActionScope({+ filters: [+ { column: "type", operator: "eq", value: "Part" },+ { column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "user-a" }+ ]+ })+ ).toEqual({+ gridFilters: [{ column: "type", operator: "eq", value: "Part" }],+ actionTypes: undefined,+ actionAssignees: ["user-a"]+ });+ });++ it("accepts several people in the `in` encoding, without duplicates", () => {+ expect(+ resolvePlanningActionScope({+ filters: [+ {+ column: PLANNING_ASSIGNEE_COLUMN,+ operator: "in",+ value: "user-a,user-b"+ },+ { column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "user-a" }+ ]+ }).actionAssignees+ ).toEqual(["user-a", "user-b"]);+ });++ it("returns assignees and types together — the RPC matches both on the same action", () => {+ expect(+ resolvePlanningActionScope({+ filters: [+ { column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "Cancel" },+ { column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "user-a" }+ ]+ })+ ).toEqual({+ gridFilters: [],+ actionTypes: ["Cancel"],+ actionAssignees: ["user-a"]+ });+ });++ it("an empty Assignee filter value restricts nothing", () => {+ expect(+ resolvePlanningActionScope({+ filters: [{ column: PLANNING_ASSIGNEE_COLUMN, operator: "eq", value: "" }]+ }).actionAssignees+ ).toBeUndefined();+ });++ it("an empty filter value restricts nothing", () => {+ expect(+ resolvePlanningActionScope({+ filters: [{ column: PLANNING_ACTIONS_COLUMN, operator: "eq", value: "" }],+ }).actionTypes+ ).toBeUndefined();+ });+});++describe("actionsOfTypes", () => {+ const actions = [+ { id: "a", type: "Expedite" },+ { id: "b", type: "Defer" },+ { id: "c", type: "Expedite" },+ { id: "d", type: "Cancel" }+ ] as const;++ it("shows every action when the grid is not filtered by type", () => {+ expect(actionsOfTypes(actions, undefined)).toEqual([...actions]);+ expect(actionsOfTypes(actions, null)).toEqual([...actions]);+ expect(actionsOfTypes(actions, [])).toEqual([...actions]);+ });++ it("keeps only the filtered type, in the original order", () => {+ expect(actionsOfTypes(actions, ["Expedite"]).map((a) => a.id)).toEqual([+ "a",+ "c"+ ]);+ });++ it("keeps any of several filtered types", () => {+ expect(+ actionsOfTypes(actions, ["Cancel", "Defer"]).map((a) => a.id)+ ).toEqual(["b", "d"]);+ });++ it("returns nothing when the row has no action of the filtered type", () => {+ expect(actionsOfTypes(actions, ["Order"])).toEqual([]);+ });+});diff --git a/apps/erp/test/planning-fence.test.ts b/apps/erp/test/planning-fence.test.tsnew file mode 100644index 0000000000..2efa5ad58a--- /dev/null+++ b/apps/erp/test/planning-fence.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ actionsInsideFence,+ effectiveFenceDate,+ isInsideFence,+ splitOrdersByFence+} from "../app/modules/production/ui/Planning/planning-fence";++describe("isInsideFence", () => {+ it("has no fence when the fence date is null", () => {+ expect(isInsideFence("2027-01-01", null)).toBe(true);+ });++ it("is inclusive of the fence date itself", () => {+ expect(isInsideFence("2026-10-31", "2026-10-31")).toBe(true);+ expect(isInsideFence("2026-11-01", "2026-10-31")).toBe(false);+ });++ it("keeps an undated suggestion visible", () => {+ expect(isInsideFence(null, "2026-10-31")).toBe(true);+ expect(isInsideFence(undefined, "2026-10-31")).toBe(true);+ });+});++describe("effectiveFenceDate", () => {+ it("prefers the on-screen override over the saved horizon", () => {+ expect(effectiveFenceDate("2026-10-31", "2026-12-30")).toBe("2026-12-30");+ });++ it("falls back to the saved horizon, then to no fence", () => {+ expect(effectiveFenceDate("2026-10-31", undefined)).toBe("2026-10-31");+ expect(effectiveFenceDate(null, undefined)).toBeNull();+ expect(effectiveFenceDate(undefined, null)).toBeNull();+ });++ it("has no fence when the planner cleared a saved horizon", () => {+ expect(effectiveFenceDate("2026-10-31", null)).toBeNull();+ });+});++describe("actionsInsideFence", () => {+ const actions = [+ // a Defer: its order sits inside the fence though the need is far out+ { id: "defer", horizonDate: "2026-10-08" },+ { id: "order-near", horizonDate: "2026-10-04" },+ { id: "order-far", horizonDate: "2026-11-29" }+ ];++ it("returns everything when there is no fence", () => {+ expect(actionsInsideFence(actions, null)).toBe(actions);+ });++ it("keeps only the actions dated on or before the fence", () => {+ expect(+ actionsInsideFence(actions, "2026-10-31").map((a) => a.id)+ ).toEqual(["defer", "order-near"]);+ });++ it("widening the fence brings the rest back", () => {+ expect(actionsInsideFence(actions, "2026-12-30")).toHaveLength(3);+ });+});++describe("splitOrdersByFence", () => {+ const orders = [+ { id: 1, dueDate: "2026-10-04" },+ { id: 2, dueDate: "2026-10-31" },+ { id: 3, dueDate: "2026-11-29" },+ { id: 4, dueDate: null }+ ];++ it("puts every order inside when there is no fence", () => {+ expect(splitOrdersByFence(orders, null)).toEqual({+ inside: orders,+ beyond: []+ });+ });++ it("splits on the required date, fence day included", () => {+ const { inside, beyond } = splitOrdersByFence(orders, "2026-10-31");+ expect(inside.map((o) => o.id)).toEqual([1, 2, 4]);+ expect(beyond.map((o) => o.id)).toEqual([3]);+ });+});diff --git a/apps/erp/test/planning-increase.test.ts b/apps/erp/test/planning-increase.test.tsnew file mode 100644index 0000000000..0501e04446--- /dev/null+++ b/apps/erp/test/planning-increase.test.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { chartedOrderQuantity } from "../app/modules/production/ui/Planning/planning-increase";++const increase = (+ periodId: string,+ status = "Open",+ suggestedQuantity = 2530+) => ({ type: "Increase", status, periodId, suggestedQuantity });++describe("chartedOrderQuantity", () => {+ it("charts an order at its open Increase", () => {+ expect(+ chartedOrderQuantity({+ quantity: 250,+ loadedQuantity: 250,+ increase: increase("w1")+ })+ ).toBe(2530);+ });++ it("charts the order as is with no Increase, or a dismissed one", () => {+ expect(+ chartedOrderQuantity({ quantity: 250, loadedQuantity: 250, increase: null })+ ).toBe(250);+ expect(+ chartedOrderQuantity({+ quantity: 250,+ loadedQuantity: 250,+ increase: increase("w1", "Dismissed")+ })+ ).toBe(250);+ });++ it("charts the planner's edit over the Increase", () => {+ expect(+ chartedOrderQuantity({+ quantity: 1000,+ loadedQuantity: 250,+ increase: increase("w1")+ })+ ).toBe(1000);+ });+});diff --git a/apps/erp/test/planning-job-editable.test.ts b/apps/erp/test/planning-job-editable.test.tsnew file mode 100644index 0000000000..a8e719b005--- /dev/null+++ b/apps/erp/test/planning-job-editable.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// The models barrel reaches the glossary's lingui macros, which vitest does not+// transform (same stub as Schedule/Kanban/date-utils.test.ts).+vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));++import { isJobEditableFromPlanning } from "../app/modules/production/production.models";++// Planning's Apply used a blocklist (Ready / In Progress / Paused), so a job+// completed, closed or cancelled after MRP ran could still be edited or+// re-cancelled from a stale action. Only an unreleased job may change.+describe("isJobEditableFromPlanning", () => {+ it("allows a job that is not released yet", () => {+ expect(isJobEditableFromPlanning("Draft")).toBe(true);+ expect(isJobEditableFromPlanning("Planned")).toBe(true);+ });++ it("refuses a job on the floor", () => {+ expect(isJobEditableFromPlanning("Ready")).toBe(false);+ expect(isJobEditableFromPlanning("In Progress")).toBe(false);+ expect(isJobEditableFromPlanning("Paused")).toBe(false);+ });++ it("refuses a job that is finished, closed or cancelled", () => {+ expect(isJobEditableFromPlanning("Completed")).toBe(false);+ expect(isJobEditableFromPlanning("Closed")).toBe(false);+ expect(isJobEditableFromPlanning("Cancelled")).toBe(false);+ });++ it("refuses a job with no status", () => {+ expect(isJobEditableFromPlanning(null)).toBe(false);+ expect(isJobEditableFromPlanning(undefined)).toBe(false);+ });+});diff --git a/apps/erp/test/planning-purchase-order.test.ts b/apps/erp/test/planning-purchase-order.test.tsnew file mode 100644index 0000000000..3ed80c1bb6--- /dev/null+++ b/apps/erp/test/planning-purchase-order.test.ts@@ -0,0 +1,215 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));++import { parseDate } from "@internationalized/date";+import {+ findPlanningPurchaseOrder,+ isPurchaseOrderEditableFromPlanning,+ planningPurchaseOrderWeek,+ purchaseOrderStatusType,+ taxPairForQuantity+} from "../app/modules/purchasing/purchasing.models";++// The planning gates used isPurchaseOrderLocked, a blocklist of sent+// statuses, so a PO waiting for approval (Needs Approval, To Review,+// Rejected) could still be edited from planning while MRP itself showed+// "Review on PO" for it.+describe("isPurchaseOrderEditableFromPlanning", () => {+ it("allows only a PO that is neither in approval nor sent", () => {+ const editable = purchaseOrderStatusType.filter(+ isPurchaseOrderEditableFromPlanning+ );+ expect(editable).toEqual(["Draft", "Planned"]);+ });++ it("refuses a PO in approval", () => {+ for (const status of ["Needs Approval", "To Review", "Rejected"] as const) {+ expect(isPurchaseOrderEditableFromPlanning(status)).toBe(false);+ }+ });++ it("refuses a PO with no status", () => {+ expect(isPurchaseOrderEditableFromPlanning(null)).toBe(false);+ expect(isPurchaseOrderEditableFromPlanning(undefined)).toBe(false);+ });+});++// A quantity change wrote purchaseQuantity alone. The extended price is a+// generated column and follows; the stored tax amount did not, so the line's+// tax pair stopped agreeing.+describe("taxPairForQuantity", () => {+ const line = {+ supplierUnitPrice: 10,+ supplierShippingCost: 0,+ purchaseQuantity: 10,+ taxPercent: 0.0625,+ supplierTaxAmount: 6.25+ };++ it("restates the amount at the line's rate for the new quantity", () => {+ expect(taxPairForQuantity(line, 20, 2)).toEqual({+ percent: 0.0625,+ amount: 12.5+ });+ });++ it("taxes shipping too, as the canonical base does", () => {+ expect(+ taxPairForQuantity({ ...line, supplierShippingCost: 4 }, 20, 2)+ ).toEqual({ percent: 0.0625, amount: 12.75 });+ });++ it("rounds at the currency's own precision", () => {+ expect(+ taxPairForQuantity(+ { ...line, supplierUnitPrice: 1000, taxPercent: 0.1 },+ 3,+ 0+ )+ ).toEqual({ percent: 0.1, amount: 300 });+ });++ it("derives the rate once for a line that holds only an amount", () => {+ expect(+ taxPairForQuantity({ ...line, taxPercent: null }, 20, 2)+ ).toEqual({ percent: 0.0625, amount: 12.5 });+ });++ it("keeps a tax-free line tax-free", () => {+ expect(+ taxPairForQuantity(+ { ...line, taxPercent: 0, supplierTaxAmount: 0 },+ 20,+ 2+ )+ ).toEqual({ percent: 0, amount: 0 });+ });+});++// Planning put every week's order for a supplier on one open PO, so+// finalizing it to send the first week also locked the later weeks, and MRP+// could no longer change them. Orders are now grouped one PO per supplier per+// week. 2026-10-06 is a Tuesday; its week starts on Sunday 2026-10-04.+describe("planningPurchaseOrderWeek", () => {+ const asOf = parseDate("2026-10-06");++ it("starts the week on Sunday, as the planning grid does", () => {+ expect(planningPurchaseOrderWeek("2026-10-10", asOf)).toBe("2026-10-04");+ expect(planningPurchaseOrderWeek("2026-10-11", asOf)).toBe("2026-10-11");+ });++ it("puts each week of a recurring buy in its own week", () => {+ expect(+ ["2026-10-07", "2026-11-01", "2026-11-29"].map((date) =>+ planningPurchaseOrderWeek(date, asOf)+ )+ ).toEqual(["2026-10-04", "2026-11-01", "2026-11-29"]);+ });++ it("puts a late or undated order in the current week", () => {+ expect(planningPurchaseOrderWeek("2026-09-20", asOf)).toBe("2026-10-04");+ expect(planningPurchaseOrderWeek(null, asOf)).toBe("2026-10-04");+ });+});++describe("findPlanningPurchaseOrder", () => {+ const asOf = parseDate("2026-10-06");+ const po = (+ id: string,+ requiredDates: (string | null)[],+ overrides: { supplierId?: string; currencyCode?: string | null } = {}+ ) => ({+ id,+ supplierId: "sup1",+ currencyCode: "USD",+ ...overrides,+ purchaseOrderLine: requiredDates.map((requiredDate) => ({ requiredDate }))+ });+ const target = (week: string) => ({+ supplierId: "sup1",+ currencyCode: "USD",+ week+ });++ it("reuses the PO that already has a line in the week", () => {+ const candidates = [po("oct", ["2026-10-07"]), po("nov", ["2026-11-03"])];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-11-01"), asOf)?.id+ ).toBe("nov");+ });++ it("does not add a later week to an open PO", () => {+ const candidates = [po("oct", ["2026-10-07"])];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-11-01"), asOf)+ ).toBeUndefined();+ });++ it("matches a late line to the current week", () => {+ const candidates = [po("late", [null, "2026-09-28"])];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-10-04"), asOf)?.id+ ).toBe("late");+ });++ it("takes the oldest PO when two cover the week", () => {+ const candidates = [+ po("older", ["2026-10-05"]),+ po("newer", ["2026-10-08"])+ ];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-10-04"), asOf)?.id+ ).toBe("older");+ });++ it("never reuses a PO in another currency or for another supplier", () => {+ const candidates = [+ po("eur", ["2026-10-07"], { currencyCode: "EUR" }),+ po("other", ["2026-10-07"], { supplierId: "sup2" })+ ];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-10-04"), asOf)+ ).toBeUndefined();+ });++ // PO000019 was raised before the weekly rule with lines due Oct 4 and+ // Nov 1; reusing it for any week it touched put a new order's two weeks+ // back on one PO.+ it("never reuses a PO with lines in several weeks", () => {+ const candidates = [po("mixed", ["2026-10-04", "2026-11-01"])];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-10-04"), asOf)+ ).toBeUndefined();+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-11-01"), asOf)+ ).toBeUndefined();+ });++ it("reuses a PO whose lines are all in the week", () => {+ const candidates = [+ po("mixed", ["2026-10-04", "2026-11-01"]),+ po("week", ["2026-10-04", null, "2026-10-09"])+ ];+ expect(+ findPlanningPurchaseOrder(candidates, target("2026-10-04"), asOf)?.id+ ).toBe("week");+ });++ it("never reuses a PO with no lines", () => {+ expect(+ findPlanningPurchaseOrder([po("empty", [])], target("2026-10-04"), asOf)+ ).toBeUndefined();+ });+});diff --git a/apps/erp/test/planning-review.test.ts b/apps/erp/test/planning-review.test.tsnew file mode 100644index 0000000000..7a6215c66f--- /dev/null+++ b/apps/erp/test/planning-review.test.ts@@ -0,0 +1,310 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));++import {+ isPlanningActionLate,+ isStaleRelease,+ planningActionDot,+ planningActionNeedsReview,+ purchaseOrderPlanningMenu,+ type ReviewableAction+} from "../app/modules/production/ui/Planning/planning-review";++const poAction = (overrides: Partial<ReviewableAction>): ReviewableAction => ({+ type: "Increase",+ requiresManualAction: true,+ purchaseOrderLineId: "line-1",+ purchaseOrderStatus: "To Receive",+ purchaseOrderLinePromisedDate: null,+ jobId: null,+ jobStatus: null,+ ...overrides+});++describe("planningActionNeedsReview", () => {+ it("reviews an action on a PO that was sent", () => {+ expect(planningActionNeedsReview(poAction({}))).toBe(true);+ });++ it("applies once the PO is reopened, before MRP runs again", () => {+ // MRP's stamp still says review; the live status says Planned+ expect(+ planningActionNeedsReview(poAction({ purchaseOrderStatus: "Planned" }))+ ).toBe(false);+ });++ it("reviews a PO waiting for approval", () => {+ expect(+ planningActionNeedsReview(+ poAction({+ purchaseOrderStatus: "Needs Approval",+ requiresManualAction: false+ })+ )+ ).toBe(true);+ });++ it("reviews a date move on a promised line, even on a Planned PO", () => {+ for (const type of ["Expedite", "Defer"]) {+ expect(+ planningActionNeedsReview(+ poAction({+ type,+ purchaseOrderStatus: "Planned",+ purchaseOrderLinePromisedDate: "2026-10-20"+ })+ )+ ).toBe(true);+ }+ });++ it("applies a quantity change on a promised line", () => {+ expect(+ planningActionNeedsReview(+ poAction({+ purchaseOrderStatus: "Planned",+ purchaseOrderLinePromisedDate: "2026-10-20"+ })+ )+ ).toBe(false);+ });++ it("follows the job's live status", () => {+ const jobAction = poAction({+ purchaseOrderLineId: null,+ purchaseOrderStatus: null,+ jobId: "job-1"+ });+ expect(planningActionNeedsReview({ ...jobAction, jobStatus: "Ready" })).toBe(+ true+ );+ expect(+ planningActionNeedsReview({ ...jobAction, jobStatus: "Planned" })+ ).toBe(false);+ });++ it("falls back to MRP's stamp when the order was not read", () => {+ expect(+ planningActionNeedsReview(poAction({ purchaseOrderStatus: null }))+ ).toBe(true);+ expect(+ planningActionNeedsReview(+ poAction({ purchaseOrderStatus: null, requiresManualAction: false })+ )+ ).toBe(false);+ });+});++describe("purchaseOrderPlanningMenu", () => {+ it("offers reopen and a revision on a sent PO", () => {+ expect(+ purchaseOrderPlanningMenu({+ id: "po",+ status: "To Receive",+ orderDate: "2026-09-01"+ })+ ).toEqual({ canReopen: true, canReopenAsRevision: true, canFinalize: false });+ });++ it("offers no revision on a PO that never reached the supplier", () => {+ expect(+ purchaseOrderPlanningMenu({+ id: "po",+ status: "Needs Approval",+ orderDate: null+ })+ ).toEqual({+ canReopen: true,+ canReopenAsRevision: false,+ canFinalize: false+ });+ });++ it("offers finalize on a Draft or Planned PO", () => {+ for (const status of ["Draft", "Planned"] as const) {+ expect(+ purchaseOrderPlanningMenu({ id: "po", status, orderDate: null })+ ).toEqual({+ canReopen: false,+ canReopenAsRevision: false,+ canFinalize: true+ });+ }+ });++ it("offers nothing when the status is unknown", () => {+ expect(+ purchaseOrderPlanningMenu({ id: "po", status: null, orderDate: null })+ ).toEqual({+ canReopen: false,+ canReopenAsRevision: false,+ canFinalize: false+ });+ });+});++describe("planningActionDot", () => {+ const open = (type: string, isASAP: boolean) => ({+ type,+ status: "Open",+ isASAP+ });++ it("is red for an ASAP action that adds or advances supply", () => {+ for (const type of ["Order", "Make", "Expedite", "Increase"]) {+ expect(planningActionDot([open(type, true)])).toBe("red");+ }+ });++ it("is green for an on-time action that adds or advances supply", () => {+ for (const type of ["Order", "Make", "Expedite", "Increase"]) {+ expect(planningActionDot([open(type, false)])).toBe("green");+ }+ });++ it("is not lit by a Decrease, Defer or Cancel, whatever its flag", () => {+ for (const type of ["Decrease", "Defer", "Cancel"]) {+ expect(planningActionDot([open(type, true)])).toBeNull();+ expect(planningActionDot([open(type, false)])).toBeNull();+ }+ });++ it("follows the supply actions when a Decrease sits beside them", () => {+ expect(+ planningActionDot([open("Decrease", false), open("Increase", false)])+ ).toBe("green");+ expect(+ planningActionDot([open("Cancel", false), open("Order", true)])+ ).toBe("red");+ });++ it("is null when nothing is open", () => {+ expect(+ planningActionDot([{ type: "Order", status: "Dismissed", isASAP: true }])+ ).toBeNull();+ });+});++describe("isPlanningActionLate", () => {+ const today = "2026-10-06";+ const action = (type: string, suggestedDate: string) => ({+ type,+ status: "Open",+ isASAP: false,+ suggestedDate+ });++ it("marks an urgent action whose date has passed", () => {+ expect(isPlanningActionLate(action("Expedite", "2026-10-04"), today)).toBe(+ true+ );+ expect(isPlanningActionLate(action("Order", "2026-10-07"), today)).toBe(+ false+ );+ });++ // A Decrease is dated where its order sits; an overdue order is not a+ // late decrease.+ it("never marks a Decrease, Defer or Cancel late", () => {+ for (const type of ["Decrease", "Defer", "Cancel"]) {+ expect(isPlanningActionLate(action(type, "2026-10-04"), today)).toBe(+ false+ );+ }+ });++ it("never marks a dismissed action late", () => {+ expect(+ isPlanningActionLate(+ { ...action("Order", "2026-10-01"), status: "Dismissed" },+ today+ )+ ).toBe(false);+ });+});++describe("Release", () => {+ const today = "2026-10-06";+ const release = (suggestedDate: string, isASAP: boolean) => ({+ type: "Release",+ status: "Open",+ isASAP,+ suggestedDate+ });++ // Every planned order has one: a green dot for each would say nothing.+ it("lights the dot red once its day has come, and not before", () => {+ expect(planningActionDot([release(today, true)])).toBe("red");+ expect(planningActionDot([release("2026-10-20", false)])).toBeNull();+ expect(+ planningActionDot([+ release("2026-10-20", false),+ { type: "Order", status: "Open", isASAP: false }+ ])+ ).toBe("green");+ });++ it("is late once its day has passed, not on the day", () => {+ expect(isPlanningActionLate(release(today, true), today)).toBe(false);+ expect(isPlanningActionLate(release("2026-10-05", true), today)).toBe(true);+ });++ const target = {+ type: "Release",+ purchaseOrderLineId: "pol-1",+ purchaseOrderStatus: "Planned" as const,+ jobId: null,+ jobStatus: null+ };++ it("applies only while its order is Planned", () => {+ expect(isStaleRelease(target)).toBe(false);+ expect(+ isStaleRelease({ ...target, purchaseOrderStatus: "To Receive" })+ ).toBe(true);+ expect(+ isStaleRelease({+ ...target,+ purchaseOrderLineId: null,+ purchaseOrderStatus: null,+ jobId: "job-1",+ jobStatus: "Ready"+ })+ ).toBe(true);+ expect(+ isStaleRelease({+ ...target,+ purchaseOrderLineId: null,+ purchaseOrderStatus: null,+ jobId: "job-1",+ jobStatus: "Planned"+ })+ ).toBe(false);+ });++ it("keeps a Release whose order status was not read", () => {+ expect(isStaleRelease({ ...target, purchaseOrderStatus: null })).toBe(false);+ });++ it("is never stale for another action type", () => {+ expect(+ isStaleRelease({+ ...target,+ type: "Increase",+ purchaseOrderStatus: "To Receive"+ })+ ).toBe(false);+ });+});diff --git a/apps/erp/test/planning-week-geometry.test.ts b/apps/erp/test/planning-week-geometry.test.tsnew file mode 100644index 0000000000..8530a8f7eb--- /dev/null+++ b/apps/erp/test/planning-week-geometry.test.ts@@ -0,0 +1,40 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { planningWeekGeometry } from "../app/modules/production/ui/Planning/planning-week-geometry";++describe("planningWeekGeometry", () => {+ it("puts the zero line at the bottom when nothing is short", () => {+ const { zero, heights } = planningWeekGeometry([100, 50, 25]);+ expect(zero).toBe(100);+ expect(heights).toEqual([100, 50, 25]);+ });++ it("puts the zero line at the top when every week is short", () => {+ const { zero, heights } = planningWeekGeometry([-10, -40]);+ expect(zero).toBe(0);+ expect(heights).toEqual([25, 100]);+ });++ it("splits the strip in proportion to the stock above and the shortfall below", () => {+ // 300 above, 100 below: the line sits three quarters of the way down+ const { zero, heights } = planningWeekGeometry([300, 100, -100]);+ expect(zero).toBe(75);+ expect(heights).toEqual([75, 25, 25]);+ });++ it("gives a zero or missing week no bar", () => {+ const { heights } = planningWeekGeometry([10, 0, undefined, -10]);+ expect(heights).toEqual([50, 0, 0, 50]);+ });++ it("draws a flat line through the middle when there is nothing to scale to", () => {+ expect(planningWeekGeometry([0, undefined, 0])).toEqual({+ zero: 50,+ heights: [0, 0, 0]+ });+ expect(planningWeekGeometry([])).toEqual({ zero: 50, heights: [] });+ });+});diff --git a/apps/erp/test/update-purchase-order-line-schedule.test.ts b/apps/erp/test/update-purchase-order-line-schedule.test.tsnew file mode 100644index 0000000000..287f575a56--- /dev/null+++ b/apps/erp/test/update-purchase-order-line-schedule.test.ts@@ -0,0 +1,123 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely as KyselyClient,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";+import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));+vi.mock("@carbon/server-functions", () => ({ serverFns: {} }));+// The service's module graph reaches @carbon/onboarding, whose content builds+// Lingui `msg` descriptors at load; the macro is not compiled under vitest+// (same stub as production.service.test.ts).+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>+ Array.isArray(strings)+ ? strings.reduce(+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),+ ""+ )+ : String(strings)+}));++const { updatePurchaseOrderLineSchedule } = await import(+ "../app/modules/purchasing/purchasing.service"+);++// The drawer's inline edit of one open PO line: a quantity or a required date,+// with the Draft / Planned guard inside the one UPDATE so a PO sent after the+// route read it is left alone. (Planning's Cancel, which deletes a line, is+// set-based with the rest of Apply — apply-purchasing-planning-actions.test.ts.)++class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ constructor(private readonly returnedIds: string[]) {+ super();+ }+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ this.sent.push(query);+ return { rows: this.returnedIds.map((id) => ({ id })) as R[] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+}++function database(returnedIds: string[]) {+ const driver = new RecordingDriver(returnedIds);+ const db = new KyselyClient<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ }) as unknown as Kysely<KyselyDatabase>;+ return { db, driver };+}++const args = { lineId: "pol1", purchaseOrderId: "po1", companyId: "c1" };++describe("updatePurchaseOrderLineSchedule", () => {+ const dateChange = {+ lineId: "pol1",+ companyId: "c1",+ companyGroupId: "g1",+ userId: "u1",+ requiredDate: "2026-11-02"+ };++ it("updates the line only while its PO is Draft or Planned, in one statement", async () => {+ const { db, driver } = database(["pol1"]);+ // A date change reads nothing first, so the client is never used.+ await updatePurchaseOrderLineSchedule({} as never, db, dateChange);++ expect(driver.sent).toHaveLength(1);+ const [{ sql, parameters }] = driver.sent;+ expect(sql).toMatch(/^update "purchaseOrderLine" set "requiredDate" = \$1/);+ expect(sql).toMatch(+ /"purchaseOrderId" in \(select "id" from "purchaseOrder" where "companyId" = \$\d+ and "status" in \(\$\d+, \$\d+\)\)/+ );+ expect(parameters).toEqual(+ expect.arrayContaining(["pol1", "c1", "Draft", "Planned"])+ );+ });++ it("reports the line updated", async () => {+ const { db } = database(["pol1"]);+ expect(+ await updatePurchaseOrderLineSchedule({} as never, db, dateChange)+ ).toEqual({ updated: true, error: null });+ });++ it("reports nothing updated when the PO left Draft / Planned", async () => {+ const { db } = database([]);+ expect(+ await updatePurchaseOrderLineSchedule({} as never, db, dateChange)+ ).toEqual({ updated: false, error: null });+ });+});diff --git a/docs/content/docs/building/architecture.mdx b/docs/content/docs/building/architecture.mdxindex df70f4b13c..7fdd00f0e7 100644--- a/docs/content/docs/building/architecture.mdx+++ b/docs/content/docs/building/architecture.mdx@@ -494,9 +494,11 @@ await trigger("notify", {Event names are always `carbon/<something>`.-**Scheduled work** has two sources. Inngest cron schedules run application jobs: MRP every-three hours, exchange rates and audit archiving nightly. All of them are UTC, and any job that-needs a company's local day computes it inside the run. Database-level maintenance uses+**Scheduled work** has two sources. Inngest cron schedules run application jobs: MRP (a+fifteen-minute tick that plans each company every three hours, or once a day at the time+it sets on its own clock), exchange rates and audit archiving nightly. The cron schedules+themselves are UTC, and any job that needs a company's local day or time computes it inside+the run. Database-level maintenance usespg_cron [[14]](#g14) instead, for refreshing cached aggregate tables, sweeping the eventqueue and purging old notifications. pg_cron also decides when two application jobs run:every fifteen minutes it checks whether any notifications are due to be rolled into adiff --git a/docs/content/docs/platform/demo-data.mdx b/docs/content/docs/platform/demo-data.mdxindex 3f712466b6..b919749861 100644--- a/docs/content/docs/platform/demo-data.mdx+++ b/docs/content/docs/platform/demo-data.mdx@@ -100,7 +100,7 @@ Expected refusal. The company has customers or suppliers linked to another compaExpected refusal. Posted and voided card transactions cannot be deleted, so the demo-data wipe cannot clear the company. Nothing was written. Apply the template to a company without posted card transactions.### Material Planning, Scheduling or Priorities are empty right after applying-Planning runs as a separate background step once the demo data is committed: MRP for the company, then scheduling for every location with Ready, In Progress or Paused jobs. Give it a moment. If that step failed, the demo data stays and MRP fills in on its regular run every three hours.+Planning runs as a separate background step once the demo data is committed: MRP for the company, then scheduling for every location with Ready, In Progress or Paused jobs. Give it a moment. If that step failed, the demo data stays and MRP fills in on its next scheduled run (every three hours by default).### The Webhooks, API keys or Audit log screens are empty after applyingExpected. Templates never seed credentials, webhooks or audit history, and applying a template leaves any existing webhooks and API keys in place.diff --git a/docs/content/docs/reference/company-settings.mdx b/docs/content/docs/reference/company-settings.mdxindex e7bc082597..10586e9c87 100644--- a/docs/content/docs/reference/company-settings.mdx+++ b/docs/content/docs/reference/company-settings.mdx@@ -42,6 +42,11 @@ A user can belong to multiple companies and switch between them with the company<Field name="plmReleaseControl" type="text">The release-control policy for item revisions.</Field><Field name="kanbanOutput" type="enum">What a Kanban card prints: `label`, `qrcode`, or `url`.</Field><Field name="productLabelSize / shelfLabelSize" type="text">Default label sizes.</Field>+ <Field name="mrpRunTime" type="time">The time of day scheduled MRP runs, on the company's time zone. Empty keeps the default, every 3 hours. Edited from **Settings → Planning**. See [planning](/docs/reference/planning#when-it-runs).</Field>+ <Field name="defaultPlanningHorizonDays" type="number">How many days ahead the planning grids show actions and suggested orders, unless an item sets its own. Empty or 0 shows everything. Edited from **Settings → Planning**. See [planning horizon](/docs/reference/planning#planning-horizon).</Field>+ <Field name="rescheduleToleranceDays" type="number">How many days an open order may land from the date it is needed before MRP suggests an Expedite or Defer. Default 7. Edited from **Settings → Planning**. See [reschedule tolerance](/docs/reference/planning#reschedule-tolerance).</Field>+ <Field name="defaultResponsibleEmployee" type="text">The person a planning action is assigned to when no item, item group or location names one. Edited from **Settings → Planning**. See [planning ownership](/docs/reference/planning#planning-ownership).</Field>+ <Field name="forecastConsumptionBackwardPeriods / forecastConsumptionForwardPeriods" type="number">How many weeks before and after its own week a real order reaches to consume forecast (defaults 4 and 1). Edited from **Settings → Planning**. See [forecast consumption](/docs/reference/forecast).</Field><Field name="updateLeadTimesOnReceipt" type="boolean">Whether receiving recalculates supplier lead times.</Field><Field name="purchasePriceUpdateTiming" type="enum">When purchase prices refresh: `Purchase Invoice Post` or `Purchase Order Finalize`.</Field><Field name="maintenanceGenerateInAdvance / maintenanceAdvanceDays" type="boolean / number">Whether preventive maintenance is generated ahead of time, and by how many days (1–90).</Field>diff --git a/docs/content/docs/reference/forecast.mdx b/docs/content/docs/reference/forecast.mdxindex 47b618635f..e8885f8b34 100644--- a/docs/content/docs/reference/forecast.mdx+++ b/docs/content/docs/reference/forecast.mdx@@ -5,35 +5,39 @@ description: Enter expected future demand for a make part, week by week, so planA <Term id="demand-projection">demand projection</Term> is expected weekly demand for a part before sales orders exist. Planning nets projections against scheduled supply, explodes the part's method into component demand, and suggests required jobs and purchase orders.-Enter projections under **Production → Projections** in a 52-week grid, one part at a time. Each cell contains expected consumption for that week. The next <Term>MRP</Term> run reads saved values.+You enter projections under **Production → Demand Forecasts**, one part at a time, as a 52-week grid. Each cell is the quantity you expect to consume that week. Save it, and the next <Term>MRP</Term> run reads it.## What a projection isA projection lives on the `demandProjection` table, keyed by item, location, and a weekly `period` — one row per part / location / week with a `forecastQuantity` (`packages/database/supabase/migrations/20251020183630_mrp-projections.sql:3-25`). The `period` table is a shared, company-agnostic set of dated week buckets (`startDate`, `endDate`, `periodType`); Carbon creates them on demand as `getOrCreatePeriods` walks forward from today (`packages/database/supabase/migrations/20250610000433_demand-planning.sql:26-34`).-Only parts with `replenishmentSystem="Make"` can have projections (`apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx:195-202`). Purchased components receive derived demand through BOM explosion rather than direct projections.+Only **make parts** carry projections. The item picker on the form is fixed to `type="Part"` with `replenishmentSystem="Make"` (`apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx`), so you project the things you build. Their purchased components inherit demand through the BOM explosion, not through their own projection.<Callout type="note" title="Projection, not forecast">-Two tables look alike. `demandProjection` is your input — the numbers you type. `demandForecast` is planning's output — the exploded, per-component demand the <Term>MRP</Term> run writes back (`forecastMethod` = `"mrp"`). You never edit `demandForecast` by hand; it's rebuilt on every run (`packages/planning/src/mrp/mrp.ts:918-963`). The Projections screen only ever touches `demandProjection`.+Two tables look alike. `demandProjection` is your input — the numbers you type. `demandForecast` is planning's output — the exploded, per-component demand the <Term>MRP</Term> run writes back (`forecastMethod` = `"mrp"`). You never edit `demandForecast` by hand; it's rebuilt on every run (`packages/planning/src/mrp/mrp.ts`). The Demand Forecasts screen only ever touches `demandProjection`.</Callout>## How you enter one-The form is a drawer with a part, a location, and 52 numeric week cells grouped into four quarter tabs, plus a live bar-and-line chart of weekly and cumulative demand (`apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx:264-304`). Week 1 starts at the current week; each cell is labelled with its calendar date.+The form is a drawer with a part, a location, and 52 numeric week cells grouped into four quarter tabs, plus a live bar-and-line chart of weekly and cumulative demand (`apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionForm.tsx`). Week 1 starts at the current week; each cell is labelled with its calendar date.-On save, the action pairs each `week{i}` value with the matching `period` id and upserts the rows (`apps/erp/app/routes/x+/production+/projections.new.tsx:50-78`). A cell you set to zero is deleted rather than stored, so the grid stays sparse (`apps/erp/app/modules/production/production.service.ts:3780-3829`). Editing a part reloads its existing rows back into the grid; deleting a part's projections clears every future week for that item and location (`apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx:30-40`).+On save, the action pairs each `week{i}` value with the matching `period` id and upserts the rows (`apps/erp/app/routes/x+/production+/demand-forecasts.$itemId.$locationId.tsx`). A cell you set to zero is deleted rather than stored, so the grid stays sparse (`upsertDemandProjections`, `packages/ee/src/forecast.server.ts`). Editing a part reloads its existing rows back into the grid; deleting a part's projections clears every future week for that item and location (`apps/erp/app/routes/x+/production+/demand-forecasts.delete.$itemId.$locationId.tsx`).-The grid spans 52 weeks (`WEEKS_TO_PROJECT = 12 * 4`, `apps/erp/app/routes/x+/production+/projections.tsx:23`). The list view pivots the per-period rows back into week columns for scanning, labelling the first as "Present Week" (`apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx:60-103`). Creating, editing, and deleting projections all require the `production` permission.+The entry grid spans 52 weeks (`WEEKS_TO_PROJECT = 52` in both `demand-forecasts.new.tsx` and `demand-forecasts.$itemId.$locationId.tsx`). The list view shows the next 48 (`WEEKS_TO_PROJECT = 12 * 4`, `apps/erp/app/routes/x+/production+/demand-forecasts.tsx`), pivoting the per-period rows back into week columns for scanning and labelling the first as "Present Week" (`apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionTable.tsx`). Creating, editing, and deleting projections all require the `production` permission, and are available on the Business plan (the `FORECAST` feature, `packages/ee/src/plan.ts`).## How planning consumes it-Planning runs in-process from `@carbon/planning` (`runMrp`), and it reads `demandProjection` directly as a demand source (`packages/planning/src/mrp/mrp.ts:159-161`). A projected week's full quantity drives gross demand — open production you've already planned is *not* pre-subtracted here; instead firm job and purchase-order supply is credited exactly once during the BOM explosion's running balance, so a projection you're partway to covering doesn't get double-planned.+Planning runs in-process from `@carbon/planning` (`runMrp`), and it reads `demandProjection` directly as a demand source (`packages/planning/src/mrp/mrp.ts`). But a projection does not simply add to demand: **actual demand consumes the forecast**. Each MRP run nets every open sales order line and job-material line against the projections for the same part and location — first in the order's own week, then reaching backward and then forward a configurable number of weeks — and only the *unconsumed remainder* of the projection still drives demand. Ten forecast plus ten on order in the same week is ten of demand, not twenty; twelve on order against ten forecast is twelve.++The reach is set company-wide on the **Forecast Consumption** card under **Settings → Planning**: **Look back (weeks)** (default 4) and **Look ahead (weeks)** (default 1). That window is what heals gaps — if you forecast 10 in one week and 0 the next, a sales order landing in the empty week consumes the neighboring forecast instead of double-counting. Set both to 0 to net strictly within the same week. Each run persists what it consumed to `demandProjection.consumedQuantity`, so the planning screens, the item planning chart, and Inventory all read the same net number, and the edit form shows an "N consumed" note under each week that actual demand has claimed.++Sales orders consume at their full open quantity — a Make to Order line already covered by its linked job still consumes the forecast that predicted it, even though the job, not the line, is what drives supply. An order dated before the current week is still demand, but it consumes no forecast; an order with no date counts as due now and does consume. Forecast in past weeks simply falls out of the horizon; it never lingers as phantom demand.<Callout type="note" title="Projections don't double-plan production you've already got in flight">-A projection's full `forecastQuantity` enters gross demand at face value — it is *not* pre-netted against open production (`packages/planning/src/mrp/mrp.ts:430-461`). Firm job/PO supply is instead credited once through the BOM explosion's running on-hand/supply balance, so a projection partway covered by in-flight jobs isn't planned twice. Actual **sales orders** and **job material** demand are firm too — they're added in full alongside the projection (`packages/planning/src/mrp/mrp.ts:463-531`).+Open production is handled on the *supply* side, not by consumption: firm job/PO supply is credited exactly once through the BOM explosion's running on-hand/supply balance, so a projection partway covered by in-flight jobs isn't planned twice. Consumption is the *demand*-side reconciliation — forecast versus actual orders — and the two never overlap.</Callout>-That projection demand joins actual demand (open sales order lines and open job materials) in the gross-demand tally, and MRP explodes each make part's method to push component demand down the BOM. The result is written to `demandForecast` and to a `demandForecastSource` lineage table that tags every unit with where it came from: `"Sales Order"`, `"Job Material"`, or `"Demand Projection"` (`packages/planning/src/mrp/mrp.ts:653-712`). On a part's planning page you can open the demand for any week and see exactly which projections, orders, and parent jobs make it up (`apps/erp/app/modules/items/items.service.ts:695-753`).+That projection demand joins actual demand (open sales order lines and open job materials) in the gross-demand tally, and MRP explodes each make part's method to push component demand down the BOM. The result is written to `demandForecast` and to a `demandForecastSource` lineage table that tags every unit with where it came from: `"Sales Order"`, `"Job Material"`, or `"Demand Projection"` (`packages/planning/src/mrp/mrp.ts`). On a part's planning page you can open the demand for any week and see exactly which projections, orders, and parent jobs make it up (`apps/erp/app/modules/items/items.service.ts`).<Callout type="warning" title="MRP suggests; it never places the order">The run turns projected demand into *suggested* jobs and purchase orders. Nothing is created until you act on a suggestion. See [Planning (MRP)](/docs/reference/planning) for how those suggestions surface and how you convert them, and [Reordering policy](/docs/reference/reordering) for the per-part numbers (lead time, lot size, safety stock) that shape what a projection turns into.@@ -47,7 +51,7 @@ The run turns projected demand into *suggested* jobs and purchase orders. Nothin<Field name="Week 1 … Week 52">Expected quantity consumed in each weekly bucket, starting from the current week. A blank or zero cell stores nothing.</Field></FieldTable>-Projections are manual inputs. Carbon does not calculate them from history, seasonality, or a statistical model. Although the schema reserves `forecastMethod` and `confidence`, the Projections form does not write them. MRP provides the netting and BOM explosion.+Projections are manual inputs. Carbon does not calculate them from history, seasonality, or a statistical model. Although the schema reserves `forecastMethod` and `confidence`, the Demand Forecast form does not write them. MRP provides the netting and BOM explosion.<AgentContext>## Troubleshooting@@ -61,7 +65,7 @@ The item picker is fixed to parts with a **Make** replenishment system (`type="PCreating, editing, and deleting projections all require the **`production`** permission. Without it the actions are blocked. Have an admin grant production access.### I edited `demandForecast` but my change was overwritten-You never edit `demandForecast` by hand — it's planning's **output**, rebuilt on every <Term>MRP</Term> run (`forecastMethod = "mrp"`). Your input is `demandProjection`, edited only from the Projections screen. If you meant to change the projected numbers, edit them there and re-run MRP.+You never edit `demandForecast` by hand — it's planning's **output**, rebuilt on every <Term>MRP</Term> run (`forecastMethod = "mrp"`). Your input is `demandProjection`, edited only from the Demand Forecasts screen. If you meant to change the projected numbers, edit them there and re-run MRP.### Deleting a part's projection removed more than I expectedDeleting a part's projections clears **every future week** for that item and location (current week and beyond), not just the visible tab. It's an all-or-nothing clear per item/location, so delete only when you mean to wipe the whole forward projection.@@ -71,4 +75,10 @@ Open production you've already planned reduces what a projection drives — but### A zero cell isn't savedA blank or zero cell stores nothing — it's deleted rather than persisted, so the grid stays sparse. That's expected; only non-zero weeks become `demandProjection` rows.++### Planning shows less demand than my forecast+That's forecast consumption working. Open sales orders and job materials for the same part and location consume the projection (own week first, then backward/forward per **Settings → Planning**), and planning drives only actuals plus the unconsumed remainder — so forecast and real orders are never double-counted. The edit form's "consumed" note under a week shows how much actual demand has claimed. If you want strict same-week netting only, set both consumption windows to 0.++### A sales order in a week with no forecast still reduced a neighboring week+Also consumption, by design: the backward/forward window lets an order land in a gap between forecast entries and consume the nearest forecast instead of adding on top of it. Narrow the window in **Settings → Planning** if your forecasts are precise to the week.</AgentContext>diff --git a/docs/content/docs/reference/planning.mdx b/docs/content/docs/reference/planning.mdxindex 4ca5148bc3..0632390b8b 100644--- a/docs/content/docs/reference/planning.mdx+++ b/docs/content/docs/reference/planning.mdx@@ -9,13 +9,17 @@ Planning determines what to make or buy and in what quantity. Carbon's <Term>MRPPlanning has two distinct stages:-1. **MRP, explode and net.** The engine explodes demand through bills of material, nets it against on-hand plus open jobs and purchase orders, and writes period-bucketed demand forecasts (plus the demand and supply *actuals* it read). It does **not** apply <Term id="reorder-point">reorder points</Term> and does **not** create orders.-2. **Planning views, suggest a quantity.** The production and purchasing planning pages read those forecasts, project running stock week by week, and apply each item's **<Term id="reordering-policy">reorder policy</Term>** to propose a quantity to order.+1. **MRP, explode and net.** The engine explodes demand through bills of material, nets it against on-hand plus open jobs and purchase orders, and writes period-bucketed demand forecasts (plus the demand and supply *actuals* it read). It then sizes each shortage with the item's <Term id="reordering-policy">reorder policy</Term> and writes a <Term id="planning-action">planning action</Term> for it, and one for every open order whose date or quantity no longer fits.+2. **Planning views, show and apply.** The production and purchasing planning pages project running stock week by week, show the actions on each row, and let you apply them.<Callout type="note">-MRP **suggests, it never auto-orders.** The engine only writes forecasts; turning a suggestion into a real job or PO is an explicit action you take on the planning page.+MRP **suggests, it never auto-orders.** The engine writes forecasts and suggestions; turning a suggestion into a real job or PO, or moving an existing one, is an explicit action you take on the planning page.</Callout>+## When it runs++MRP recalculates on its own every 3 hours. To run it once a day instead, go to **Settings → Planning → MRP Schedule**, choose **Once a day**, and pick the hour; the hour is on your company's time zone. You can also run it yourself at any moment with **Recalculate** on the planning pages, whichever schedule is set; hover the button to see which schedule is active.+## What feeds it| Input | Source |@@ -32,12 +36,57 @@ Each item, per location, carries a **reordering policy** that decides how a sugg## From suggestion to order-An item's **<Term>replenishment system</Term>** determines where its shortage appears. *Make* items produce suggested <Term id="job">jobs</Term> on the production planning page; *Buy* items produce suggested POs on the purchasing page. Choosing **Order** creates a saved job or purchase order with status **"Planned"**, pending release into its normal lifecycle.+An item's **<Term>replenishment system</Term>** determines where its shortage appears. *Make* items produce suggested <Term id="job">jobs</Term> on the production planning page; *Buy* items produce suggested POs on the purchasing page. Choosing **Order** creates a saved job or purchase order with status **"Planned"**, pending release into its normal lifecycle. Purchase orders are grouped one per supplier per week, so each week's order is sent on its own and the later weeks stay open to planning changes.<Callout type="info">**"Planned"** is a real, saved job or PO that came from a planning suggestion and is waiting to be released — distinct from a hand-started **"Draft"**.</Callout>+## Reading the grid++Each row is an item at the location. **Stock Availability** draws the projected stock for every planning week as one strip; the CSV export keeps a column per week. **1st Negative On Hand** is the first week the projection goes below zero. **Latest Order Date** is the date you must order by to receive in time (the required date less the lead time); it turns red once it has passed. Open a row to see the order drawer.++## Planning actions++Every MRP run leaves a worklist on the planning pages. Each row's **Actions** column shows one chip per open action type, an **ASAP** flag when a suggestion is already late, and a muted count of the actions you dismissed. Expand the row to see each action with its target order, quantity, date and assignee; hover the action type for MRP's reason.++| Action | Target | What applying it does |+| --- | --- | --- |+| **Order** / **Make** | none yet | Opens the order drawer; the existing **Order** button creates the PO or job. |+| **Expedite** / **Defer** | an open PO line or job | Moves the required date (PO line) or the due date (job) to the suggested date. |+| **Increase** / **Decrease** | an open PO line or job | Sets the line's purchase quantity, or the job's quantity, to the suggested quantity. |+| **Cancel** | an open PO line or job | Deletes the PO line, or cancels the job, when nothing needs it. |++**Apply** is offered only while the target can still change from planning: a PO at **"Draft"** or **"Planned"**, a job at **"Draft"** or **"Planned"**. A PO that has been sent or is in approval, a job on the floor, or a PO line whose date the supplier has promised shows **Review** instead, and you make the change on the order itself. Select several rows and choose **Apply Suggested Changes** to apply every open action on them at once. Apply writes the suggestion as it is at that moment: if an MRP run refreshed the action after the page loaded, the refreshed quantity or date is what lands. A job that had no deadline gets a **Soft Deadline** with its new date. Cancelling a PO line deletes it, so it needs the purchasing delete permission.++<Callout type="info" title="A dismissed action stays dismissed until the need changes">+**Dismiss** hides an action you have decided not to take. The next MRP runs keep it hidden while the suggested quantity stays the same and the date moves by no more than the reschedule tolerance; a larger change reopens it. **Reopen** brings it back by hand. **Assign to Me** sets the owner, and MRP keeps a hand-set owner on later runs.+</Callout>++An applied action is finished: the next run re-evaluates the changed order and writes a fresh action only if something still does not fit.++<Screenshot label="Production planning grid with the Actions column and one row expanded to its action lines" caption="Each row carries its open actions; expand it to apply, dismiss or assign them." ratio="wide" />++## The order drawer++The drawer shows the item's suggested orders — the same Order or Make suggestions as the row's action list, one per week, refreshed each time MRP runs — and, below them, its **Open Jobs** (production) or **Open Orders** (purchasing). An open order at **"Draft"** or **"Planned"** can be edited in place: change its **Due Date** or **Quantity** in the grid and the order is saved. The **Suggestion** column shows the open action on that order, with the same Apply, Dismiss, Reopen and Assign controls as the grid. Suggested orders due after the row's planning horizon stay out of the drawer until you choose **N More After <date>**. The chart in the drawer marks the planning horizon.++## Planning horizon++The **Planning Horizon** column is a date per row: today plus the item's horizon in days. A row shows only the actions and suggested orders due on or before that date, so a long planning window does not bury next week's work. Set the company default in **Settings → Planning → Planning Horizon**, and override it per item on the item's planning tab (**Planning Horizon (Days)**). An item set to 0 shows everything MRP plans, whatever the company default.++Moving the date in the column widens or narrows that one row for this page view only; it never changes the item.++## Reschedule tolerance++MRP suggests **Expedite** or **Defer** only when an open order lands more than the tolerance away from the date it is needed. The default is 7 days. Set it in **Settings → Planning → Reschedule Tolerance**; 0 suggests a move for any date difference.++Two kinds of open order never get a change suggestion. An order due after the planning window (48 weeks) is outside what the check can judge, so it is left alone rather than offered for Cancel. An order that holds the item's safety stock or reorder point is never Cancelled, Decreased or Deferred; it can still be Expedited when demand needs it earlier.++## Planning ownership++Each action gets a <Term id="responsible-employee">responsible employee</Term>, resolved from the most specific setting that names one: the item at that location, then the item group at that location, then the location, then the company default. Set the rungs in **Settings → Planning → Planning Ownership** and on the item's planning tab (**Responsible Employee**). Filter the grid by assignee to see your own worklist.+## Planning vs schedulingPlanning determines quantities; **scheduling** determines timing and work-center allocation. After a job exists, scheduling places its <Term id="operation">operations</Term> on <Term id="work-center">work centers</Term> and calculates dates without changing quantities.@@ -51,6 +100,12 @@ Planning determines quantities; **scheduling** determines timing and work-center<Card title="Jobs" href="/docs/reference/jobs">What a Make suggestion becomes once you order it.</Card>+ <Card title="Demand forecasts" href="/docs/reference/forecast">+ The projections MRP plans against, and how real orders consume them.+ </Card>+ <Card title="Company settings" href="/docs/reference/company-settings">+ The planning settings behind the horizon, the tolerance and the owner ladder.+ </Card></Cards><AgentContext>@@ -67,4 +122,13 @@ The job was created but copying the item's method into it failed — usually the### "Failed to load any locations"Planning needs at least one location. Create one in settings and set a default.++### "Planning action … was already applied"+Another planner applied the same action after this page loaded. Reload the planning page; the action is gone and the order already carries the change.++### "… is committed — review on the order"+The target left Draft / Planned between the page load and Apply (the PO was sent or put in approval, the job was released). The action stays open as Review; make the change on the order.++### Mechanics+Actions are rows in `planningAction` (`type` Order / Make / Expedite / Defer / Cancel / Increase / Decrease; `status` Open / Dismissed / Actioned), written by `generatePlanningActions` after every MRP run as a diff against the previous run. Purchasing actions, and job Expedite / Defer, apply as one transaction per batch: the claim (Open → Actioned) and the change commit together. Job Increase / Decrease / Cancel run one job at a time through server functions with their own transactions, each action claimed right before its own change. Every claim returns the action's suggested quantity and date as they are at the claim, and Apply writes those. A date move on a "No Deadline" job sets `deadlineType` to "Soft Deadline". The horizon is `itemPlanning.planningHorizonDays`, else `companySettings.defaultPlanningHorizonDays`; 0 at either level means no horizon. The tolerance is `companySettings.rescheduleToleranceDays`. The owner ladder is `itemPlanning.responsibleEmployee` → `itemPostingGroupResponsibility` → `location.responsibleEmployee` → `companySettings.defaultResponsibleEmployee`.</AgentContext>diff --git a/docs/content/docs/reference/reordering.mdx b/docs/content/docs/reference/reordering.mdxindex 8e7c1567db..89dc9189f6 100644--- a/docs/content/docs/reference/reordering.mdx+++ b/docs/content/docs/reference/reordering.mdx@@ -24,6 +24,8 @@ Each part has a **reordering policy** that determines when and how much to reple<Field name="Lot size">Round an order up to a multiple. *(applies to: all)*</Field><Field name="Demand accumulation period">Window that groups demand into a single order. *(applies to: Demand-Based Reorder)*</Field><Field name="Demand accumulation safety stock">Buffer each accumulation window is topped up to. *(applies to: Demand-Based Reorder)*</Field>+ <Field name="Planning Horizon (Days)">How far ahead the planning grids show this item's actions and suggested orders. Empty inherits the company default; 0 shows everything. See [planning horizon](/docs/reference/planning#planning-horizon). *(applies to: all)*</Field>+ <Field name="Responsible Employee">Who this item's planning actions are assigned to at this location. Empty inherits the item group, location or company owner. See [planning ownership](/docs/reference/planning#planning-ownership). *(applies to: all)*</Field></FieldTable><Callout type="info">diff --git a/docs/content/src/glossary/terms.ts b/docs/content/src/glossary/terms.tsindex 15d5b2f0f2..a2cab1895c 100644--- a/docs/content/src/glossary/terms.ts+++ b/docs/content/src/glossary/terms.ts@@ -1121,6 +1121,30 @@ export const terms = {term: msg`Maximum Order Quantity`,definition: msg`Planning's upper bound on a single suggested replenishment; quantities above this are split into multiple orders.`},+ "item-planning-horizon": {+ term: msg`Planning Horizon (Days)`,+ definition: msg`Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item.`+ },+ "planning-action": {+ term: msg`Planning action`,+ definition: msg`A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it.`,+ href: "/docs/reference/planning#planning-actions"+ },+ "reschedule-tolerance": {+ term: msg`Reschedule tolerance`,+ definition: msg`How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days.`,+ href: "/docs/reference/planning#reschedule-tolerance"+ },+ "responsible-employee": {+ term: msg`Responsible employee`,+ definition: msg`The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default.`,+ href: "/docs/reference/planning#planning-ownership"+ },+ "forecast-consumption": {+ term: msg`Forecast consumption`,+ definition: msg`Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units.`,+ href: "/docs/reference/forecast"+ },// ── Items: Supersession (ItemSupersessionForm) ──────────────────────────supersession: {diff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.tsindex e911bcbcf6..54577906e8 100644--- a/packages/database/src/authz/manifest.ts+++ b/packages/database/src/authz/manifest.ts@@ -767,6 +767,11 @@ export const manifest = {}),itemPlanning: company("parts", { read: "parts_view", delete: false }),itemPostingGroup: company("accounting", { read: "accounting_view" }),+ itemPostingGroupResponsibility: company("settings", {+ create: "settings_update",+ update: "settings_update",+ delete: "settings_update"+ }),itemReplenishment: company("parts", { read: "parts_view" }),itemSerialSequence: company("settings"),itemShelfLife: company("parts", { read: "parts_view" }),@@ -1050,6 +1055,18 @@ export const manifest = {}),pickMethod: company("parts", { read: "parts_view", delete: false }),plan: policies({ select: authenticated }),+ // Read-only through the API. MRP writes it (Kysely) and the planning routes+ // change it with the service role after their own checks; an API write could+ // point an action's jobId / purchaseOrderLineId at another company's row+ // (single-column foreign keys), which the service-role read then shows.+ planningAction: company("production", {+ // Read by the production AND purchasing planning pages with the user's+ // client; the row names a supplier, an open quantity and an assignee.+ read: anyOf("production_view", "purchasing_view"),+ create: false,+ update: false,+ delete: false+ }),pricingRule: company("sales"),printerRoute: company("printing", { read: "printing_view" }),printJob: company("printing", { read: "printing_view" }),diff --git a/packages/database/src/datasets/wipe.ts b/packages/database/src/datasets/wipe.tsindex e17a3f3eff..554ca33c6c 100644--- a/packages/database/src/datasets/wipe.ts+++ b/packages/database/src/datasets/wipe.ts@@ -73,15 +73,20 @@ const PRESERVED_TABLES = new Set([]);/**- * MRP planning output — regenerated wholesale on the next run, and deleted- * before the FK-nulling pass because their discriminator CHECKs cannot survive- * it. Mirrors TRANSIENT_TABLES in packages/jobs/src/backups/schema.ts.+ * MRP planning output — regenerated on the next run, and deleted before the+ * FK-nulling pass because their CHECKs cannot survive it. The first four are+ * also TRANSIENT_TABLES in packages/jobs/src/backups/schema.ts; planningAction+ * is NOT (a backup keeps it: Dismissed and assigneeOverridden are the planner's+ * own state), it is only transient for a dataset apply.*/const TRANSIENT_MRP_TABLES = ["demandForecastSource","demandActual","supplyForecast",- "supplyActual"+ "supplyActual",+ // planningAction_change_target_chk: a change action must keep its job or+ // PO line, and the FK-nulling pass would clear jobId while jobs still exist.+ "planningAction"];// Their content CHECK (imagePath OR modelUploadId) cannot survive the FK-nulling@@ -375,9 +380,9 @@ export async function wipeCompanyBusinessData(ctx: Ctx): Promise<void> {// so on for jobId / demandProjectionId) over columns that are all nullable,// so nullNullableReferences below — which nulls every nullable FK whose// parent is being deleted — would violate the CHECK and abort the wipe.- // Deleting outright is safe and loses nothing: MRP regenerates these wholesale- // on its next run, which is why the backup catalog also treats them as- // transient (see TRANSIENT_TABLES in packages/jobs/src/backups/schema.ts).+ // Deleting outright is safe for a dataset apply: MRP regenerates these on+ // its next run (the planner's dismissals and assignments on planningAction+ // go with the rest of the company's data, as the apply intends).for (const t of [...TRANSIENT_MRP_TABLES, ...MODEL_SLIDE_TABLES]) {if (deleteSet.has(t)) {await client.query(`DELETE FROM ${quote(t)} WHERE "companyId" = $1`, [diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex ebed379bc4..de64f64dcf 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -6042,6 +6042,177 @@ export default {tags: ["trainings"]}},+ "/itemPostingGroupResponsibility": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.id"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.itemPostingGroupId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.responsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/itemPostingGroupResponsibility"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["itemPostingGroupResponsibility"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.itemPostingGroupResponsibility"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["itemPostingGroupResponsibility"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.id"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.itemPostingGroupId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.responsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["itemPostingGroupResponsibility"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.id"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.itemPostingGroupId"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.responsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.itemPostingGroupResponsibility.updatedAt"+ },+ {+ $ref: "#/parameters/body.itemPostingGroupResponsibility"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["itemPostingGroupResponsibility"]+ }+ },"/companyUsage": {get: {parameters: [@@ -25293,6 +25464,9 @@ export default {{$ref: "#/parameters/rowFilter.location.requiresStaffing"},+ {+ $ref: "#/parameters/rowFilter.location.responsibleEmployee"+ },{$ref: "#/parameters/select"},@@ -25412,6 +25586,9 @@ export default {{$ref: "#/parameters/rowFilter.location.requiresStaffing"},+ {+ $ref: "#/parameters/rowFilter.location.responsibleEmployee"+ },{$ref: "#/parameters/preferReturn"}@@ -25485,6 +25662,9 @@ export default {{$ref: "#/parameters/rowFilter.location.requiresStaffing"},+ {+ $ref: "#/parameters/rowFilter.location.responsibleEmployee"+ },{$ref: "#/parameters/body.location"},@@ -42504,6 +42684,321 @@ export default {tags: ["document"]}},+ "/planningAction": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.planningAction.id"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.periodId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.type"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.status"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.suggestedQuantity"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.suggestedDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.isASAP"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.horizonDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.latestOrderDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.purchaseOrderLineId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.jobId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.requiresManualAction"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.supplierId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.policyName"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.reason"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.triggerValues"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.assignee"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.assigneeOverridden"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/planningAction"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["planningAction"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.planningAction"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["planningAction"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.planningAction.id"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.periodId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.type"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.status"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.suggestedQuantity"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.suggestedDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.isASAP"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.horizonDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.latestOrderDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.purchaseOrderLineId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.jobId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.requiresManualAction"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.supplierId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.policyName"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.reason"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.triggerValues"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.assignee"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.assigneeOverridden"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["planningAction"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.planningAction.id"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.itemId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.periodId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.type"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.status"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.suggestedQuantity"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.suggestedDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.isASAP"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.horizonDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.latestOrderDate"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.purchaseOrderLineId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.jobId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.requiresManualAction"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.supplierId"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.policyName"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.reason"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.triggerValues"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.assignee"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.assigneeOverridden"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.planningAction.updatedAt"+ },+ {+ $ref: "#/parameters/body.planningAction"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["planningAction"]+ }+ },"/supplierQuoteLines": {get: {parameters: [@@ -59085,6 +59580,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrder.jobReadableId"},+ {+ $ref: "#/parameters/rowFilter.purchaseOrder.createdFromPlanning"+ },{$ref: "#/parameters/select"},@@ -59228,6 +59726,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrder.jobReadableId"},+ {+ $ref: "#/parameters/rowFilter.purchaseOrder.createdFromPlanning"+ },{$ref: "#/parameters/preferReturn"}@@ -59325,6 +59826,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrder.jobReadableId"},+ {+ $ref: "#/parameters/rowFilter.purchaseOrder.createdFromPlanning"+ },{$ref: "#/parameters/body.purchaseOrder"},@@ -75612,6 +76116,12 @@ export default {{$ref: "#/parameters/rowFilter.itemPlanning.minimumReserveQuantity"},+ {+ $ref: "#/parameters/rowFilter.itemPlanning.responsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.itemPlanning.planningHorizonDays"+ },{$ref: "#/parameters/select"},@@ -75734,6 +76244,12 @@ export default {{$ref: "#/parameters/rowFilter.itemPlanning.minimumReserveQuantity"},+ {+ $ref: "#/parameters/rowFilter.itemPlanning.responsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.itemPlanning.planningHorizonDays"+ },{$ref: "#/parameters/preferReturn"}@@ -75810,6 +76326,12 @@ export default {{$ref: "#/parameters/rowFilter.itemPlanning.minimumReserveQuantity"},+ {+ $ref: "#/parameters/rowFilter.itemPlanning.responsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.itemPlanning.planningHorizonDays"+ },{$ref: "#/parameters/body.itemPlanning"},@@ -83211,6 +83733,9 @@ export default {{$ref: "#/parameters/rowFilter.openSalesOrderLines.quantityToSend"},+ {+ $ref: "#/parameters/rowFilter.openSalesOrderLines.quantityToConsume"+ },{$ref: "#/parameters/rowFilter.openSalesOrderLines.salesOrderLineType"},@@ -89049,6 +89574,9 @@ export default {{$ref: "#/parameters/rowFilter.demandProjection.id"},+ {+ $ref: "#/parameters/rowFilter.demandProjection.consumedQuantity"+ },{$ref: "#/parameters/select"},@@ -89147,6 +89675,9 @@ export default {{$ref: "#/parameters/rowFilter.demandProjection.id"},+ {+ $ref: "#/parameters/rowFilter.demandProjection.consumedQuantity"+ },{$ref: "#/parameters/preferReturn"}@@ -89199,6 +89730,9 @@ export default {{$ref: "#/parameters/rowFilter.demandProjection.id"},+ {+ $ref: "#/parameters/rowFilter.demandProjection.consumedQuantity"+ },{$ref: "#/parameters/body.demandProjection"},@@ -92802,6 +93336,27 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.showBomExplorerReadableId"},+ {+ $ref: "#/parameters/rowFilter.companySettings.defaultResponsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.rescheduleToleranceDays"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.forecastConsumptionBackwardPeriods"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.forecastConsumptionForwardPeriods"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.defaultPlanningHorizonDays"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.mrpRunTime"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.skipApprovalForPlanningPurchaseOrders"+ },{$ref: "#/parameters/select"},@@ -93020,6 +93575,27 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.showBomExplorerReadableId"},+ {+ $ref: "#/parameters/rowFilter.companySettings.defaultResponsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.rescheduleToleranceDays"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.forecastConsumptionBackwardPeriods"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.forecastConsumptionForwardPeriods"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.defaultPlanningHorizonDays"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.mrpRunTime"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.skipApprovalForPlanningPurchaseOrders"+ },{$ref: "#/parameters/preferReturn"}@@ -93192,6 +93768,27 @@ export default {{$ref: "#/parameters/rowFilter.companySettings.showBomExplorerReadableId"},+ {+ $ref: "#/parameters/rowFilter.companySettings.defaultResponsibleEmployee"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.rescheduleToleranceDays"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.forecastConsumptionBackwardPeriods"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.forecastConsumptionForwardPeriods"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.defaultPlanningHorizonDays"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.mrpRunTime"+ },+ {+ $ref: "#/parameters/rowFilter.companySettings.skipApprovalForPlanningPurchaseOrders"+ },{$ref: "#/parameters/body.companySettings"},@@ -99679,6 +100276,127 @@ export default {tags: ["(rpc) sync_check_method_material_self_reference"]}},+ "/rpc/get_purchasing_planning_grid": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "company_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "location_id",+ required: true,+ type: "string"+ },+ {+ format: "text[]",+ in: "query",+ name: "periods",+ required: true,+ type: "string"+ },+ {+ format: "date",+ in: "query",+ name: "as_of",+ required: false,+ type: "string"+ },+ {+ format: "text[]",+ in: "query",+ name: "action_types",+ required: false,+ type: "string"+ },+ {+ format: "text[]",+ in: "query",+ name: "action_assignees",+ required: false,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_purchasing_planning_grid"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ action_assignees: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ action_types: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ as_of: {+ format: "date",+ type: "string"+ },+ company_id: {+ format: "text",+ type: "string"+ },+ location_id: {+ format: "text",+ type: "string"+ },+ periods: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ }+ },+ required: ["company_id", "location_id", "periods"],+ 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_purchasing_planning_grid"]+ }+ },"/rpc/sync_update_job_material_make_method_item_id": {post: {parameters: [@@ -102207,33 +102925,137 @@ export default {description: "OK"}},- tags: ["(rpc) sync_insert_job_make_method"]+ tags: ["(rpc) sync_insert_job_make_method"]+ }+ },+ "/rpc/get_assigned_job_operations": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ company_id: {+ format: "text",+ type: "string"+ },+ user_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["user_id", "company_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_assigned_job_operations"]+ }+ },+ "/rpc/sync_check_job_material_self_reference": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_new: {+ format: "jsonb"+ },+ p_old: {+ format: "jsonb"+ },+ p_operation: {+ format: "text",+ type: "string"+ },+ p_table: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_table", "p_operation", "p_new", "p_old"],+ 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) sync_check_job_material_self_reference"]}},- "/rpc/get_assigned_job_operations": {- post: {+ "/rpc/get_production_planning_grid": {+ get: {parameters: [{- in: "body",- name: "args",+ format: "text",+ in: "query",+ name: "company_id",required: true,- schema: {- properties: {- company_id: {- format: "text",- type: "string"- },- user_id: {- format: "text",- type: "string"- }- },- required: ["user_id", "company_id"],- type: "object"- }+ type: "string"},{- $ref: "#/parameters/preferParams"+ format: "text",+ in: "query",+ name: "location_id",+ required: true,+ type: "string"+ },+ {+ format: "text[]",+ in: "query",+ name: "periods",+ required: true,+ type: "string"+ },+ {+ format: "date",+ in: "query",+ name: "as_of",+ required: false,+ type: "string"+ },+ {+ format: "text[]",+ in: "query",+ name: "action_types",+ required: false,+ type: "string"+ },+ {+ format: "text[]",+ in: "query",+ name: "action_assignees",+ required: false,+ type: "string"}],produces: [@@ -102246,10 +103068,8 @@ export default {description: "OK"}},- tags: ["(rpc) get_assigned_job_operations"]- }- },- "/rpc/sync_check_job_material_self_reference": {+ tags: ["(rpc) get_production_planning_grid"]+ },post: {parameters: [{@@ -102258,22 +103078,41 @@ export default {required: true,schema: {properties: {- p_new: {- format: "jsonb"+ action_assignees: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"},- p_old: {- format: "jsonb"+ action_types: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"},- p_operation: {+ as_of: {+ format: "date",+ type: "string"+ },+ company_id: {format: "text",type: "string"},- p_table: {+ location_id: {format: "text",type: "string"+ },+ periods: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"}},- required: ["p_table", "p_operation", "p_new", "p_old"],+ required: ["company_id", "location_id", "periods"],type: "object"}},@@ -102291,7 +103130,7 @@ export default {description: "OK"}},- tags: ["(rpc) sync_check_job_material_self_reference"]+ tags: ["(rpc) get_production_planning_grid"]}},"/rpc/xid_encode": {@@ -110197,6 +111036,66 @@ export default {},type: "object"},+ itemPostingGroupResponsibility: {+ required: [+ "id",+ "companyId",+ "locationId",+ "itemPostingGroupId",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id('pgr'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ locationId: {+ format: "text",+ type: "string"+ },+ itemPostingGroupId: {+ format: "text",+ type: "string"+ },+ responsibleEmployee: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },companyUsage: {required: ["id",@@ -119436,6 +120335,12 @@ export default {default: false,format: "boolean",type: "boolean"+ },+ responsibleEmployee: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"}},type: "object"@@ -127604,6 +128509,165 @@ export default {},type: "object"},+ planningAction: {+ required: [+ "id",+ "companyId",+ "itemId",+ "locationId",+ "periodId",+ "type",+ "status",+ "suggestedQuantity",+ "suggestedDate",+ "isASAP",+ "horizonDate",+ "requiresManualAction",+ "assigneeOverridden",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id('pla'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ itemId: {+ description:+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",+ format: "text",+ type: "string"+ },+ locationId: {+ description:+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",+ format: "text",+ type: "string"+ },+ periodId: {+ description:+ "Note:\nThis is a Foreign Key to `period.id`.<fk table='period' column='id'/>",+ format: "text",+ type: "string"+ },+ type: {+ enum: [+ "Order",+ "Make",+ "Expedite",+ "Defer",+ "Cancel",+ "Increase",+ "Decrease",+ "Release"+ ],+ format: 'public."planningActionType"',+ type: "string"+ },+ status: {+ default: "Open",+ enum: ["Open", "Dismissed", "Actioned"],+ format: 'public."planningActionStatus"',+ type: "string"+ },+ suggestedQuantity: {+ format: "numeric",+ type: "number"+ },+ suggestedDate: {+ format: "date",+ type: "string"+ },+ isASAP: {+ default: false,+ format: "boolean",+ type: "boolean"+ },+ horizonDate: {+ format: "date",+ type: "string"+ },+ latestOrderDate: {+ format: "date",+ type: "string"+ },+ purchaseOrderLineId: {+ description:+ "Note:\nThis is a Foreign Key to `purchaseOrderLine.id`.<fk table='purchaseOrderLine' column='id'/>",+ format: "text",+ type: "string"+ },+ jobId: {+ description:+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",+ format: "text",+ type: "string"+ },+ requiresManualAction: {+ default: false,+ format: "boolean",+ type: "boolean"+ },+ supplierId: {+ description:+ "Note:\nThis is a Foreign Key to `supplier.id`.<fk table='supplier' column='id'/>",+ format: "text",+ type: "string"+ },+ policyName: {+ format: "text",+ type: "string"+ },+ reason: {+ format: "text",+ type: "string"+ },+ triggerValues: {+ format: "jsonb"+ },+ assignee: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ assigneeOverridden: {+ default: false,+ format: "boolean",+ type: "boolean"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },supplierQuoteLines: {properties: {id: {@@ -135018,7 +136082,8 @@ export default {"createdAt","createdBy","supplierInteractionId",- "purchaseOrderType"+ "purchaseOrderType",+ "createdFromPlanning"],properties: {id: {@@ -135172,6 +136237,11 @@ export default {jobReadableId: {format: "text",type: "string"+ },+ createdFromPlanning: {+ default: false,+ format: "boolean",+ type: "boolean"}},type: "object"@@ -143282,6 +144352,16 @@ export default {default: 0,format: "numeric",type: "number"+ },+ responsibleEmployee: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ planningHorizonDays: {+ format: "integer",+ type: "integer"}},type: "object"@@ -146888,6 +147968,10 @@ export default {format: "numeric",type: "number"},+ quantityToConsume: {+ format: "numeric",+ type: "number"+ },salesOrderLineType: {enum: ["Comment",@@ -149895,7 +150979,8 @@ export default {"createdAt","updatedAt","updatedBy",- "id"+ "id",+ "consumedQuantity"],properties: {itemId: {@@ -149965,6 +151050,11 @@ export default {default: "public.id()",format: "text",type: "string"+ },+ consumedQuantity: {+ default: 0,+ format: "numeric",+ type: "number"}},type: "object"@@ -151437,7 +152527,11 @@ export default {"includeOperationsOnTraveler","requireSupplierContactAndLocation","requireCustomerContactAndLocation",- "showBomExplorerReadableId"+ "showBomExplorerReadableId",+ "rescheduleToleranceDays",+ "forecastConsumptionBackwardPeriods",+ "forecastConsumptionForwardPeriods",+ "skipApprovalForPlanningPurchaseOrders"],properties: {id: {@@ -151729,6 +152823,40 @@ export default {default: false,format: "boolean",type: "boolean"+ },+ defaultResponsibleEmployee: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ rescheduleToleranceDays: {+ default: 7,+ format: "integer",+ type: "integer"+ },+ forecastConsumptionBackwardPeriods: {+ default: 4,+ format: "integer",+ type: "integer"+ },+ forecastConsumptionForwardPeriods: {+ default: 1,+ format: "integer",+ type: "integer"+ },+ defaultPlanningHorizonDays: {+ format: "integer",+ type: "integer"+ },+ mrpRunTime: {+ format: "time without time zone",+ type: "string"+ },+ skipApprovalForPlanningPurchaseOrders: {+ default: true,+ format: "boolean",+ type: "boolean"}},type: "object"@@ -155387,6 +156515,69 @@ export default {in: "query",type: "string"},+ "body.itemPostingGroupResponsibility": {+ name: "itemPostingGroupResponsibility",+ description: "itemPostingGroupResponsibility",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/itemPostingGroupResponsibility"+ }+ },+ "rowFilter.itemPostingGroupResponsibility.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.locationId": {+ name: "locationId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.itemPostingGroupId": {+ name: "itemPostingGroupId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.responsibleEmployee": {+ name: "responsibleEmployee",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPostingGroupResponsibility.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.companyUsage": {name: "companyUsage",description: "companyUsage",@@ -165734,6 +166925,12 @@ export default {in: "query",type: "string"},+ "rowFilter.location.responsibleEmployee": {+ name: "responsibleEmployee",+ required: false,+ in: "query",+ type: "string"+ },"body.kanbans": {name: "kanbans",description: "kanbans",@@ -174824,6 +176021,165 @@ export default {in: "query",type: "string"},+ "body.planningAction": {+ name: "planningAction",+ description: "planningAction",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/planningAction"+ }+ },+ "rowFilter.planningAction.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.locationId": {+ name: "locationId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.periodId": {+ name: "periodId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.type": {+ name: "type",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.status": {+ name: "status",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.suggestedQuantity": {+ name: "suggestedQuantity",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.suggestedDate": {+ name: "suggestedDate",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.isASAP": {+ name: "isASAP",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.horizonDate": {+ name: "horizonDate",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.latestOrderDate": {+ name: "latestOrderDate",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.purchaseOrderLineId": {+ name: "purchaseOrderLineId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.jobId": {+ name: "jobId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.requiresManualAction": {+ name: "requiresManualAction",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.supplierId": {+ name: "supplierId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.policyName": {+ name: "policyName",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.reason": {+ name: "reason",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.triggerValues": {+ name: "triggerValues",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.assignee": {+ name: "assignee",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.assigneeOverridden": {+ name: "assigneeOverridden",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.planningAction.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.supplierQuoteLines": {name: "supplierQuoteLines",description: "supplierQuoteLines",@@ -183238,6 +184594,12 @@ export default {in: "query",type: "string"},+ "rowFilter.purchaseOrder.createdFromPlanning": {+ name: "createdFromPlanning",+ required: false,+ in: "query",+ type: "string"+ },"body.maintenanceDispatchComment": {name: "maintenanceDispatchComment",description: "maintenanceDispatchComment",@@ -192309,6 +193671,18 @@ export default {in: "query",type: "string"},+ "rowFilter.itemPlanning.responsibleEmployee": {+ name: "responsibleEmployee",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.itemPlanning.planningHorizonDays": {+ name: "planningHorizonDays",+ required: false,+ in: "query",+ type: "string"+ },"body.nonConformanceTrackedEntity": {name: "nonConformanceTrackedEntity",description: "nonConformanceTrackedEntity",@@ -196360,6 +197734,12 @@ export default {in: "query",type: "string"},+ "rowFilter.openSalesOrderLines.quantityToConsume": {+ name: "quantityToConsume",+ required: false,+ in: "query",+ type: "string"+ },"rowFilter.openSalesOrderLines.salesOrderLineType": {name: "salesOrderLineType",required: false,@@ -199790,6 +201170,12 @@ export default {in: "query",type: "string"},+ "rowFilter.demandProjection.consumedQuantity": {+ name: "consumedQuantity",+ required: false,+ in: "query",+ type: "string"+ },"body.pickingListLineTrackedEntity": {name: "pickingListLineTrackedEntity",description: "pickingListLineTrackedEntity",@@ -201666,6 +203052,48 @@ export default {in: "query",type: "string"},+ "rowFilter.companySettings.defaultResponsibleEmployee": {+ name: "defaultResponsibleEmployee",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.rescheduleToleranceDays": {+ name: "rescheduleToleranceDays",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.forecastConsumptionBackwardPeriods": {+ name: "forecastConsumptionBackwardPeriods",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.forecastConsumptionForwardPeriods": {+ name: "forecastConsumptionForwardPeriods",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.defaultPlanningHorizonDays": {+ name: "defaultPlanningHorizonDays",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.mrpRunTime": {+ name: "mrpRunTime",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.companySettings.skipApprovalForPlanningPurchaseOrders": {+ name: "skipApprovalForPlanningPurchaseOrders",+ required: false,+ in: "query",+ type: "string"+ },"body.part": {name: "part",description: "part",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex ebce0272f1..7f66c4a2ce 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -7963,11 +7963,15 @@ export type Database = {autoStartOperationTimer: booleanconsoleEnabled: booleandefaultCustomerCc: string[] | null+ defaultPlanningHorizonDays: number | null+ defaultResponsibleEmployee: string | nulldefaultSupplierCc: string[] | nulldigitalQuoteEnabled: booleandigitalQuoteIncludesPurchaseOrders: booleandigitalQuoteNotificationGroup: string[]enforceInspectionFourEyes: boolean+ forecastConsumptionBackwardPeriods: number+ forecastConsumptionForwardPeriods: numbergaugeCalibrationExpiredNotificationGroup: string[]id: stringincludeMaterialsOnTraveler: boolean@@ -7978,6 +7982,7 @@ export type Database = {kanbanOutput: Database["public"]["Enums"]["kanbanOutput"]maintenanceDispatchNotificationGroup: string[] | nullmaterialGeneratedIds: boolean+ mrpRunTime: string | nulloperationsDispatchNotificationGroup: string[] | nullotherDispatchNotificationGroup: string[] | nullplmReleaseControl: string@@ -7990,6 +7995,7 @@ export type Database = {requireCustomerContactAndLocation: booleanrequireMfa: booleanrequireSupplierContactAndLocation: boolean+ rescheduleToleranceDays: numberreturnPickedMaterialTiming: stringrfqReadyNotificationGroup: string[]salesJobCompletedNotificationGroup: string[]@@ -8000,6 +8006,7 @@ export type Database = {showCurrencyTrailingZeros: booleanshowCustomerReadableId: booleanshowSupplierReadableId: boolean+ skipApprovalForPlanningPurchaseOrders: booleansupplierQuoteNotificationGroup: string[]timeCardEnabled: booleanupdateLeadTimesOnReceipt: boolean@@ -8018,11 +8025,15 @@ export type Database = {autoStartOperationTimer?: booleanconsoleEnabled?: booleandefaultCustomerCc?: string[] | null+ defaultPlanningHorizonDays?: number | null+ defaultResponsibleEmployee?: string | nulldefaultSupplierCc?: string[] | nulldigitalQuoteEnabled?: booleandigitalQuoteIncludesPurchaseOrders?: booleandigitalQuoteNotificationGroup?: string[]enforceInspectionFourEyes?: boolean+ forecastConsumptionBackwardPeriods?: number+ forecastConsumptionForwardPeriods?: numbergaugeCalibrationExpiredNotificationGroup?: string[]id: stringincludeMaterialsOnTraveler?: boolean@@ -8033,6 +8044,7 @@ export type Database = {kanbanOutput?: Database["public"]["Enums"]["kanbanOutput"]maintenanceDispatchNotificationGroup?: string[] | nullmaterialGeneratedIds?: boolean+ mrpRunTime?: string | nulloperationsDispatchNotificationGroup?: string[] | nullotherDispatchNotificationGroup?: string[] | nullplmReleaseControl?: string@@ -8045,6 +8057,7 @@ export type Database = {requireCustomerContactAndLocation?: booleanrequireMfa?: booleanrequireSupplierContactAndLocation?: boolean+ rescheduleToleranceDays?: numberreturnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]@@ -8055,6 +8068,7 @@ export type Database = {showCurrencyTrailingZeros?: booleanshowCustomerReadableId?: booleanshowSupplierReadableId?: boolean+ skipApprovalForPlanningPurchaseOrders?: booleansupplierQuoteNotificationGroup?: string[]timeCardEnabled?: booleanupdateLeadTimesOnReceipt?: boolean@@ -8073,11 +8087,15 @@ export type Database = {autoStartOperationTimer?: booleanconsoleEnabled?: booleandefaultCustomerCc?: string[] | null+ defaultPlanningHorizonDays?: number | null+ defaultResponsibleEmployee?: string | nulldefaultSupplierCc?: string[] | nulldigitalQuoteEnabled?: booleandigitalQuoteIncludesPurchaseOrders?: booleandigitalQuoteNotificationGroup?: string[]enforceInspectionFourEyes?: boolean+ forecastConsumptionBackwardPeriods?: number+ forecastConsumptionForwardPeriods?: numbergaugeCalibrationExpiredNotificationGroup?: string[]id?: stringincludeMaterialsOnTraveler?: boolean@@ -8088,6 +8106,7 @@ export type Database = {kanbanOutput?: Database["public"]["Enums"]["kanbanOutput"]maintenanceDispatchNotificationGroup?: string[] | nullmaterialGeneratedIds?: boolean+ mrpRunTime?: string | nulloperationsDispatchNotificationGroup?: string[] | nullotherDispatchNotificationGroup?: string[] | nullplmReleaseControl?: string@@ -8100,6 +8119,7 @@ export type Database = {requireCustomerContactAndLocation?: booleanrequireMfa?: booleanrequireSupplierContactAndLocation?: boolean+ rescheduleToleranceDays?: numberreturnPickedMaterialTiming?: stringrfqReadyNotificationGroup?: string[]salesJobCompletedNotificationGroup?: string[]@@ -8110,6 +8130,7 @@ export type Database = {showCurrencyTrailingZeros?: booleanshowCustomerReadableId?: booleanshowSupplierReadableId?: boolean+ skipApprovalForPlanningPurchaseOrders?: booleansupplierQuoteNotificationGroup?: string[]timeCardEnabled?: booleanupdateLeadTimesOnReceipt?: boolean@@ -8143,6 +8164,41 @@ export type Database = {isOneToOne: truereferencedRelation: "integrations"referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "companySettings_defaultResponsibleEmployee_fkey"+ columns: ["defaultResponsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companySettings_defaultResponsibleEmployee_fkey"+ columns: ["defaultResponsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companySettings_defaultResponsibleEmployee_fkey"+ columns: ["defaultResponsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companySettings_defaultResponsibleEmployee_fkey"+ columns: ["defaultResponsibleEmployee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "companySettings_defaultResponsibleEmployee_fkey"+ columns: ["defaultResponsibleEmployee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]}]}@@ -12509,6 +12565,7 @@ export type Database = {Row: {companyId: stringconfidence: number | null+ consumedQuantity: numbercreatedAt: stringcreatedBy: stringforecastMethod: string | null@@ -12524,6 +12581,7 @@ export type Database = {Insert: {companyId: stringconfidence?: number | null+ consumedQuantity?: numbercreatedAt?: stringcreatedBy: stringforecastMethod?: string | null@@ -12539,6 +12597,7 @@ export type Database = {Update: {companyId?: stringconfidence?: number | null+ consumedQuantity?: numbercreatedAt?: stringcreatedBy?: stringforecastMethod?: string | null@@ -22610,9 +22669,11 @@ export type Database = {minimumOrderQuantity: numberminimumReserveQuantity: numberorderMultiple: number+ planningHorizonDays: number | nullreorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]reorderPoint: numberreorderQuantity: number+ responsibleEmployee: string | nulltags: string[] | nullupdatedAt: string | nullupdatedBy: string | null@@ -22633,9 +22694,11 @@ export type Database = {minimumOrderQuantity?: numberminimumReserveQuantity?: numberorderMultiple?: number+ planningHorizonDays?: number | nullreorderingPolicy?: Database["public"]["Enums"]["itemReorderingPolicy"]reorderPoint?: numberreorderQuantity?: number+ responsibleEmployee?: string | nulltags?: string[] | nullupdatedAt?: string | nullupdatedBy?: string | null@@ -22656,9 +22719,11 @@ export type Database = {minimumOrderQuantity?: numberminimumReserveQuantity?: numberorderMultiple?: number+ planningHorizonDays?: number | nullreorderingPolicy?: Database["public"]["Enums"]["itemReorderingPolicy"]reorderPoint?: numberreorderQuantity?: number+ responsibleEmployee?: string | nulltags?: string[] | nullupdatedAt?: string | nullupdatedBy?: string | null@@ -22776,6 +22841,41 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "itemPlanning_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPlanning_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPlanning_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPlanning_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPlanning_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },{foreignKeyName: "itemPlanning_updatedBy_fkey"columns: ["updatedBy"]@@ -22954,6 +23054,190 @@ export type Database = {}]}+ itemPostingGroupResponsibility: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ itemPostingGroupId: string+ locationId: string+ responsibleEmployee: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ itemPostingGroupId: string+ locationId: string+ responsibleEmployee?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ itemPostingGroupId?: string+ locationId?: string+ responsibleEmployee?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "itemPostingGroupResponsibility_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_group_fkey"+ columns: ["itemPostingGroupId", "companyId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id", "companyId"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_location_fkey"+ columns: ["locationId", "companyId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id", "companyId"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "itemPostingGroupResponsibility_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }itemReplenishment: {Row: {companyId: string@@ -27854,6 +28138,7 @@ export type Database = {name: stringpostalCode: stringrequiresStaffing: boolean+ responsibleEmployee: string | nullstateProvince: string | nulltags: string[] | nulltimezone: string@@ -27876,6 +28161,7 @@ export type Database = {name: stringpostalCode: stringrequiresStaffing?: boolean+ responsibleEmployee?: string | nullstateProvince?: string | nulltags?: string[] | nulltimezone: string@@ -27898,6 +28184,7 @@ export type Database = {name?: stringpostalCode?: stringrequiresStaffing?: boolean+ responsibleEmployee?: string | nullstateProvince?: string | nulltags?: string[] | nulltimezone?: string@@ -27932,6 +28219,41 @@ export type Database = {isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "location_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "location_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "location_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "location_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "location_responsibleEmployee_fkey"+ columns: ["responsibleEmployee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]}]}@@ -39810,6 +40132,357 @@ export type Database = {}Relationships: []}+ planningAction: {+ Row: {+ assignee: string | null+ assigneeOverridden: boolean+ companyId: string+ createdAt: string+ createdBy: string+ horizonDate: string+ id: string+ isASAP: boolean+ itemId: string+ jobId: string | null+ latestOrderDate: string | null+ locationId: string+ periodId: string+ policyName: string | null+ purchaseOrderLineId: string | null+ reason: string | null+ requiresManualAction: boolean+ status: Database["public"]["Enums"]["planningActionStatus"]+ suggestedDate: string+ suggestedQuantity: number+ supplierId: string | null+ triggerValues: Json | null+ type: Database["public"]["Enums"]["planningActionType"]+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ assignee?: string | null+ assigneeOverridden?: boolean+ companyId: string+ createdAt?: string+ createdBy: string+ horizonDate: string+ id?: string+ isASAP?: boolean+ itemId: string+ jobId?: string | null+ latestOrderDate?: string | null+ locationId: string+ periodId: string+ policyName?: string | null+ purchaseOrderLineId?: string | null+ reason?: string | null+ requiresManualAction?: boolean+ status?: Database["public"]["Enums"]["planningActionStatus"]+ suggestedDate: string+ suggestedQuantity: number+ supplierId?: string | null+ triggerValues?: Json | null+ type: Database["public"]["Enums"]["planningActionType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ assignee?: string | null+ assigneeOverridden?: boolean+ companyId?: string+ createdAt?: string+ createdBy?: string+ horizonDate?: string+ id?: string+ isASAP?: boolean+ itemId?: string+ jobId?: string | null+ latestOrderDate?: string | null+ locationId?: string+ periodId?: string+ policyName?: string | null+ purchaseOrderLineId?: string | null+ reason?: string | null+ requiresManualAction?: boolean+ status?: Database["public"]["Enums"]["planningActionStatus"]+ suggestedDate?: string+ suggestedQuantity?: number+ supplierId?: string | null+ triggerValues?: Json | null+ type?: Database["public"]["Enums"]["planningActionType"]+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "planningAction_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_assignee_fkey"+ columns: ["assignee"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "planningAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "planningAction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "planningAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "planningAction_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "consumables"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "item"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "materials"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "parts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "services"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_itemId_fkey"+ columns: ["itemId"]+ isOneToOne: false+ referencedRelation: "tools"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_jobId_fkey"+ columns: ["jobId"]+ isOneToOne: false+ referencedRelation: "job"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_jobId_fkey"+ columns: ["jobId"]+ isOneToOne: false+ referencedRelation: "jobs"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_jobId_fkey"+ columns: ["jobId"]+ isOneToOne: false+ referencedRelation: "openProductionOrders"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_periodId_fkey"+ columns: ["periodId"]+ isOneToOne: false+ referencedRelation: "period"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_purchaseOrderLineId_fkey"+ columns: ["purchaseOrderLineId"]+ isOneToOne: false+ referencedRelation: "openPurchaseOrderLines"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_purchaseOrderLineId_fkey"+ columns: ["purchaseOrderLineId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderLine"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_purchaseOrderLineId_fkey"+ columns: ["purchaseOrderLineId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderLines"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "planningAction_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "planningAction_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "planningAction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ }+ ]+ }pricingRule: {Row: {active: boolean@@ -42477,6 +43150,7 @@ export type Database = {companyId: stringcreatedAt: stringcreatedBy: string+ createdFromPlanning: booleancurrencyCode: string | nullcustomFields: Json | nullexchangeRate: number | null@@ -42507,6 +43181,7 @@ export type Database = {companyId: stringcreatedAt?: stringcreatedBy: string+ createdFromPlanning?: booleancurrencyCode?: string | nullcustomFields?: Json | nullexchangeRate?: number | null@@ -42537,6 +43212,7 @@ export type Database = {companyId?: stringcreatedAt?: stringcreatedBy?: string+ createdFromPlanning?: booleancurrencyCode?: string | nullcustomFields?: Json | nullexchangeRate?: number | null@@ -73031,6 +73707,7 @@ export type Database = {locationId: string | nullmethodType: Database["public"]["Enums"]["methodType"] | nullpromisedDate: string | null+ quantityToConsume: number | nullquantityToSend: number | nullreplenishmentSystem:| Database["public"]["Enums"]["itemReplenishmentSystem"]@@ -84313,6 +84990,101 @@ export type Database = {week9: number}[]}+ get_production_planning_grid: {+ Args: {+ action_assignees?: string[]+ action_types?: string[]+ as_of?: string+ company_id: string+ location_id: string+ periods: string[]+ }+ Returns: {+ active: boolean+ demandAccumulationPeriod: number+ demandAccumulationSafetyStock: number+ firstNegativeDate: string+ id: string+ itemPostingGroupId: string+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]+ latestOrderDate: string+ leadTime: number+ lotSize: number+ manufacturingBlocked: boolean+ maximumInventoryQuantity: number+ maximumOrderQuantity: number+ minimumOrderQuantity: number+ minimumReserveQuantity: number+ name: string+ orderMultiple: number+ orderQuantity: number+ planningHorizonDays: number+ quantityOnHand: number+ quantityToOrder: number+ readableIdWithRevision: string+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]+ reorderPoint: number+ reorderQuantity: number+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ supersessionMode: string+ thumbnailPath: string+ timeFenceDate: string+ type: Database["public"]["Enums"]["itemType"]+ unitOfMeasureCode: string+ week1: number+ week10: number+ week11: number+ week12: number+ week13: number+ week14: number+ week15: number+ week16: number+ week17: number+ week18: number+ week19: number+ week2: number+ week20: number+ week21: number+ week22: number+ week23: number+ week24: number+ week25: number+ week26: number+ week27: number+ week28: number+ week29: number+ week3: number+ week30: number+ week31: number+ week32: number+ week33: number+ week34: number+ week35: number+ week36: number+ week37: number+ week38: number+ week39: number+ week4: number+ week40: number+ week41: number+ week42: number+ week43: number+ week44: number+ week45: number+ week46: number+ week47: number+ week48: number+ week49: number+ week5: number+ week50: number+ week51: number+ week52: number+ week6: number+ week7: number+ week8: number+ week9: number+ }[]+ }get_production_projections: {Args: { company_id: string; location_id: string; periods: string[] }Returns: {@@ -84478,6 +85250,105 @@ export type Database = {week9: number}[]}+ get_purchasing_planning_grid: {+ Args: {+ action_assignees?: string[]+ action_types?: string[]+ as_of?: string+ company_id: string+ location_id: string+ periods: string[]+ }+ Returns: {+ active: boolean+ conversionFactor: number+ demandAccumulationPeriod: number+ demandAccumulationSafetyStock: number+ firstNegativeDate: string+ id: string+ itemPostingGroupId: string+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]+ latestOrderDate: string+ leadTime: number+ lotSize: number+ maximumInventoryQuantity: number+ maximumOrderQuantity: number+ minimumOrderQuantity: number+ minimumReserveQuantity: number+ name: string+ orderMultiple: number+ orderQuantity: number+ planningHorizonDays: number+ preferredSupplierId: string+ purchasingBlocked: boolean+ purchasingUnitOfMeasureCode: string+ quantityOnHand: number+ quantityToOrder: number+ readableIdWithRevision: string+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]+ reorderPoint: number+ reorderQuantity: number+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ supersessionMode: string+ suppliers: Json+ thumbnailPath: string+ timeFenceDate: string+ type: Database["public"]["Enums"]["itemType"]+ unitOfMeasureCode: string+ week1: number+ week10: number+ week11: number+ week12: number+ week13: number+ week14: number+ week15: number+ week16: number+ week17: number+ week18: number+ week19: number+ week2: number+ week20: number+ week21: number+ week22: number+ week23: number+ week24: number+ week25: number+ week26: number+ week27: number+ week28: number+ week29: number+ week3: number+ week30: number+ week31: number+ week32: number+ week33: number+ week34: number+ week35: number+ week36: number+ week37: number+ week38: number+ week39: number+ week4: number+ week40: number+ week41: number+ week42: number+ week43: number+ week44: number+ week45: number+ week46: number+ week47: number+ week48: number+ week49: number+ week5: number+ week50: number+ week51: number+ week52: number+ week6: number+ week7: number+ week8: number+ week9: number+ }[]+ }get_quote_methods: {Args: { qid: string }Returns: {@@ -86156,6 +87027,16 @@ export type Database = {| "Cancelled"| "Partial"pickMethodSortMethod: "Default" | "FEFO" | "FIFO" | "LIFO"+ planningActionStatus: "Open" | "Dismissed" | "Actioned"+ planningActionType:+ | "Order"+ | "Make"+ | "Expedite"+ | "Defer"+ | "Cancel"+ | "Increase"+ | "Decrease"+ | "Release"pricingRuleAmountType: "Percentage" | "Fixed"pricingRuleType: "Discount" | "Markup" | "Configuration"procedureStatus: "Draft" | "Active" | "Archived"@@ -87604,6 +88485,17 @@ export const Constants = {"Partial",],pickMethodSortMethod: ["Default", "FEFO", "FIFO", "LIFO"],+ planningActionStatus: ["Open", "Dismissed", "Actioned"],+ planningActionType: [+ "Order",+ "Make",+ "Expedite",+ "Defer",+ "Cancel",+ "Increase",+ "Decrease",+ "Release",+ ],pricingRuleAmountType: ["Percentage", "Fixed"],pricingRuleType: ["Discount", "Markup", "Configuration"],procedureStatus: ["Draft", "Active", "Archived"],diff --git a/packages/database/supabase/migrations/20261006130000_mrp-planning-actions.sql b/packages/database/supabase/migrations/20261006130000_mrp-planning-actions.sqlnew file mode 100644index 0000000000..1101f31383--- /dev/null+++ b/packages/database/supabase/migrations/20261006130000_mrp-planning-actions.sql@@ -0,0 +1,158 @@+-- MRP Planning Actions (Phase 1)+-- Spec: .ai/specs/2026-08-22-mrp-v2-planned-order-generation.md §P1+-- Plan: .ai/plans/2026-09-08-mrp-planning-actions.md (Task 1)++-- Enums (idempotent)+DO $$ BEGIN+ CREATE TYPE "planningActionType" AS ENUM+ ('Order', 'Make', 'Expedite', 'Defer', 'Cancel', 'Increase', 'Decrease');+EXCEPTION WHEN duplicate_object THEN NULL; END $$;++DO $$ BEGIN+ CREATE TYPE "planningActionStatus" AS ENUM ('Open', 'Dismissed', 'Actioned');+EXCEPTION WHEN duplicate_object THEN NULL; END $$;++-- The persisted planning action message: one row per suggested action, written+-- diff-write by MRP each run. Assignable, dismissible.+CREATE TABLE IF NOT EXISTS "planningAction" (+ "id" TEXT NOT NULL DEFAULT id('pla'),+ "companyId" TEXT NOT NULL,++ "itemId" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "periodId" TEXT NOT NULL,+ "type" "planningActionType" NOT NULL,+ "status" "planningActionStatus" NOT NULL DEFAULT 'Open',++ "suggestedQuantity" NUMERIC NOT NULL,+ "suggestedDate" DATE NOT NULL,+ "isASAP" BOOLEAN NOT NULL DEFAULT false,++ -- The two dates the planning grids read off a stored action:+ -- horizonDate — the date that decides whether the action is inside a+ -- planning horizon (time fence): the earlier of the target+ -- order's current date and the suggested date, so a Defer+ -- counts from where the order sits today and an Expedite+ -- from when it is needed.+ -- latestOrderDate — Order / Make / Increase only: the required date less the+ -- item's lead time, i.e. the last day to place the order.+ "horizonDate" DATE NOT NULL,+ "latestOrderDate" DATE,++ -- Target of a CHANGE action (exactly one set; both NULL for Order/Make):+ "purchaseOrderLineId" TEXT,+ "jobId" TEXT,+ "requiresManualAction" BOOLEAN NOT NULL DEFAULT false,++ -- Suggestion attribution (the "why"):+ "supplierId" TEXT REFERENCES "supplier"("id") ON DELETE SET NULL,+ "policyName" TEXT,+ "reason" TEXT,+ "triggerValues" JSONB,++ -- Assignment:+ "assignee" TEXT REFERENCES "user"("id"),+ "assigneeOverridden" BOOLEAN NOT NULL DEFAULT false,++ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ -- ON DELETE CASCADE throughout: a planning action is regenerable MRP output —+ -- when its item, location, period or target disappears, the suggestion is+ -- meaningless and must never block the delete or linger until the next run.+ -- All five referenced tables have single-column ("id") primary keys.+ CONSTRAINT "planningAction_itemId_fkey"+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,+ CONSTRAINT "planningAction_locationId_fkey"+ FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,+ CONSTRAINT "planningAction_periodId_fkey"+ FOREIGN KEY ("periodId") REFERENCES "period"("id") ON DELETE CASCADE,+ CONSTRAINT "planningAction_purchaseOrderLineId_fkey"+ FOREIGN KEY ("purchaseOrderLineId") REFERENCES "purchaseOrderLine"("id") ON DELETE CASCADE,+ CONSTRAINT "planningAction_jobId_fkey"+ FOREIGN KEY ("jobId") REFERENCES "job"("id") ON DELETE CASCADE,+ CONSTRAINT "planningAction_change_target_chk" CHECK (+ ("type" IN ('Order','Make') AND "purchaseOrderLineId" IS NULL AND "jobId" IS NULL)+ OR ("type" NOT IN ('Order','Make') AND (("purchaseOrderLineId" IS NOT NULL)::int + ("jobId" IS NOT NULL)::int) = 1)+ )+);++CREATE INDEX IF NOT EXISTS "planningAction_companyId_idx" ON "planningAction" ("companyId");+CREATE INDEX IF NOT EXISTS "planningAction_assignee_idx" ON "planningAction" ("companyId", "assignee");+CREATE INDEX IF NOT EXISTS "planningAction_item_loc_idx" ON "planningAction" ("companyId", "itemId", "locationId");+CREATE INDEX IF NOT EXISTS "planningAction_status_idx" ON "planningAction" ("companyId", "status");+CREATE INDEX IF NOT EXISTS "planningAction_createdBy_idx" ON "planningAction" ("createdBy");++-- Foreign-key indexes, for cascade deletes: a job / purchaseOrderLine delete+-- scans these columns. The two nullable targets are partial.+CREATE INDEX IF NOT EXISTS "planningAction_jobId_idx"+ ON "planningAction" ("jobId") WHERE "jobId" IS NOT NULL;+CREATE INDEX IF NOT EXISTS "planningAction_purchaseOrderLineId_idx"+ ON "planningAction" ("purchaseOrderLineId") WHERE "purchaseOrderLineId" IS NOT NULL;+CREATE INDEX IF NOT EXISTS "planningAction_supplierId_idx"+ ON "planningAction" ("supplierId") WHERE "supplierId" IS NOT NULL;+CREATE INDEX IF NOT EXISTS "planningAction_itemId_idx"+ ON "planningAction" ("itemId");+CREATE INDEX IF NOT EXISTS "planningAction_periodId_idx"+ ON "planningAction" ("periodId");+CREATE INDEX IF NOT EXISTS "planningAction_locationId_idx"+ ON "planningAction" ("locationId");++-- Deterministic regen identity (diff-write, `naturalKey` in+-- @carbon/planning): one non-terminal action per (item, location, type, and+-- the target order, or for a new order its week). A change action's week is+-- data, updated in place when its need moves, so it is not part of the key.+CREATE UNIQUE INDEX IF NOT EXISTS "planningAction_natural_key_idx" ON "planningAction"+ ("companyId", "itemId", "locationId", "type",+ (COALESCE("purchaseOrderLineId", "jobId", "periodId")))+ WHERE "status" <> 'Actioned';++-- RLS policies live in packages/database/src/authz/manifest.ts (`planningAction`)+-- and ship through the generated authz migration.+ALTER TABLE "public"."planningAction" ENABLE ROW LEVEL SECURITY;++-- Ownership ladder (tree: company default -> location -> location-specific item group -> item)+ALTER TABLE "itemPlanning" ADD COLUMN IF NOT EXISTS "responsibleEmployee" TEXT REFERENCES "user"("id");+ALTER TABLE "location" ADD COLUMN IF NOT EXISTS "responsibleEmployee" TEXT REFERENCES "user"("id");+ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "defaultResponsibleEmployee" TEXT REFERENCES "user"("id");+ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "rescheduleToleranceDays" INTEGER NOT NULL DEFAULT 7+ CHECK ("rescheduleToleranceDays" >= 0);++-- Composite-FK prerequisite: itemPostingGroup's PK is ("id") alone (parts.sql:69);+-- location already has UNIQUE ("id","companyId") via 20260905132037.+DO $$ BEGIN+ ALTER TABLE "itemPostingGroup"+ ADD CONSTRAINT "itemPostingGroup_id_companyId_key" UNIQUE ("id", "companyId");+EXCEPTION WHEN duplicate_table THEN NULL; WHEN duplicate_object THEN NULL; END $$;++-- Location-specific item-group ownership (the "location > item group" tier).+-- Sparse: rows exist only for configured (location, group) cells.+CREATE TABLE IF NOT EXISTS "itemPostingGroupResponsibility" (+ "id" TEXT NOT NULL DEFAULT id('pgr'),+ "companyId" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "itemPostingGroupId" TEXT NOT NULL,+ "responsibleEmployee" TEXT REFERENCES "user"("id"),+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_location_fkey"+ FOREIGN KEY ("locationId", "companyId") REFERENCES "location"("id", "companyId") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_group_fkey"+ FOREIGN KEY ("itemPostingGroupId", "companyId") REFERENCES "itemPostingGroup"("id", "companyId") ON DELETE CASCADE,+ CONSTRAINT "itemPostingGroupResponsibility_unique" UNIQUE ("companyId", "locationId", "itemPostingGroupId")+);++CREATE INDEX IF NOT EXISTS "itemPostingGroupResponsibility_companyId_idx" ON "itemPostingGroupResponsibility" ("companyId");+CREATE INDEX IF NOT EXISTS "itemPostingGroupResponsibility_createdBy_idx" ON "itemPostingGroupResponsibility" ("createdBy");++-- RLS policies live in packages/database/src/authz/manifest.ts+-- (`itemPostingGroupResponsibility`) and ship through the generated authz migration.+ALTER TABLE "public"."itemPostingGroupResponsibility" ENABLE ROW LEVEL SECURITY;diff --git a/packages/database/supabase/migrations/20261006130001_demand-forecast-consumption.sql b/packages/database/supabase/migrations/20261006130001_demand-forecast-consumption.sqlnew file mode 100644index 0000000000..cb099a0cd1--- /dev/null+++ b/packages/database/supabase/migrations/20261006130001_demand-forecast-consumption.sql@@ -0,0 +1,1191 @@+-- Demand forecast consumption: actual demand (open SO lines, job materials)+-- consumes the authored forecast (demandProjection) so the two never+-- double-count. runMrp computes consumption per weekly bucket (own bucket ->+-- backward N -> forward M, company settings below) and persists it as+-- demandProjection.consumedQuantity; every read path subtracts+-- GREATEST(forecastQuantity - consumedQuantity, 0).+-- Spec: .ai/specs/implemented/2026-09-11-demand-forecast-consumption.md++-- ============================================================+-- 1. Consumption state (MRP-written, derived — never user-authored)+-- ============================================================+ALTER TABLE "demandProjection"+ ADD COLUMN IF NOT EXISTS "consumedQuantity" NUMERIC NOT NULL DEFAULT 0;++-- ============================================================+-- 2. Company-level consumption window, in weekly periods+-- (0/0 = same-week netting only)+-- ============================================================+ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "forecastConsumptionBackwardPeriods" INTEGER NOT NULL DEFAULT 4+ CHECK ("forecastConsumptionBackwardPeriods" >= 0),+ ADD COLUMN IF NOT EXISTS "forecastConsumptionForwardPeriods" INTEGER NOT NULL DEFAULT 1+ CHECK ("forecastConsumptionForwardPeriods" >= 0);++-- ============================================================+-- 3. openSalesOrderLines: expose the pre-job-dedup open quantity as+-- "quantityToConsume". An MTO line fully covered by its linked job still+-- consumed the forecast that predicted it; only its residual+-- ("quantityToSend") drives new supply.+-- Forked from 20260811123619_widen-sales-production-scale.sql+-- ============================================================+DROP VIEW IF EXISTS "openSalesOrderLines";+CREATE VIEW "openSalesOrderLines" WITH (security_invoker=true) AS (+ SELECT+ sol."id",+ sol."salesOrderId",+ sol."itemId",+ sol."promisedDate",+ sol."methodType",+ sol."unitOfMeasureCode",+ CASE+ WHEN sol."methodType" = 'Make to Order' THEN GREATEST(+ sol."quantityToSend" - COALESCE((+ SELECT SUM(GREATEST(j."quantity" - j."quantityReceivedToInventory" - j."quantityShipped", 0))+ FROM "job" j+ WHERE j."salesOrderLineId" = sol."id"+ AND j."companyId" = sol."companyId"+ AND j."status" IN ('Planned', 'Ready', 'In Progress', 'Paused')+ ), 0),+ 0+ )+ ELSE sol."quantityToSend"+ END AS "quantityToSend",+ -- Pre-job-dedup open quantity: what this line CONSUMES from the demand+ -- forecast. An MTO line fully covered by its linked job still consumed+ -- the forecast that predicted it; only its residual drives new supply.+ sol."quantityToSend" AS "quantityToConsume",+ sol."salesOrderLineType",+ sol."companyId",+ COALESCE(sol."locationId", so."locationId") AS "locationId",+ i."replenishmentSystem",+ i."itemTrackingType",+ ir."leadTime"+ FROM "salesOrderLine" sol+ INNER JOIN "salesOrder" so ON sol."salesOrderId" = so."id"+ INNER JOIN "item" i ON sol."itemId" = i."id"+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"+ WHERE sol."salesOrderLineType" != 'Service'+ AND so."status" IN ('To Ship', 'To Ship and Invoice')+);++-- ============================================================+-- 4. get_production_planning: demandProjection arm nets consumption.+-- Forked from 20260715195226_planning-reads-demand-projections.sql+-- ============================================================+DROP FUNCTION IF EXISTS get_production_planning(TEXT, TEXT, TEXT[]);+CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id TEXT, periods TEXT[])+ RETURNS TABLE (+ "id" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "manufacturingBlocked" BOOLEAN,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,+ "quantityToOrder" NUMERIC,+ "supersessionMode" TEXT,+ "minimumReserveQuantity" NUMERIC,+ "week1" NUMERIC,+ "week2" NUMERIC,+ "week3" NUMERIC,+ "week4" NUMERIC,+ "week5" NUMERIC,+ "week6" NUMERIC,+ "week7" NUMERIC,+ "week8" NUMERIC,+ "week9" NUMERIC,+ "week10" NUMERIC,+ "week11" NUMERIC,+ "week12" NUMERIC,+ "week13" NUMERIC,+ "week14" NUMERIC,+ "week15" NUMERIC,+ "week16" NUMERIC,+ "week17" NUMERIC,+ "week18" NUMERIC,+ "week19" NUMERIC,+ "week20" NUMERIC,+ "week21" NUMERIC,+ "week22" NUMERIC,+ "week23" NUMERIC,+ "week24" NUMERIC,+ "week25" NUMERIC,+ "week26" NUMERIC,+ "week27" NUMERIC,+ "week28" NUMERIC,+ "week29" NUMERIC,+ "week30" NUMERIC,+ "week31" NUMERIC,+ "week32" NUMERIC,+ "week33" NUMERIC,+ "week34" NUMERIC,+ "week35" NUMERIC,+ "week36" NUMERIC,+ "week37" NUMERIC,+ "week38" NUMERIC,+ "week39" NUMERIC,+ "week40" NUMERIC,+ "week41" NUMERIC,+ "week42" NUMERIC,+ "week43" NUMERIC,+ "week44" NUMERIC,+ "week45" NUMERIC,+ "week46" NUMERIC,+ "week47" NUMERIC,+ "week48" NUMERIC,+ "week49" NUMERIC,+ "week50" NUMERIC,+ "week51" NUMERIC,+ "week52" NUMERIC+ ) AS $$+BEGIN+ -- Tenant guard: SECURITY DEFINER bypasses RLS and PostgREST lets any caller+ -- supply an arbitrary company_id. The shared guard every SECURITY DEFINER+ -- read opens with (20260925121735_rpc-function-guards.sql), as+ -- get_purchasing_planning below does: service_role and direct connections+ -- pass, anyone else must belong to the company.+ PERFORM assert_company_access(company_id);++ RETURN QUERY+ WITH RECURSIVE+ -- Incoming supply per item/period: received quantities (supplyActual) plus+ -- planned/expected receipts (supplyForecast, e.g. MRP planned orders).+ supply_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "supplyActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "supplyForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ -- Demand per item/period, from three sources:+ -- 1. demandActual — real demand (sales order lines, job materials)+ -- 2. demandForecast — MRP output: BOM-derived (child) demand+ -- 3. demandProjection — planner-entered top-level projections (NEW in this+ -- migration; previously missing, so purely-projected items never showed)+ demand_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "demandActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "demandForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ -- Top-level manual projections, net of forecast consumption: actual+ -- demand consumed them during the MRP run (consumedQuantity), so only+ -- the unconsumed remainder still drives demand here. Without this arm a+ -- make item whose only demand is a projection never appears in+ -- production planning to create jobs.+ SELECT "itemId", "periodId", NULL as "actualQuantity",+ GREATEST("forecastQuantity" - "consumedQuantity", 0) AS "forecastQuantity"+ FROM "demandProjection"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ -- Which items belong on the production planning screen: active Make items+ -- with replenishment + planning settings at this location, that either have+ -- demand in the selected periods or are stock-driven (reorder point with a+ -- Fixed Reorder Quantity / Maximum Quantity policy). Supersession rules drop+ -- obsolete/phased-out items.+ base_items AS (+ SELECT DISTINCT ON (i."id")+ i."id",+ i."readableIdWithRevision",+ i."name",+ i."active",+ i."type",+ i."itemTrackingType",+ i."replenishmentSystem",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."unitOfMeasureCode",+ ir."leadTime",+ ir."manufacturingBlocked",+ ir."lotSize",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."orderMultiple",+ ip."maximumInventoryQuantity",+ COALESCE((+ SELECT SUM("quantity")+ FROM "itemLedger"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "itemId" = i."id"+ ), 0) AS "quantityOnHand"+ FROM "item" i+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"+ WHERE i."companyId" = company_id+ AND i."replenishmentSystem" = 'Make'+ AND i."itemTrackingType" != 'Non-Inventory'+ AND i."active" = TRUE+ -- Supersession: drop obsolete items and items past their discontinuation+ -- date so no new orders are suggested.+ AND NOT EXISTS (+ SELECT 1 FROM "itemSupersession" ss+ WHERE ss."itemId" = i."id"+ AND (+ ss."supersessionMode" = 'No Stock'+ OR (+ -- date-based suppression applies only to the phase-out modes; Stock+ -- Only keeps replenishing to its reserve floor regardless of date.+ ss."supersessionMode" IN ('Consume First', 'Prefer New')+ AND ss."discontinuationDate" IS NOT NULL+ AND ss."discontinuationDate" <= CURRENT_DATE+ )+ )+ )+ AND (+ EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ OR (+ ip."reorderPoint" > 0+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')+ )+ )+ ),+ -- Week-by-week running inventory balance: start from on-hand, then for each+ -- selected period add supply and subtract demand (recursive walk). Negative+ -- values are the projected shortfall the planner needs to cover with jobs.+ projections AS (+ SELECT+ bi.*,+ periods[1] as "periodId",+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ 1 as period_index+ FROM base_items bi+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]++ UNION ALL++ SELECT+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."manufacturingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."maximumInventoryQuantity",+ p."quantityOnHand",+ periods[p.period_index + 1] as "periodId",+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ p.period_index + 1 as period_index+ FROM projections p+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]+ WHERE p.period_index < array_length(periods, 1)+ ),+ order_quantities AS (+ SELECT+ p."id",+ calculate_quantity_to_order(+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ array_agg(p."projection" ORDER BY p.period_index)+ ) AS "quantityToOrder"+ FROM projections p+ GROUP BY+ p."id",+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock"+ )+ SELECT DISTINCT ON (p."id")+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."manufacturingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ CASE+ WHEN ss."supersessionMode" = 'Stock Only'+ THEN GREATEST(+ 0,+ COALESCE(rsv."minimumReserveQuantity", 0)+ - p."quantityOnHand"+ - COALESCE(sup."incomingSupply", 0)+ )+ ELSE COALESCE(oq."quantityToOrder", 0)+ END AS "quantityToOrder",+ ss."supersessionMode"::TEXT AS "supersessionMode",+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"+ FROM projections p+ LEFT JOIN order_quantities oq ON p."id" = oq."id"+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id+ LEFT JOIN (+ SELECT "itemId", SUM("supply") AS "incomingSupply"+ FROM supply_data GROUP BY "itemId"+ ) sup ON sup."itemId" = p."id"+ GROUP BY+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."manufacturingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ oq."quantityToOrder",+ ss."supersessionMode",+ rsv."minimumReserveQuantity",+ sup."incomingSupply";+END;+$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public;++-- ============================================================+-- 5. get_purchasing_planning: the demandProjection arm nets consumption.+-- Forked from 20260925121735_rpc-function-guards.sql, which added the+-- assert_company_access guard every SECURITY DEFINER read must open with.+-- ============================================================+CREATE OR REPLACE FUNCTION public.get_purchasing_planning(company_id text, location_id text, periods text[])+ RETURNS TABLE(id text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "purchasingBlocked" boolean, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "orderMultiple" integer, "quantityOnHand" numeric, "maximumInventoryQuantity" numeric, suppliers jsonb, "preferredSupplierId" text, "purchasingUnitOfMeasureCode" text, "conversionFactor" numeric, "quantityToOrder" numeric, "supersessionMode" text, "minimumReserveQuantity" numeric, week1 numeric, week2 numeric, week3 numeric, week4 numeric, week5 numeric, week6 numeric, week7 numeric, week8 numeric, week9 numeric, week10 numeric, week11 numeric, week12 numeric, week13 numeric, week14 numeric, week15 numeric, week16 numeric, week17 numeric, week18 numeric, week19 numeric, week20 numeric, week21 numeric, week22 numeric, week23 numeric, week24 numeric, week25 numeric, week26 numeric, week27 numeric, week28 numeric, week29 numeric, week30 numeric, week31 numeric, week32 numeric, week33 numeric, week34 numeric, week35 numeric, week36 numeric, week37 numeric, week38 numeric, week39 numeric, week40 numeric, week41 numeric, week42 numeric, week43 numeric, week44 numeric, week45 numeric, week46 numeric, week47 numeric, week48 numeric, week49 numeric, week50 numeric, week51 numeric, week52 numeric)+ LANGUAGE sql+ SECURITY DEFINER+AS $function$+ SELECT assert_company_access(company_id);+ WITH RECURSIVE+ supply_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "supplyActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "supplyForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ demand_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "demandActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "demandForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ -- Top-level manual projections, net of forecast consumption: actual+ -- demand consumed them during the MRP run (consumedQuantity), so only+ -- the unconsumed remainder still drives demand here. Without this arm a+ -- purchased item whose only demand is a projection never appears in+ -- purchasing planning and never drives a suggested order.+ SELECT "itemId", "periodId", NULL as "actualQuantity",+ GREATEST("forecastQuantity" - "consumedQuantity", 0) AS "forecastQuantity"+ FROM "demandProjection"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ base_items AS (+ SELECT DISTINCT ON (i."id")+ i."id",+ i."readableIdWithRevision",+ i."name",+ i."active",+ i."type",+ i."itemTrackingType",+ i."replenishmentSystem",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."unitOfMeasureCode",+ ir."leadTime",+ ir."purchasingBlocked",+ ir."lotSize",+ ir."preferredSupplierId",+ ir."purchasingUnitOfMeasureCode",+ ir."conversionFactor",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."orderMultiple",+ ip."maximumInventoryQuantity",+ COALESCE(ps."suppliers", '[]'::jsonb) as "suppliers",+ COALESCE((+ SELECT SUM("quantity")+ FROM "itemLedger"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "itemId" = i."id"+ ), 0) AS "quantityOnHand"+ FROM "item" i+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"+ LEFT JOIN (+ SELECT+ ps."itemId",+ jsonb_agg(+ jsonb_build_object(+ 'id', ps."id",+ 'minimumOrderQuantity', ps."minimumOrderQuantity",+ 'supplierUnitOfMeasureCode', ps."supplierUnitOfMeasureCode",+ 'conversionFactor', ps."conversionFactor",+ 'unitPrice', ps."unitPrice",+ 'supplierId', ps."supplierId",+ 'supplierPartId', ps."supplierPartId"+ )+ ) AS "suppliers"+ FROM "supplierPart" ps+ WHERE ps."companyId" = company_id+ AND ps.active = true+ GROUP BY ps."itemId"+ ) ps ON ps."itemId" = i."id"+ WHERE i."companyId" = company_id+ AND i."replenishmentSystem" != 'Make'+ AND i."itemTrackingType" != 'Non-Inventory'+ AND i."active" = TRUE+ -- Supersession: drop obsolete items and items past their discontinuation+ -- date so no new orders are suggested.+ AND NOT EXISTS (+ SELECT 1 FROM "itemSupersession" ss+ WHERE ss."itemId" = i."id"+ AND (+ ss."supersessionMode" = 'No Stock'+ OR (+ -- date-based suppression applies only to the phase-out modes; Stock+ -- Only keeps replenishing to its reserve floor regardless of date.+ ss."supersessionMode" IN ('Consume First', 'Prefer New')+ AND ss."discontinuationDate" IS NOT NULL+ AND ss."discontinuationDate" <= CURRENT_DATE+ )+ )+ )+ AND (+ EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ OR (+ ip."reorderPoint" > 0+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')+ )+ )+ ),+ projections AS (+ SELECT+ bi.*,+ periods[1] as "periodId",+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ 1 as period_index+ FROM base_items bi+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]++ UNION ALL++ SELECT+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."quantityOnHand",+ periods[p.period_index + 1] as "periodId",+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ p.period_index + 1 as period_index+ FROM projections p+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]+ WHERE p.period_index < array_length(periods, 1)+ ),+ order_quantities AS (+ SELECT+ p."id",+ calculate_quantity_to_order(+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ array_agg(p."projection" ORDER BY p.period_index)+ ) AS "quantityToOrder"+ FROM projections p+ GROUP BY+ p."id",+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock"+ )+ SELECT DISTINCT ON (p."id")+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ CASE+ WHEN ss."supersessionMode" = 'Stock Only'+ THEN GREATEST(+ 0,+ COALESCE(rsv."minimumReserveQuantity", 0)+ - p."quantityOnHand"+ - COALESCE(sup."incomingSupply", 0)+ )+ ELSE COALESCE(oq."quantityToOrder", 0)+ END AS "quantityToOrder",+ ss."supersessionMode" AS "supersessionMode",+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"+ FROM projections p+ LEFT JOIN order_quantities oq ON p."id" = oq."id"+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id+ LEFT JOIN (+ SELECT "itemId", SUM("supply") AS "incomingSupply"+ FROM supply_data GROUP BY "itemId"+ ) sup ON sup."itemId" = p."id"+ GROUP BY+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ oq."quantityToOrder",+ ss."supersessionMode",+ rsv."minimumReserveQuantity",+ sup."incomingSupply";+$function$;++-- ============================================================+-- 6. get_inventory_quantities: ADD the net-projection arm to its demand CTE+-- (projections were previously omitted from inventory demand entirely).+-- Forked from 20260925121735_rpc-function-guards.sql+-- ============================================================+CREATE OR REPLACE FUNCTION public.get_inventory_quantities(company_id text, location_id text, item_id text DEFAULT NULL::text)+ RETURNS TABLE(id text, "readableId" text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "materialSubstanceId" text, "materialFormId" text, "dimensionId" text, dimension text, "finishId" text, finish text, "gradeId" text, grade text, "materialType" text, "materialTypeId" text, "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "maximumInventoryQuantity" numeric, "orderMultiple" integer, "quantityOnHand" numeric, "quantityOnHold" numeric, "quantityRejected" numeric, "quantityOnSalesOrder" numeric, "quantityOnPurchaseOrder" numeric, "quantityOnProductionOrder" numeric, "quantityOnProductionDemand" numeric, "demandForecast" numeric, "usageLast30Days" numeric, "usageLast90Days" numeric, "daysRemaining" numeric, "storageTypeIds" text[], "storageUnitIds" text[], tags text[])+ LANGUAGE plpgsql+ SECURITY DEFINER+ -- CREATE OR REPLACE drops the pin 20261003224019 set on this function.+ SET search_path = public, extensions+AS $function$+ DECLARE+ v_cutoff TIMESTAMPTZ;+ BEGIN+ PERFORM assert_company_access(company_id);++ SELECT MAX("snapshotCutoff") INTO v_cutoff+ FROM "itemLedgerSnapshot"+ WHERE "companyId" = company_id;++ RETURN QUERY++WITH+ open_purchase_orders AS (+ SELECT+ pol."itemId",+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"+ FROM+ "purchaseOrder" po+ INNER JOIN "purchaseOrderLine" pol+ ON pol."purchaseOrderId" = po."id"+ WHERE+ po."status" IN (+ 'Planned',+ 'To Receive',+ 'To Receive and Invoice'+ )+ AND po."companyId" = company_id+ AND pol."locationId" = location_id+ AND (item_id IS NULL OR pol."itemId" = item_id)+ GROUP BY pol."itemId"+ ),+ open_sales_orders AS (+ SELECT+ sol."itemId",+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"+ FROM+ "salesOrder" so+ INNER JOIN "salesOrderLine" sol+ ON sol."salesOrderId" = so."id"+ WHERE+ so."status" IN (+ 'Confirmed',+ 'To Ship and Invoice',+ 'To Ship',+ 'To Invoice',+ 'In Progress'+ )+ AND so."companyId" = company_id+ AND sol."locationId" = location_id+ AND (item_id IS NULL OR sol."itemId" = item_id)+ GROUP BY sol."itemId"+ ),+ open_job_requirements AS (+ SELECT+ jm."itemId",+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"+ FROM "jobMaterial" jm+ INNER JOIN "job" j ON jm."jobId" = j."id"+ WHERE j."status" IN (+ 'Planned',+ 'Ready',+ 'In Progress',+ 'Paused'+ )+ AND jm."methodType" != 'Make to Order'+ AND j."companyId" = company_id+ AND j."locationId" = location_id+ AND (item_id IS NULL OR jm."itemId" = item_id)+ GROUP BY jm."itemId"+ ),+ open_jobs AS (+ SELECT+ j."itemId",+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"+ FROM job j+ WHERE j."status" IN (+ 'Planned',+ 'Ready',+ 'In Progress',+ 'Paused'+ )+ AND j."companyId" = company_id+ AND j."locationId" = location_id+ AND (item_id IS NULL OR j."itemId" = item_id)+ GROUP BY j."itemId"+ ),+ -- Snapshot (immutable untracked rows) + live tracked rows + live untracked+ -- rows past the snapshot cutoff. With no snapshot (v_cutoff NULL) the third+ -- arm is the full untracked history — the pre-snapshot behavior.+ item_ledgers AS (+ SELECT+ combined."itemId",+ SUM(combined."quantityOnHand") AS "quantityOnHand",+ SUM(combined."quantityOnHold") AS "quantityOnHold",+ SUM(combined."quantityRejected") AS "quantityRejected",+ SUM(combined."consumed30") / 30 AS "usageLast30Days",+ SUM(combined."consumed90") / 90 AS "usageLast90Days"+ FROM (+ SELECT+ s."itemId",+ s."quantity" AS "quantityOnHand",+ 0::NUMERIC AS "quantityOnHold",+ 0::NUMERIC AS "quantityRejected",+ s."consumed30",+ s."consumed90"+ FROM "itemLedgerSnapshot" s+ WHERE s."companyId" = company_id+ AND s."locationId" = location_id+ AND (item_id IS NULL OR s."itemId" = item_id)++ UNION ALL++ SELECT+ il."itemId",+ CASE WHEN il."trackedEntityStatus" IS NULL+ OR il."trackedEntityStatus" != 'Rejected'+ THEN il."quantity" ELSE 0 END,+ CASE WHEN il."trackedEntityStatus" = 'On Hold'+ THEN il."quantity" ELSE 0 END,+ CASE WHEN il."trackedEntityStatus" = 'Rejected'+ THEN il."quantity" ELSE 0 END,+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'+ THEN -il."quantity" ELSE 0 END,+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'+ THEN -il."quantity" ELSE 0 END+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND (item_id IS NULL OR il."itemId" = item_id)+ AND il."trackedEntityId" IS NOT NULL++ UNION ALL++ SELECT+ il."itemId",+ CASE WHEN il."trackedEntityStatus" IS NULL+ OR il."trackedEntityStatus" != 'Rejected'+ THEN il."quantity" ELSE 0 END,+ CASE WHEN il."trackedEntityStatus" = 'On Hold'+ THEN il."quantity" ELSE 0 END,+ CASE WHEN il."trackedEntityStatus" = 'Rejected'+ THEN il."quantity" ELSE 0 END,+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'+ THEN -il."quantity" ELSE 0 END,+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'+ THEN -il."quantity" ELSE 0 END+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND (item_id IS NULL OR il."itemId" = item_id)+ AND il."trackedEntityId" IS NULL+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)+ ) combined+ GROUP BY combined."itemId"+ ),+ -- Distinct storage units the item is stocked in: snapshot arrays plus the+ -- same live arms. NULL storageUnitId rows are excluded.+ item_storage_units AS (+ SELECT+ u."itemId",+ ARRAY_AGG(DISTINCT u."storageUnitId") AS "storageUnitIds"+ FROM (+ SELECT s."itemId", su_id AS "storageUnitId"+ FROM "itemLedgerSnapshot" s+ CROSS JOIN LATERAL unnest(s."storageUnitIds") AS su_id+ WHERE s."companyId" = company_id+ AND s."locationId" = location_id+ AND (item_id IS NULL OR s."itemId" = item_id)++ UNION ALL++ SELECT il."itemId", il."storageUnitId"+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND il."storageUnitId" IS NOT NULL+ AND (item_id IS NULL OR il."itemId" = item_id)+ AND il."trackedEntityId" IS NOT NULL++ UNION ALL++ SELECT il."itemId", il."storageUnitId"+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND il."storageUnitId" IS NOT NULL+ AND (item_id IS NULL OR il."itemId" = item_id)+ AND il."trackedEntityId" IS NULL+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)+ ) u+ GROUP BY u."itemId"+ ),+ -- Distinct storage types, derived from the merged storage-unit ids.+ item_storage_types AS (+ SELECT+ isu."itemId",+ ARRAY_AGG(DISTINCT t) AS "storageTypeIds"+ FROM item_storage_units isu+ INNER JOIN "storageUnit" su+ ON su."id" = ANY(isu."storageUnitIds")+ AND su."companyId" = company_id+ CROSS JOIN LATERAL unnest(su."storageTypeIds") AS t+ GROUP BY isu."itemId"+ ),+ demand_forecast AS (+ SELECT combined."itemId", SUM(qty) AS "demandForecast"+ FROM (+ SELECT da."itemId", da."actualQuantity" AS qty+ FROM "demandActual" da+ WHERE da."companyId" = company_id AND da."locationId" = location_id+ AND (item_id IS NULL OR da."itemId" = item_id)+ UNION ALL+ SELECT df."itemId", df."forecastQuantity" AS qty+ FROM "demandForecast" df+ WHERE df."companyId" = company_id AND df."locationId" = location_id+ AND (item_id IS NULL OR df."itemId" = item_id)+ UNION ALL+ -- Planner-entered projections, net of forecast consumption. Previously+ -- omitted entirely, so a top-level item whose only demand was a+ -- projection showed zero forecast demand on the Inventory screen.+ -- Current and future weeks only: MRP re-nets a projection's consumption+ -- only inside its window, so a past week kept its last leftover and,+ -- unfiltered, every week that passed added to this total for good.+ SELECT dp."itemId", GREATEST(dp."forecastQuantity" - dp."consumedQuantity", 0) AS qty+ FROM "demandProjection" dp+ INNER JOIN "period" pr ON pr."id" = dp."periodId"+ WHERE dp."companyId" = company_id AND dp."locationId" = location_id+ AND (item_id IS NULL OR dp."itemId" = item_id)+ AND pr."endDate" >= location_today(location_id, company_id)+ ) combined+ GROUP BY combined."itemId"+ )++SELECT+ i."id",+ i."readableId",+ i."readableIdWithRevision",+ i."name",+ i."active",+ i."type",+ i."itemTrackingType",+ i."replenishmentSystem",+ m."materialSubstanceId",+ m."materialFormId",+ m."dimensionId",+ md."name" AS "dimension",+ m."finishId",+ mf."name" AS "finish",+ m."gradeId",+ mg."name" AS "grade",+ mt."name" AS "materialType",+ m."materialTypeId",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."unitOfMeasureCode",+ ir."leadTime",+ ir."lotSize",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."maximumInventoryQuantity",+ ip."orderMultiple",+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",+ COALESCE(il."quantityOnHold", 0) AS "quantityOnHold",+ COALESCE(il."quantityRejected", 0) AS "quantityRejected",+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand",+ COALESCE(df."demandForecast", 0) AS "demandForecast",+ COALESCE(il."usageLast30Days", 0) AS "usageLast30Days",+ COALESCE(il."usageLast90Days", 0) AS "usageLast90Days",+ CASE+ WHEN COALESCE(il."usageLast30Days", 0) > 0+ THEN ROUND(COALESCE(il."quantityOnHand", 0) / il."usageLast30Days", 2)+ ELSE NULL+ END AS "daysRemaining",+ COALESCE(ist."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds",+ COALESCE(isu."storageUnitIds", ARRAY[]::TEXT[]) AS "storageUnitIds",+ COALESCE(m."tags", p."tags", t."tags", c."tags") AS "tags"+FROM+ "item" i+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"+ LEFT JOIN item_storage_types ist ON i."id" = ist."itemId"+ LEFT JOIN item_storage_units isu ON i."id" = isu."itemId"+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"+ LEFT JOIN demand_forecast df ON i."id" = df."itemId"+ LEFT JOIN material m ON i."readableId" = m."id" AND m."companyId" = company_id+ LEFT JOIN part p ON i."readableId" = p."id" AND p."companyId" = company_id+ LEFT JOIN tool t ON i."readableId" = t."id" AND t."companyId" = company_id+ LEFT JOIN consumable c ON i."readableId" = c."id" AND c."companyId" = company_id+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"+ LEFT JOIN "materialFinish" mf ON m."finishId" = mf."id"+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"+ LEFT JOIN "itemReplenishment" ir ON i."id" = ir."itemId" AND ir."companyId" = company_id+ LEFT JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id+WHERE+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id+ AND (item_id IS NULL OR i."id" = item_id);+ END;+$function$;diff --git a/packages/database/supabase/migrations/20261006130004_planning-horizon.sql b/packages/database/supabase/migrations/20261006130004_planning-horizon.sqlnew file mode 100644index 0000000000..61a336aa11--- /dev/null+++ b/packages/database/supabase/migrations/20261006130004_planning-horizon.sql@@ -0,0 +1,292 @@+-- Planning horizon (time fence) for MRP planning actions.+--+-- MRP keeps generating actions over the whole planning window; the horizon is a+-- READ-TIME lens: the planning grids surface only the actions (and suggested new+-- orders) that fall on or before today + horizon days. Empty or 0 = no fence;+-- an item's 0 also opts it out of the company default, which empty inherits.+--+-- Named planningHorizonDays on purpose: planningTimeFenceDays is reserved by the+-- MRP v2 spec for the auto-firm fence, which is a different concept.+--+-- The fence is compared against planningAction."horizonDate", defined with the+-- table in 20261006130000_mrp-planning-actions.sql.++-- 1. Per item + location horizon, with a company-wide default.+ALTER TABLE "itemPlanning"+ ADD COLUMN IF NOT EXISTS "planningHorizonDays" INTEGER+ CHECK ("planningHorizonDays" IS NULL OR "planningHorizonDays" >= 0);++ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "defaultPlanningHorizonDays" INTEGER+ CHECK ("defaultPlanningHorizonDays" IS NULL OR "defaultPlanningHorizonDays" >= 0);++-- 2. Grid wrappers. The base RPCs stay the one definition of the projection+-- (generatePlanningActions reads them too); these add the columns only the+-- grids need and evaluate the Actions and Assignee filters in the+-- database, inside each item's fence, so the filter is complete at any volume+-- and paging stays correct.+--+-- SECURITY INVOKER: the base RPC asserts company access; everything joined+-- here runs under the caller's RLS.+--+-- `p.*` ties the column list below to the base RPC's. Adding a column to a+-- base RPC means re-creating its wrapper with the same column — the wrapper+-- fails loudly (return type mismatch) until then.++DROP FUNCTION IF EXISTS get_purchasing_planning_grid(TEXT, TEXT, TEXT[], DATE, TEXT[], TEXT);+DROP FUNCTION IF EXISTS get_purchasing_planning_grid(TEXT, TEXT, TEXT[], DATE, TEXT[], TEXT[]);+CREATE FUNCTION get_purchasing_planning_grid(+ company_id TEXT,+ location_id TEXT,+ periods TEXT[],+ as_of DATE DEFAULT NULL,+ action_types TEXT[] DEFAULT NULL,+ action_assignees TEXT[] DEFAULT NULL+)+ RETURNS TABLE (+ "id" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "purchasingBlocked" BOOLEAN,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,+ "suppliers" JSONB,+ "preferredSupplierId" TEXT,+ "purchasingUnitOfMeasureCode" TEXT,+ "conversionFactor" NUMERIC,+ "quantityToOrder" NUMERIC,+ "supersessionMode" TEXT,+ "minimumReserveQuantity" NUMERIC,+ "week1" NUMERIC, "week2" NUMERIC, "week3" NUMERIC, "week4" NUMERIC, "week5" NUMERIC, "week6" NUMERIC,+ "week7" NUMERIC, "week8" NUMERIC, "week9" NUMERIC, "week10" NUMERIC, "week11" NUMERIC, "week12" NUMERIC,+ "week13" NUMERIC, "week14" NUMERIC, "week15" NUMERIC, "week16" NUMERIC, "week17" NUMERIC, "week18" NUMERIC,+ "week19" NUMERIC, "week20" NUMERIC, "week21" NUMERIC, "week22" NUMERIC, "week23" NUMERIC, "week24" NUMERIC,+ "week25" NUMERIC, "week26" NUMERIC, "week27" NUMERIC, "week28" NUMERIC, "week29" NUMERIC, "week30" NUMERIC,+ "week31" NUMERIC, "week32" NUMERIC, "week33" NUMERIC, "week34" NUMERIC, "week35" NUMERIC, "week36" NUMERIC,+ "week37" NUMERIC, "week38" NUMERIC, "week39" NUMERIC, "week40" NUMERIC, "week41" NUMERIC, "week42" NUMERIC,+ "week43" NUMERIC, "week44" NUMERIC, "week45" NUMERIC, "week46" NUMERIC, "week47" NUMERIC, "week48" NUMERIC,+ "week49" NUMERIC, "week50" NUMERIC, "week51" NUMERIC, "week52" NUMERIC,+ "itemPostingGroupId" TEXT,+ "planningHorizonDays" INTEGER,+ "timeFenceDate" DATE,+ "firstNegativeDate" DATE,+ "latestOrderDate" DATE+ )+ LANGUAGE sql+ STABLE+ SECURITY INVOKER+AS $$+ SELECT+ p.*,+ (+ SELECT ic."itemPostingGroupId"+ FROM "itemCost" ic+ WHERE ic."itemId" = p."id"+ AND ic."companyId" = company_id+ LIMIT 1+ ) AS "itemPostingGroupId",+ h."days" AS "planningHorizonDays",+ (COALESCE(as_of, location_today(location_id, company_id)) + h."days") AS "timeFenceDate",+ (+ -- weekN is the projection for periods[N]+ SELECT MIN(pr."startDate")+ FROM unnest(periods) WITH ORDINALITY AS u("periodId", "n")+ INNER JOIN "period" pr ON pr."id" = u."periodId"+ WHERE (w."row" ->> ('week' || u."n"))::NUMERIC < 0+ ) AS "firstNegativeDate",+ (+ SELECT MIN(a."latestOrderDate")+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Order' OR a."purchaseOrderLineId" IS NOT NULL)+ ) AS "latestOrderDate"+ FROM get_purchasing_planning(company_id, location_id, periods) p+ -- OFFSET 0 keeps the planner from pulling to_jsonb(p) into the weekly+ -- firstNegativeDate subquery, where it ran 48 times per item (1.2 s against+ -- 0.8 s on 405 items). The JSON is built once per row.+ CROSS JOIN LATERAL (SELECT to_jsonb(p) AS "row" OFFSET 0) w+ CROSS JOIN LATERAL (+ -- 0 means "no fence", at either level. An item's 0 is how it opts OUT of a+ -- company default (empty would inherit it); NULLIF comes after the+ -- COALESCE so that 0 wins over the default instead of falling through.+ SELECT NULLIF(+ COALESCE(+ (+ SELECT ip."planningHorizonDays"+ FROM "itemPlanning" ip+ WHERE ip."itemId" = p."id"+ AND ip."locationId" = location_id+ AND ip."companyId" = company_id+ ),+ (+ SELECT cs."defaultPlanningHorizonDays"+ FROM "companySettings" cs+ WHERE cs."id" = company_id+ )+ ),+ 0+ ) AS "days"+ ) h+ WHERE (action_types IS NULL AND action_assignees IS NULL)+ OR EXISTS (+ SELECT 1+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Order' OR a."purchaseOrderLineId" IS NOT NULL)+ AND (action_types IS NULL OR a."type"::TEXT = ANY(action_types))+ AND (action_assignees IS NULL OR a."assignee" = ANY(action_assignees))+ AND (+ h."days" IS NULL+ OR a."horizonDate" <= COALESCE(as_of, location_today(location_id, company_id)) + h."days"+ )+ );+$$;++DROP FUNCTION IF EXISTS get_production_planning_grid(TEXT, TEXT, TEXT[], DATE, TEXT[], TEXT);+DROP FUNCTION IF EXISTS get_production_planning_grid(TEXT, TEXT, TEXT[], DATE, TEXT[], TEXT[]);+CREATE FUNCTION get_production_planning_grid(+ company_id TEXT,+ location_id TEXT,+ periods TEXT[],+ as_of DATE DEFAULT NULL,+ action_types TEXT[] DEFAULT NULL,+ action_assignees TEXT[] DEFAULT NULL+)+ RETURNS TABLE (+ "id" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "manufacturingBlocked" BOOLEAN,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,+ "quantityToOrder" NUMERIC,+ "supersessionMode" TEXT,+ "minimumReserveQuantity" NUMERIC,+ "week1" NUMERIC, "week2" NUMERIC, "week3" NUMERIC, "week4" NUMERIC, "week5" NUMERIC, "week6" NUMERIC,+ "week7" NUMERIC, "week8" NUMERIC, "week9" NUMERIC, "week10" NUMERIC, "week11" NUMERIC, "week12" NUMERIC,+ "week13" NUMERIC, "week14" NUMERIC, "week15" NUMERIC, "week16" NUMERIC, "week17" NUMERIC, "week18" NUMERIC,+ "week19" NUMERIC, "week20" NUMERIC, "week21" NUMERIC, "week22" NUMERIC, "week23" NUMERIC, "week24" NUMERIC,+ "week25" NUMERIC, "week26" NUMERIC, "week27" NUMERIC, "week28" NUMERIC, "week29" NUMERIC, "week30" NUMERIC,+ "week31" NUMERIC, "week32" NUMERIC, "week33" NUMERIC, "week34" NUMERIC, "week35" NUMERIC, "week36" NUMERIC,+ "week37" NUMERIC, "week38" NUMERIC, "week39" NUMERIC, "week40" NUMERIC, "week41" NUMERIC, "week42" NUMERIC,+ "week43" NUMERIC, "week44" NUMERIC, "week45" NUMERIC, "week46" NUMERIC, "week47" NUMERIC, "week48" NUMERIC,+ "week49" NUMERIC, "week50" NUMERIC, "week51" NUMERIC, "week52" NUMERIC,+ "itemPostingGroupId" TEXT,+ "planningHorizonDays" INTEGER,+ "timeFenceDate" DATE,+ "firstNegativeDate" DATE,+ "latestOrderDate" DATE+ )+ LANGUAGE sql+ STABLE+ SECURITY INVOKER+AS $$+ SELECT+ p.*,+ (+ SELECT ic."itemPostingGroupId"+ FROM "itemCost" ic+ WHERE ic."itemId" = p."id"+ AND ic."companyId" = company_id+ LIMIT 1+ ) AS "itemPostingGroupId",+ h."days" AS "planningHorizonDays",+ (COALESCE(as_of, location_today(location_id, company_id)) + h."days") AS "timeFenceDate",+ (+ -- weekN is the projection for periods[N]+ SELECT MIN(pr."startDate")+ FROM unnest(periods) WITH ORDINALITY AS u("periodId", "n")+ INNER JOIN "period" pr ON pr."id" = u."periodId"+ WHERE (w."row" ->> ('week' || u."n"))::NUMERIC < 0+ ) AS "firstNegativeDate",+ (+ SELECT MIN(a."latestOrderDate")+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Make' OR a."jobId" IS NOT NULL)+ ) AS "latestOrderDate"+ FROM get_production_planning(company_id, location_id, periods) p+ -- OFFSET 0 keeps the planner from pulling to_jsonb(p) into the weekly+ -- firstNegativeDate subquery, where it ran 48 times per item (1.2 s against+ -- 0.8 s on 405 items). The JSON is built once per row.+ CROSS JOIN LATERAL (SELECT to_jsonb(p) AS "row" OFFSET 0) w+ CROSS JOIN LATERAL (+ -- 0 means "no fence", at either level. An item's 0 is how it opts OUT of a+ -- company default (empty would inherit it); NULLIF comes after the+ -- COALESCE so that 0 wins over the default instead of falling through.+ SELECT NULLIF(+ COALESCE(+ (+ SELECT ip."planningHorizonDays"+ FROM "itemPlanning" ip+ WHERE ip."itemId" = p."id"+ AND ip."locationId" = location_id+ AND ip."companyId" = company_id+ ),+ (+ SELECT cs."defaultPlanningHorizonDays"+ FROM "companySettings" cs+ WHERE cs."id" = company_id+ )+ ),+ 0+ ) AS "days"+ ) h+ WHERE (action_types IS NULL AND action_assignees IS NULL)+ OR EXISTS (+ SELECT 1+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Make' OR a."jobId" IS NOT NULL)+ AND (action_types IS NULL OR a."type"::TEXT = ANY(action_types))+ AND (action_assignees IS NULL OR a."assignee" = ANY(action_assignees))+ AND (+ h."days" IS NULL+ OR a."horizonDate" <= COALESCE(as_of, location_today(location_id, company_id)) + h."days"+ )+ );+$$;diff --git a/packages/database/supabase/migrations/20261006130006_mrp-run-time.sql b/packages/database/supabase/migrations/20261006130006_mrp-run-time.sqlnew file mode 100644index 0000000000..fe83f94d2c--- /dev/null+++ b/packages/database/supabase/migrations/20261006130006_mrp-run-time.sql@@ -0,0 +1,6 @@+-- The time of day scheduled MRP runs for a company, on the company's own clock+-- (company.timezone). NULL keeps the default cadence: every 3 hours. When set,+-- the scheduled run happens once a day at this time instead. Manual runs and+-- the runs triggered by order/job status changes are unaffected.+ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "mrpRunTime" TIME;diff --git a/packages/database/supabase/migrations/20261006130100_planning-action-policies.sql b/packages/database/supabase/migrations/20261006130100_planning-action-policies.sqlnew file mode 100644index 0000000000..e4437caa5f--- /dev/null+++ b/packages/database/supabase/migrations/20261006130100_planning-action-policies.sql@@ -0,0 +1,30 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- itemPostingGroupResponsibility+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'itemPostingGroupResponsibility' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'itemPostingGroupResponsibility');+ END LOOP;+END+$authz$;+ALTER TABLE public."itemPostingGroupResponsibility" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."itemPostingGroupResponsibility" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));+CREATE POLICY "INSERT" ON "public"."itemPostingGroupResponsibility" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_update'))::text[]));+CREATE POLICY "UPDATE" ON "public"."itemPostingGroupResponsibility" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_update'))::text[]));+CREATE POLICY "DELETE" ON "public"."itemPostingGroupResponsibility" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('settings_update'))::text[]));++-- planningAction+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'planningAction' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'planningAction');+ END LOOP;+END+$authz$;+ALTER TABLE public."planningAction" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."planningAction" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));diff --git a/packages/database/supabase/migrations/20261006130200_planning-action-read.sql b/packages/database/supabase/migrations/20261006130200_planning-action-read.sqlnew file mode 100644index 0000000000..ba94a002ad--- /dev/null+++ b/packages/database/supabase/migrations/20261006130200_planning-action-read.sql@@ -0,0 +1,15 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- planningAction+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'planningAction' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'planningAction');+ END LOOP;+END+$authz$;+ALTER TABLE public."planningAction" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."planningAction" FOR SELECT USING (("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_view'))::text[]) OR "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[])));diff --git a/packages/database/supabase/migrations/20261006205037_planning-grid-order-quantity.sql b/packages/database/supabase/migrations/20261006205037_planning-grid-order-quantity.sqlnew file mode 100644index 0000000000..5c2a992d9e--- /dev/null+++ b/packages/database/supabase/migrations/20261006205037_planning-grid-order-quantity.sql@@ -0,0 +1,337 @@+-- The planning grids' order quantity: what the row's Order / Make button+-- offers, from MRP's open new-supply actions inside the item's planning+-- horizon (the same fence the Actions filter and latestOrderDate use).+--+-- The grids sorted and showed the base RPC's "quantityToOrder", a second sizing+-- of the weekly projection in SQL (calculate_quantity_to_order). It does not+-- see what MRP does after sizing — Expedites, Increases folded into open+-- orders, orders already placed — so the Qty to Order column and the default+-- sort disagreed with the Order button: an item MRP had nothing to order for+-- sorted above items with real shortages. The base RPCs keep "quantityToOrder"+-- (generatePlanningActions reads it for Stock Only items).+--+-- Re-created rather than replaced: the return type gains a column.++DROP FUNCTION IF EXISTS get_purchasing_planning_grid(TEXT, TEXT, TEXT[], DATE, TEXT[], TEXT[]);+CREATE FUNCTION get_purchasing_planning_grid(+ company_id TEXT,+ location_id TEXT,+ periods TEXT[],+ as_of DATE DEFAULT NULL,+ action_types TEXT[] DEFAULT NULL,+ action_assignees TEXT[] DEFAULT NULL+)+ RETURNS TABLE (+ "id" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "purchasingBlocked" BOOLEAN,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,+ "suppliers" JSONB,+ "preferredSupplierId" TEXT,+ "purchasingUnitOfMeasureCode" TEXT,+ "conversionFactor" NUMERIC,+ "quantityToOrder" NUMERIC,+ "supersessionMode" TEXT,+ "minimumReserveQuantity" NUMERIC,+ "week1" NUMERIC, "week2" NUMERIC, "week3" NUMERIC, "week4" NUMERIC, "week5" NUMERIC, "week6" NUMERIC,+ "week7" NUMERIC, "week8" NUMERIC, "week9" NUMERIC, "week10" NUMERIC, "week11" NUMERIC, "week12" NUMERIC,+ "week13" NUMERIC, "week14" NUMERIC, "week15" NUMERIC, "week16" NUMERIC, "week17" NUMERIC, "week18" NUMERIC,+ "week19" NUMERIC, "week20" NUMERIC, "week21" NUMERIC, "week22" NUMERIC, "week23" NUMERIC, "week24" NUMERIC,+ "week25" NUMERIC, "week26" NUMERIC, "week27" NUMERIC, "week28" NUMERIC, "week29" NUMERIC, "week30" NUMERIC,+ "week31" NUMERIC, "week32" NUMERIC, "week33" NUMERIC, "week34" NUMERIC, "week35" NUMERIC, "week36" NUMERIC,+ "week37" NUMERIC, "week38" NUMERIC, "week39" NUMERIC, "week40" NUMERIC, "week41" NUMERIC, "week42" NUMERIC,+ "week43" NUMERIC, "week44" NUMERIC, "week45" NUMERIC, "week46" NUMERIC, "week47" NUMERIC, "week48" NUMERIC,+ "week49" NUMERIC, "week50" NUMERIC, "week51" NUMERIC, "week52" NUMERIC,+ "itemPostingGroupId" TEXT,+ "planningHorizonDays" INTEGER,+ "timeFenceDate" DATE,+ "firstNegativeDate" DATE,+ "latestOrderDate" DATE,+ "orderQuantity" NUMERIC+ )+ LANGUAGE sql+ STABLE+ SECURITY INVOKER+AS $$+ SELECT+ p.*,+ (+ SELECT ic."itemPostingGroupId"+ FROM "itemCost" ic+ WHERE ic."itemId" = p."id"+ AND ic."companyId" = company_id+ LIMIT 1+ ) AS "itemPostingGroupId",+ h."days" AS "planningHorizonDays",+ (COALESCE(as_of, location_today(location_id, company_id)) + h."days") AS "timeFenceDate",+ (+ -- weekN is the projection for periods[N]+ SELECT MIN(pr."startDate")+ FROM unnest(periods) WITH ORDINALITY AS u("periodId", "n")+ INNER JOIN "period" pr ON pr."id" = u."periodId"+ WHERE (w."row" ->> ('week' || u."n"))::NUMERIC < 0+ ) AS "firstNegativeDate",+ (+ SELECT MIN(a."latestOrderDate")+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Order' OR a."purchaseOrderLineId" IS NOT NULL)+ ) AS "latestOrderDate",+ (+ -- What the row's Order / Make button offers: the open Order actions+ -- MRP wrote, inside the item's fence. The base RPC's quantityToOrder+ -- sizes the projection again and knows nothing of what MRP did after+ -- sizing — Expedites, Increases, orders already placed — so sorted on+ -- it, rows with nothing to order sat above rows with real shortages.+ -- 0, not NULL, when there is nothing: a descending sort puts NULLs first+ SELECT COALESCE(SUM(a."suggestedQuantity"), 0)+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND a."type" = 'Order'+ AND a."purchaseOrderLineId" IS NULL+ AND (+ h."days" IS NULL+ OR a."horizonDate" <= COALESCE(as_of, location_today(location_id, company_id)) + h."days"+ )+ ) AS "orderQuantity"+ FROM get_purchasing_planning(company_id, location_id, periods) p+ -- OFFSET 0 keeps the planner from pulling to_jsonb(p) into the weekly+ -- firstNegativeDate subquery, where it ran 48 times per item (1.2 s against+ -- 0.8 s on 405 items). The JSON is built once per row.+ CROSS JOIN LATERAL (SELECT to_jsonb(p) AS "row" OFFSET 0) w+ CROSS JOIN LATERAL (+ -- 0 means "no fence", at either level. An item's 0 is how it opts OUT of a+ -- company default (empty would inherit it); NULLIF comes after the+ -- COALESCE so that 0 wins over the default instead of falling through.+ SELECT NULLIF(+ COALESCE(+ (+ SELECT ip."planningHorizonDays"+ FROM "itemPlanning" ip+ WHERE ip."itemId" = p."id"+ AND ip."locationId" = location_id+ AND ip."companyId" = company_id+ ),+ (+ SELECT cs."defaultPlanningHorizonDays"+ FROM "companySettings" cs+ WHERE cs."id" = company_id+ )+ ),+ 0+ ) AS "days"+ ) h+ WHERE (action_types IS NULL AND action_assignees IS NULL)+ OR EXISTS (+ SELECT 1+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Order' OR a."purchaseOrderLineId" IS NOT NULL)+ -- A Release applies only while its order is Planned; between runs the+ -- order can move on (sent, released) and the stale row must not match.+ -- Compared as text: the enum value is added by a later migration.+ AND (+ a."type"::TEXT <> 'Release'+ OR EXISTS (+ SELECT 1+ FROM "purchaseOrderLine" pol+ INNER JOIN "purchaseOrder" po ON po."id" = pol."purchaseOrderId"+ WHERE pol."id" = a."purchaseOrderLineId"+ AND po."status" = 'Planned'+ )+ )+ AND (action_types IS NULL OR a."type"::TEXT = ANY(action_types))+ AND (action_assignees IS NULL OR a."assignee" = ANY(action_assignees))+ AND (+ h."days" IS NULL+ OR a."horizonDate" <= COALESCE(as_of, location_today(location_id, company_id)) + h."days"+ )+ );+$$;++DROP FUNCTION IF EXISTS get_production_planning_grid(TEXT, TEXT, TEXT[], DATE, TEXT[], TEXT[]);+CREATE FUNCTION get_production_planning_grid(+ company_id TEXT,+ location_id TEXT,+ periods TEXT[],+ as_of DATE DEFAULT NULL,+ action_types TEXT[] DEFAULT NULL,+ action_assignees TEXT[] DEFAULT NULL+)+ RETURNS TABLE (+ "id" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "manufacturingBlocked" BOOLEAN,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,+ "quantityToOrder" NUMERIC,+ "supersessionMode" TEXT,+ "minimumReserveQuantity" NUMERIC,+ "week1" NUMERIC, "week2" NUMERIC, "week3" NUMERIC, "week4" NUMERIC, "week5" NUMERIC, "week6" NUMERIC,+ "week7" NUMERIC, "week8" NUMERIC, "week9" NUMERIC, "week10" NUMERIC, "week11" NUMERIC, "week12" NUMERIC,+ "week13" NUMERIC, "week14" NUMERIC, "week15" NUMERIC, "week16" NUMERIC, "week17" NUMERIC, "week18" NUMERIC,+ "week19" NUMERIC, "week20" NUMERIC, "week21" NUMERIC, "week22" NUMERIC, "week23" NUMERIC, "week24" NUMERIC,+ "week25" NUMERIC, "week26" NUMERIC, "week27" NUMERIC, "week28" NUMERIC, "week29" NUMERIC, "week30" NUMERIC,+ "week31" NUMERIC, "week32" NUMERIC, "week33" NUMERIC, "week34" NUMERIC, "week35" NUMERIC, "week36" NUMERIC,+ "week37" NUMERIC, "week38" NUMERIC, "week39" NUMERIC, "week40" NUMERIC, "week41" NUMERIC, "week42" NUMERIC,+ "week43" NUMERIC, "week44" NUMERIC, "week45" NUMERIC, "week46" NUMERIC, "week47" NUMERIC, "week48" NUMERIC,+ "week49" NUMERIC, "week50" NUMERIC, "week51" NUMERIC, "week52" NUMERIC,+ "itemPostingGroupId" TEXT,+ "planningHorizonDays" INTEGER,+ "timeFenceDate" DATE,+ "firstNegativeDate" DATE,+ "latestOrderDate" DATE,+ "orderQuantity" NUMERIC+ )+ LANGUAGE sql+ STABLE+ SECURITY INVOKER+AS $$+ SELECT+ p.*,+ (+ SELECT ic."itemPostingGroupId"+ FROM "itemCost" ic+ WHERE ic."itemId" = p."id"+ AND ic."companyId" = company_id+ LIMIT 1+ ) AS "itemPostingGroupId",+ h."days" AS "planningHorizonDays",+ (COALESCE(as_of, location_today(location_id, company_id)) + h."days") AS "timeFenceDate",+ (+ -- weekN is the projection for periods[N]+ SELECT MIN(pr."startDate")+ FROM unnest(periods) WITH ORDINALITY AS u("periodId", "n")+ INNER JOIN "period" pr ON pr."id" = u."periodId"+ WHERE (w."row" ->> ('week' || u."n"))::NUMERIC < 0+ ) AS "firstNegativeDate",+ (+ SELECT MIN(a."latestOrderDate")+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Make' OR a."jobId" IS NOT NULL)+ ) AS "latestOrderDate",+ (+ -- What the row's Order / Make button offers: the open Make actions+ -- MRP wrote, inside the item's fence. The base RPC's quantityToOrder+ -- sizes the projection again and knows nothing of what MRP did after+ -- sizing — Expedites, Increases, orders already placed — so sorted on+ -- it, rows with nothing to order sat above rows with real shortages.+ -- 0, not NULL, when there is nothing: a descending sort puts NULLs first+ SELECT COALESCE(SUM(a."suggestedQuantity"), 0)+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND a."type" = 'Make'+ AND a."jobId" IS NULL+ AND (+ h."days" IS NULL+ OR a."horizonDate" <= COALESCE(as_of, location_today(location_id, company_id)) + h."days"+ )+ ) AS "orderQuantity"+ FROM get_production_planning(company_id, location_id, periods) p+ -- OFFSET 0 keeps the planner from pulling to_jsonb(p) into the weekly+ -- firstNegativeDate subquery, where it ran 48 times per item (1.2 s against+ -- 0.8 s on 405 items). The JSON is built once per row.+ CROSS JOIN LATERAL (SELECT to_jsonb(p) AS "row" OFFSET 0) w+ CROSS JOIN LATERAL (+ -- 0 means "no fence", at either level. An item's 0 is how it opts OUT of a+ -- company default (empty would inherit it); NULLIF comes after the+ -- COALESCE so that 0 wins over the default instead of falling through.+ SELECT NULLIF(+ COALESCE(+ (+ SELECT ip."planningHorizonDays"+ FROM "itemPlanning" ip+ WHERE ip."itemId" = p."id"+ AND ip."locationId" = location_id+ AND ip."companyId" = company_id+ ),+ (+ SELECT cs."defaultPlanningHorizonDays"+ FROM "companySettings" cs+ WHERE cs."id" = company_id+ )+ ),+ 0+ ) AS "days"+ ) h+ WHERE (action_types IS NULL AND action_assignees IS NULL)+ OR EXISTS (+ SELECT 1+ FROM "planningAction" a+ WHERE a."companyId" = company_id+ AND a."itemId" = p."id"+ AND a."locationId" = location_id+ AND a."status" = 'Open'+ AND (a."type" = 'Make' OR a."jobId" IS NOT NULL)+ -- A Release applies only while its order is Planned; between runs the+ -- order can move on (sent, released) and the stale row must not match.+ -- Compared as text: the enum value is added by a later migration.+ AND (+ a."type"::TEXT <> 'Release'+ OR EXISTS (+ SELECT 1+ FROM "job" j+ WHERE j."id" = a."jobId"+ AND j."companyId" = company_id+ AND j."status" = 'Planned'+ )+ )+ AND (action_types IS NULL OR a."type"::TEXT = ANY(action_types))+ AND (action_assignees IS NULL OR a."assignee" = ANY(action_assignees))+ AND (+ h."days" IS NULL+ OR a."horizonDate" <= COALESCE(as_of, location_today(location_id, company_id)) + h."days"+ )+ );+$$;diff --git a/packages/database/supabase/migrations/20261006210557_planning-action-release.sql b/packages/database/supabase/migrations/20261006210557_planning-action-release.sqlnew file mode 100644index 0000000000..f221dd67a1--- /dev/null+++ b/packages/database/supabase/migrations/20261006210557_planning-action-release.sql@@ -0,0 +1,8 @@+-- Release: a planned order that is due to be released. MRP raises one on every+-- line of a Planned purchase order and on every Planned job, dated the day+-- before the order's due date less the item's lead time (a purchase order takes+-- the earliest of its lines). It is not applied from planning — the row links+-- to the order, which is released there — and it applies only while the order+-- is Planned: the next run drops it, and the planning pages hide it as soon as+-- the order's status moves on.+ALTER TYPE "planningActionType" ADD VALUE IF NOT EXISTS 'Release';diff --git a/packages/database/supabase/migrations/20261006214907_planning-purchase-order-approval.sql b/packages/database/supabase/migrations/20261006214907_planning-purchase-order-approval.sqlnew file mode 100644index 0000000000..d5b7a8a208--- /dev/null+++ b/packages/database/supabase/migrations/20261006214907_planning-purchase-order-approval.sql@@ -0,0 +1,14 @@+-- Purchase orders raised by the planning pages skip the approval rule when the+-- company allows it (on by default).+--+-- "createdFromPlanning" is set only on a PO the planning Order button creates.+-- Any manual line change afterwards — adding, editing or deleting a line on the+-- PO page, the API or MCP (upsertPurchaseOrderLine / deletePurchaseOrderLine) —+-- clears it, so an MRP purchase order cannot be padded to dodge approval.+-- Planning's own writes (its Order button, Apply, the drawer's inline edit)+-- keep it. The finalize route reads both columns.+ALTER TABLE "purchaseOrder"+ ADD COLUMN IF NOT EXISTS "createdFromPlanning" BOOLEAN NOT NULL DEFAULT false;++ALTER TABLE "companySettings"+ ADD COLUMN IF NOT EXISTS "skipApprovalForPlanningPurchaseOrders" BOOLEAN NOT NULL DEFAULT true;diff --git a/packages/ee/src/accounting/core/operations.ts b/packages/ee/src/accounting/core/operations.tsindex bf7783fbfb..194c64ba37 100644--- a/packages/ee/src/accounting/core/operations.ts+++ b/packages/ee/src/accounting/core/operations.ts@@ -3,6 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import type { Database } from "@carbon/database";+import { isUniqueViolation } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { SYNC_OPERATION_ALLOWED_TRANSITIONS } from "./models";import type {@@ -32,7 +33,6 @@ export const SYNC_OPERATION_STALE_IN_FLIGHT_MS = 10 * 60_000;const DEFAULT_CLAIM_LIMIT = 20;const DEFAULT_PAGE_SIZE = 25;-const UNIQUE_VIOLATION = "23505";/*** Live operations hold the partial unique index on@@ -246,7 +246,7 @@ export async function enqueueSyncOperation(.single();if (inserted.error) {- if (inserted.error.code === UNIQUE_VIOLATION) {+ if (isUniqueViolation(inserted.error)) {// A concurrent enqueue won the race on one of the unique indexes —// absorb by returning whichever row now holds itconst byKey = await getOperationByIdempotencyKey(client, op);@@ -338,7 +338,7 @@ export async function insertTerminalSyncOperation(.single();if (inserted.error) {- if (inserted.error.code === UNIQUE_VIOLATION) {+ if (isUniqueViolation(inserted.error)) {const byKey = await getOperationByIdempotencyKey(client, op);if (byKey.data) return byKey;diff --git a/packages/ee/src/stripe-connect/payment.server.ts b/packages/ee/src/stripe-connect/payment.server.tsindex ad771bb639..8c625326c9 100644--- a/packages/ee/src/stripe-connect/payment.server.ts+++ b/packages/ee/src/stripe-connect/payment.server.ts@@ -19,7 +19,7 @@ import {getConnectInvoicePaymentDetails,toStripeAmount} from "@carbon/stripe/connect.server";-import { datetime } from "@carbon/utils";+import { datetime, isUniqueViolation } from "@carbon/utils";import { fromAbsolute, toCalendarDate } from "@internationalized/date";import { PostgresDriver, sql } from "kysely";import { createMappingService } from "../accounting/index";@@ -446,7 +446,7 @@ export async function recordStripeConnectPayment({);} catch (err) {await serviceRole.from("payment").delete().eq("id", paymentId);- if ((err as { code?: string }).code === "23505") {+ if (isUniqueViolation(err)) {return {status: "skipped",reason: `Stripe invoice ${stripeInvoiceId} was recorded concurrently by another delivery`diff --git a/packages/ee/src/workflows/catalog/events.generated.ts b/packages/ee/src/workflows/catalog/events.generated.tsindex bb3036e6da..3d1190b9c9 100644--- a/packages/ee/src/workflows/catalog/events.generated.ts+++ b/packages/ee/src/workflows/catalog/events.generated.ts@@ -1055,7 +1055,8 @@ export const WORKFLOW_ENTITIES: Record<string, Record<string, ValueType>> = {createdAt: { kind: "primitive", of: "date" },tags: { kind: "list", of: { kind: "primitive", of: "string" } },code: { kind: "primitive", of: "string" },- requiresStaffing: { kind: "primitive", of: "boolean" }+ requiresStaffing: { kind: "primitive", of: "boolean" },+ responsibleEmployee: { kind: "entity", of: "user" }},nonConformance: {id: { kind: "primitive", of: "string" },@@ -1142,7 +1143,8 @@ export const WORKFLOW_ENTITIES: Record<string, Record<string, ValueType>> = {supplierInteractionId: { kind: "primitive", of: "string" },purchaseOrderType: { kind: "primitive", of: "string" },jobId: { kind: "entity", of: "job" },- jobReadableId: { kind: "primitive", of: "string" }+ jobReadableId: { kind: "primitive", of: "string" },+ createdFromPlanning: { kind: "primitive", of: "boolean" }},quote: {id: { kind: "primitive", of: "string" },diff --git a/packages/ee/src/workflows/catalog/labels.generated.ts b/packages/ee/src/workflows/catalog/labels.generated.tsindex 622ce052b7..bdb024c894 100644--- a/packages/ee/src/workflows/catalog/labels.generated.ts+++ b/packages/ee/src/workflows/catalog/labels.generated.ts@@ -239,6 +239,7 @@ export const WORKFLOW_LABELS: Record<string, MessageDescriptor> = {"entity.location.name": msg`Name`,"entity.location.postalCode": msg`Postal code`,"entity.location.requiresStaffing": msg`Requires staffing`,+ "entity.location.responsibleEmployee": msg`Responsible employee`,"entity.location.stateProvince": msg`State province`,"entity.location.tags": msg`Tags`,"entity.location.timezone": msg`Timezone`,@@ -303,6 +304,7 @@ export const WORKFLOW_LABELS: Record<string, MessageDescriptor> = {"entity.purchaseOrder.closedBy": msg`Closed by`,"entity.purchaseOrder.createdAt": msg`Created at`,"entity.purchaseOrder.createdBy": msg`Created by`,+ "entity.purchaseOrder.createdFromPlanning": msg`Created from planning`,"entity.purchaseOrder.currencyCode": msg`Currency code`,"entity.purchaseOrder.exchangeRate": msg`Exchange rate`,"entity.purchaseOrder.exchangeRateUpdatedAt": msg`Exchange rate updated at`,diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 66038b6837..3cba5a780d 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -62,6 +62,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic || `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers || `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |+| `mrp` | `*/15 * * * *` | Scheduled MRP. Each tick plans only the companies that are DUE — every 3 hours (UTC) by default, or once a day at `companySettings.mrpRunTime` on the company's clock (`isMrpDue` / `mrpTick`) — and have planning work (`companiesWithPlanningWork`), both in `scheduled/mrp-companies.ts`; one `step.run` per company |## Safety Notesdiff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex d5dddf2016..e65a8f53c8 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261005041631",+ "schemaVersion": "20261006130200","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-05T04:22:58.312Z",+ "exportedAt": "2026-10-06T01:27:39.616Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -433,10 +433,16 @@"showCurrencyTrailingZeros","requireMfa","allowLowercaseItemIds",+ "defaultResponsibleEmployee",+ "rescheduleToleranceDays",+ "forecastConsumptionBackwardPeriods",+ "forecastConsumptionForwardPeriods","includeOperationsOnTraveler","requireSupplierContactAndLocation","requireCustomerContactAndLocation",- "showBomExplorerReadableId"+ "showBomExplorerReadableId",+ "defaultPlanningHorizonDays",+ "mrpRunTime"]},{@@ -1178,7 +1184,8 @@"customFields","tags","code",- "requiresStaffing"+ "requiresStaffing",+ "responsibleEmployee"]},{@@ -1288,6 +1295,21 @@"customFields"]},+ {+ "name": "itemPostingGroupResponsibility",+ "rows": 0,+ "columns": [+ "id",+ "companyId",+ "locationId",+ "itemPostingGroupId",+ "responsibleEmployee",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt"+ ]+ },{"name": "maintenanceFailureMode","rows": 0,@@ -2830,7 +2852,8 @@"createdAt","updatedAt","updatedBy",- "id"+ "id",+ "consumedQuantity"]},{@@ -3002,7 +3025,9 @@"tags","maximumInventoryQuantity","demandAccumulationSafetyStock",- "minimumReserveQuantity"+ "minimumReserveQuantity",+ "responsibleEmployee",+ "planningHorizonDays"]},{@@ -5508,6 +5533,37 @@"employeeId"]},+ {+ "name": "planningAction",+ "rows": 0,+ "columns": [+ "id",+ "companyId",+ "itemId",+ "locationId",+ "periodId",+ "type",+ "status",+ "suggestedQuantity",+ "suggestedDate",+ "isASAP",+ "purchaseOrderLineId",+ "jobId",+ "requiresManualAction",+ "supplierId",+ "policyName",+ "reason",+ "triggerValues",+ "assignee",+ "assigneeOverridden",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt",+ "horizonDate",+ "latestOrderDate"+ ]+ },{"name": "purchaseInvoiceDelivery","rows": 0,diff --git a/packages/jobs/src/demo-planning.ts b/packages/jobs/src/demo-planning.tsindex e84e49177a..092c2d069f 100644--- a/packages/jobs/src/demo-planning.ts+++ b/packages/jobs/src/demo-planning.ts@@ -22,7 +22,7 @@ function message(err: unknown): string {/*** Same calls as the MRP cron and `api+/schedule.ts`. Must run after the seed commits- * (both engines read over PostgREST). Never throws: the 3-hourly MRP cron is the backstop.+ * (both engines read over PostgREST). Never throws: the scheduled MRP run is the backstop.*/export async function planDemoCompany({companyId,diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.tsindex 5e34edf777..deeaab23e9 100644--- a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts@@ -9,6 +9,7 @@ import {storage,TEMP_STAGING_BUCKET} from "@carbon/files";+import { isUniqueViolation } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import { resolveModelSourceBucket } from "../tasks/assembler-client";@@ -158,7 +159,7 @@ async function ensureImmutableModel(if (inserted.error) {// Do not turn a failed write into success unless another caller actually// committed THIS model in THIS company. Other insert errors remain errors.- if (inserted.error.code !== "23505" || !(await lookup())) {+ if (!isUniqueViolation(inserted.error) || !(await lookup())) {throw new Error(`attachOnshapeAssetsToItem: modelUpload insert failed: ${inserted.error.message}`);diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.tsindex 90f068e222..b374831c58 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts@@ -2,8 +2,26 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { KyselyDatabase } from "@carbon/database/client";+import { parseAbsolute } from "@internationalized/date";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";import { describe, expect, it } from "vitest";-import { selectCompaniesForMrp } from "./mrp-companies";+import {+ companiesWithPlanningWork,+ isMrpDue,+ MRP_TICK_MINUTES,+ mrpTick,+ selectCompaniesForMrp+} from "./mrp-companies";const companies = [{ id: "c1", name: "Acme" },@@ -77,3 +95,202 @@ describe("selectCompaniesForMrp with a planning-work lookup", () => {expect(result.map((c) => c.id)).toEqual(["c2"]);});});++// The Postgres wire is the boundary: the lookup's one statement is recorded+// as compiled SQL, and answered with the rows Postgres would return.+class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ constructor(private readonly rows: { companyId: string | null }[]) {+ super();+ }+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ this.sent.push(query);+ return { rows: this.rows as R[] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+}++async function lookup(rows: { companyId: string | null }[] = []) {+ const driver = new RecordingDriver(rows);+ const db = new Kysely<KyselyDatabase>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ });+ const companies = await companiesWithPlanningWork(db);+ expect(driver.sent).toHaveLength(1);+ return { companies, query: driver.sent[0]! };+}++describe("companiesWithPlanningWork", () => {+ it("returns each company once and drops a null", async () => {+ const { companies } = await lookup([+ { companyId: "c1" },+ { companyId: null },+ { companyId: "c2" }+ ]);+ expect([...companies]).toEqual(["c1", "c2"]);+ });++ // A reorder policy orders from on-hand alone: no document, no forecast,+ // nothing an earlier run wrote. Such a company was skipped, and its+ // safety-stock and reorder-point Orders never appeared.+ it("includes a company whose only need is a reorder floor", async () => {+ const { query } = await lookup();+ expect(query.sql).toContain('from "itemPlanning"');+ expect(query.sql).toMatch(/"minimumReserveQuantity" > \$\d+/);+ expect(query.sql).toMatch(/"demandAccumulationSafetyStock" > \$\d+/);+ expect(query.sql).toMatch(/"reorderPoint" > \$\d+/);+ expect(query.parameters).toEqual(+ expect.arrayContaining([+ "Demand-Based Reorder",+ "Fixed Reorder Quantity",+ "Maximum Quantity"+ ])+ );+ // "not Manual Reorder" alone would be every company: it is the default+ expect(query.parameters).not.toContain("Manual Reorder");+ });++ it("includes a company with stock below zero", async () => {+ const { query } = await lookup();+ expect(query.sql).toContain('from "itemStockQuantities"');+ expect(query.sql).toMatch(/"quantityOnHand" < \$\d+/);+ });+});++const utc = (instant: string) => parseAbsolute(instant, "UTC");++/** The ticks of one UTC day a company is due on, as "HH:MM". */+function dueTicks(+ day: string,+ schedule: { timezone: string; mrpRunTime: string | null }+) {+ const due: string[] = [];+ let tick = utc(`${day}T00:00:00Z`);+ for (let i = 0; i < (24 * 60) / MRP_TICK_MINUTES; i++) {+ if (isMrpDue(tick, schedule)) {+ due.push(+ `${String(tick.hour).padStart(2, "0")}:${String(tick.minute).padStart(2, "0")}`+ );+ }+ tick = tick.add({ minutes: MRP_TICK_MINUTES });+ }+ return due;+}++describe("mrpTick", () => {+ it("is the cron slot the run was fired for", () => {+ expect(mrpTick(utc("2026-10-03T08:30:00Z")).toAbsoluteString()).toBe(+ "2026-10-03T08:30:00.000Z"+ );+ });++ it("stays on its slot when the run starts late", () => {+ expect(mrpTick(utc("2026-10-03T08:43:59Z")).toAbsoluteString()).toBe(+ "2026-10-03T08:30:00.000Z"+ );+ });++ it("stays on its slot when the run fires a moment early", () => {+ expect(mrpTick(utc("2026-10-03T08:29:59.800Z")).toAbsoluteString()).toBe(+ "2026-10-03T08:30:00.000Z"+ );+ });+});++describe("isMrpDue with no run time set", () => {+ it("runs every 3 hours, on the hour, in UTC", () => {+ expect(+ dueTicks("2026-10-03", { timezone: "Asia/Kolkata", mrpRunTime: null })+ ).toEqual([+ "00:00",+ "03:00",+ "06:00",+ "09:00",+ "12:00",+ "15:00",+ "18:00",+ "21:00"+ ]);+ });+});++describe("isMrpDue with a run time set", () => {+ it("runs once a day at that time on the company's clock", () => {+ // 2 pm in India is 08:30 UTC — and the 3-hourly runs are gone.+ expect(+ dueTicks("2026-10-03", {+ timezone: "Asia/Kolkata",+ mrpRunTime: "14:00:00"+ })+ ).toEqual(["08:30"]);+ });++ it("follows the company's clock across daylight saving", () => {+ const chicago = { timezone: "America/Chicago", mrpRunTime: "03:00:00" };+ expect(dueTicks("2026-01-15", chicago)).toEqual(["09:00"]);+ expect(dueTicks("2026-07-15", chicago)).toEqual(["08:00"]);+ });++ it("runs on the first tick after a time that is not on a tick", () => {+ expect(+ dueTicks("2026-10-03", { timezone: "UTC", mrpRunTime: "14:07:00" })+ ).toEqual(["14:15"]);+ });++ it("runs just after midnight for a time late in the last tick of the day", () => {+ // 23:50 on Oct 2 is first reached by the 00:00 tick of Oct 3.+ const schedule = { timezone: "UTC", mrpRunTime: "23:50:00" };+ expect(dueTicks("2026-10-03", schedule)).toEqual(["00:00"]);+ });++ it("runs in a zone whose offset is not a whole hour", () => {+ // Kathmandu is UTC+5:45, so 01:00 there is 19:15 UTC the day before.+ expect(+ dueTicks("2026-10-03", {+ timezone: "Asia/Kathmandu",+ mrpRunTime: "01:00:00"+ })+ ).toEqual(["19:15"]);+ });++ it("still runs once on the day the clocks skip the run time", () => {+ // New York, 2026-03-08: 02:00 jumps to 03:00, so 02:30 never happens.+ // The run moves to 03:30 local (07:30 UTC) instead of being skipped.+ expect(+ dueTicks("2026-03-08", {+ timezone: "America/New_York",+ mrpRunTime: "02:30:00"+ })+ ).toEqual(["07:30"]);+ });++ it("runs once on the day the clocks repeat the run time", () => {+ // New York, 2026-11-01: 01:30 happens twice (05:30 and 06:30 UTC).+ expect(+ dueTicks("2026-11-01", {+ timezone: "America/New_York",+ mrpRunTime: "01:30:00"+ })+ ).toEqual(["05:30"]);+ });++ it("accepts a time without seconds", () => {+ expect(+ dueTicks("2026-10-03", { timezone: "UTC", mrpRunTime: "14:00" })+ ).toEqual(["14:00"]);+ });+});diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.tsindex 924a61548d..ecfd6b9c8b 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts@@ -3,8 +3,71 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { filterEmpty } from "@carbon/utils";+import {+ parseTime,+ toCalendarDate,+ toCalendarDateTime,+ toTimeZone,+ toZoned,+ type ZonedDateTime+} from "@internationalized/date";import type { JobDatabase } from "../../../db";+/** How often the scheduled function fires. Keep in step with its cron. */+export const MRP_TICK_MINUTES = 15;++/** The cadence of a company that has set no run time: every N hours, UTC. */+const MRP_DEFAULT_INTERVAL_HOURS = 3;++/**+ * The cron slot a run belongs to: its start time floored to the tick, in UTC.+ * A run that starts late (a retry, a queue) still answers for its own slot.+ * The one-minute lead absorbs a cron that fires a moment before the boundary,+ * which would otherwise floor into the previous slot and skip this one.+ */+export function mrpTick(instant: ZonedDateTime): ZonedDateTime {+ const utc = toTimeZone(instant, "UTC").add({ minutes: 1 });+ return utc.set({+ minute: utc.minute - (utc.minute % MRP_TICK_MINUTES),+ second: 0,+ millisecond: 0+ });+}++/**+ * Whether a scheduled tick should plan for a company.+ *+ * `mrpRunTime` (companySettings, a wall-clock "HH:MM:SS") is the company's+ * chosen time of day on its own clock (`company.timezone`). With none set the+ * company keeps the default cadence, every 3 hours. With one set it runs once+ * a day instead, on the first tick at or after that time.+ *+ * "First tick at or after" is tested against the run time's INSTANT rather+ * than by comparing local hours, so a day whose clocks skip the run time+ * (spring forward) still runs — at the moment the skipped time resolves to —+ * and a day that repeats it (fall back) runs once, not twice. Yesterday's run+ * time is checked too: one set late in the day's last tick is first reached+ * just after midnight.+ */+export function isMrpDue(+ tick: ZonedDateTime,+ schedule: { timezone: string; mrpRunTime: string | null }+): boolean {+ if (!schedule.mrpRunTime) {+ return tick.minute === 0 && tick.hour % MRP_DEFAULT_INTERVAL_HOURS === 0;+ }++ const runTime = parseTime(schedule.mrpRunTime);+ const today = toCalendarDate(toTimeZone(tick, schedule.timezone));++ return [today, today.subtract({ days: 1 })].some((date) => {+ const sinceRunTime = tick.compare(+ toZoned(toCalendarDateTime(date, runTime), schedule.timezone)+ );+ return sinceRunTime >= 0 && sinceRunTime < MRP_TICK_MINUTES * 60 * 1000;+ });+}+/*** Which companies a scheduled MRP run should plan for. A company with no* `companyPlan` row still runs — MRP is not a paid feature.@@ -38,12 +101,22 @@ export function selectCompaniesForMrp<T extends { id: string }>(/*** The companies a run can change anything for: open demand or supply to plan,- * or rows an earlier run wrote that a new one would clear. For every other- * company `runMrp` reads its inputs, finds nothing and rewrites nothing, which- * was 93% of scheduled runs and the largest share of server time (2026-10-01- * traces). Each source is a superset of what `runMrp` reads (projections and- * actuals are not narrowed to the planning horizon), so a company is only left- * out when a run would be a no-op.+ * stock a reorder policy would replenish with no document behind it, or rows+ * an earlier run wrote that a new one would clear. For every other company+ * `runMrp` reads its inputs, finds nothing and rewrites nothing, which was 93%+ * of scheduled runs and the largest share of server time (2026-10-01 traces).+ * Each source is a superset of what `runMrp` reads (projections and actuals+ * are not narrowed to the planning horizon), so a company is only left out+ * when a run would be a no-op.+ *+ * With no demand and no supply, the planning actions still size an Order /+ * Make from on-hand alone (`generatePlanningActions`: the shared sizing, and+ * the Stock Only reserve), and each of those fires only below a positive+ * floor or on negative stock: a Demand-Based Reorder item under its safety+ * stock, a Fixed Reorder Quantity / Maximum Quantity item under its reorder+ * point, a superseded item under its minimum reserve — or any policy but+ * Manual Reorder below zero. Those are the last two sources. "Not Manual+ * Reorder" alone is no filter: it is the column's default.*/export async function companiesWithPlanningWork(db: JobDatabase@@ -57,6 +130,9 @@ export async function companiesWithPlanningWork(.union(db.selectFrom("demandProjection").select("companyId")).union(db.selectFrom("demandForecastSource").select("companyId")).union(db.selectFrom("supplyForecast").select("companyId"))+ // A run clears the worklist of a company whose demand is gone; without+ // this a company with no other planning work keeps its stale actions.+ .union(db.selectFrom("planningAction").select("companyId")).union(db.selectFrom("demandForecast")@@ -75,6 +151,34 @@ export async function companiesWithPlanningWork(.select("companyId").where("actualQuantity", "!=", 0))+ .union(+ db+ .selectFrom("itemPlanning")+ .select("companyId")+ .where((eb) =>+ eb.or([+ // the Stock Only reserve applies whatever the policy+ eb("minimumReserveQuantity", ">", 0),+ eb.and([+ eb("reorderingPolicy", "=", "Demand-Based Reorder"),+ eb("demandAccumulationSafetyStock", ">", 0)+ ]),+ eb.and([+ eb("reorderingPolicy", "in", [+ "Fixed Reorder Quantity",+ "Maximum Quantity"+ ]),+ eb("reorderPoint", ">", 0)+ ])+ ])+ )+ )+ .union(+ db+ .selectFrom("itemStockQuantities")+ .select("companyId")+ .where("quantityOnHand", "<", 0)+ ).execute();return new Set(filterEmpty(rows.map((row) => row.companyId)));diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp.ts b/packages/jobs/src/inngest/functions/scheduled/mrp.tsindex cb23f478c9..c0b9e99241 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp.ts@@ -6,32 +6,66 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { fetchAllFromTable } from "@carbon/database";import { runMrp } from "@carbon/planning";import { Edition } from "@carbon/utils";+import { fromAbsolute, now } from "@internationalized/date";import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";import {companiesWithPlanningWork,+ isMrpDue,+ mrpTick,selectCompaniesForMrp} from "./mrp-companies";export const mrpFunction = inngest.createFunction({ id: "mrp", retries: 2 },- { cron: "0 */3 * * *" },- async ({ step, logger }) => {+ // Every MRP_TICK_MINUTES (mrp-companies.ts). Most ticks plan for nobody: a+ // company is due every 3 hours, or once a day at the time it set in+ // Settings → Planning (`companySettings.mrpRunTime`) — see `isMrpDue`.+ { cron: "*/15 * * * *" },+ async ({ event, step, logger }) => {const serviceRole = getCarbonServiceRole();const scheduled = await step.run("find-companies", async () => {- logger.info(- `Scheduled MRP Calculation Started: ${new Date().toISOString()}`+ // The slot this run was fired for. `event.ts` is the cron's own+ // timestamp and does not move on a retry; the clock is the fallback.+ const tick = mrpTick(+ event.ts === undefined ? now("UTC") : fromAbsolute(event.ts, "UTC"));+ // Only the companies that chose a time; everyone else is on the default.+ const runTimes = await fetchAllFromTable<{+ id: string;+ mrpRunTime: string;+ }>(serviceRole, "companySettings", "id, mrpRunTime", (query) =>+ query.not("mrpRunTime", "is", null).order("id")+ );++ if (runTimes.error) {+ // Throwing, not defaulting: without the run times every company looks+ // like it is on the 3-hour cadence, so a company that set a time would+ // be planned at the wrong hours and skipped at its own.+ logger.error("Failed to get MRP run times", { error: runTimes.error });+ throw runTimes.error;+ }++ // Most ticks fall between the 3-hourly runs, and with no company on a+ // daily time nobody can be due: stop before reading every company.+ if (+ runTimes.data.length === 0 &&+ !isMrpDue(tick, { timezone: "UTC", mrpRunTime: null })+ ) {+ return [];+ }+// Enumerate `company`, never `companyPlan` — that billing table is empty// on every install where nobody completed Stripe checkout, and MRP// silently never ran there. Paged, because max_rows would truncate the// work list the same silent way.- const companies = await fetchAllFromTable<{ id: string; name: string }>(- serviceRole,- "company",- "id, name",- (query) => query.order("id")+ const companies = await fetchAllFromTable<{+ id: string;+ name: string;+ timezone: string;+ }>(serviceRole, "company", "id, name, timezone", (query) =>+ query.order("id"));if (companies.error) {@@ -41,6 +75,42 @@ export const mrpFunction = inngest.createFunction(throw companies.error;}+ if (companies.data.length === 0) {+ // This read runs only on a 3-hourly tick or when a company set a time,+ // so an empty result is a broken work list, not a quiet tick. It is+ // how MRP once never ran on self-hosted installs, behind a green run.+ logger.warn("No companies found to plan for", {+ tick: tick.toAbsoluteString()+ });+ return [];+ }++ const runTimeByCompany = new Map(+ runTimes.data.map((row) => [row.id, row.mrpRunTime])+ );+ const due = companies.data.filter((company) => {+ const mrpRunTime = runTimeByCompany.get(company.id) ?? null;+ try {+ return isMrpDue(tick, { timezone: company.timezone, mrpRunTime });+ } catch (error) {+ // An unreadable timezone or time must not cost the company its+ // planning, or every other company this tick: use the default.+ logger.error("Invalid MRP schedule for company {companyName}", {+ companyName: company.name,+ error,+ timezone: company.timezone,+ mrpRunTime+ });+ return isMrpDue(tick, { timezone: "UTC", mrpRunTime: null });+ }+ });++ if (due.length === 0) {+ // A tick between the 3-hourly runs that is nobody's daily time. Not a+ // warning, and not worth the plan and planning-work lookups below.+ return [];+ }+// Cloud only: a cancelled subscription means the weekly job is about to// delete the company. MRP is not a paid feature anywhere else.let plans:@@ -75,19 +145,18 @@ export const mrpFunction = inngest.createFunction(return null;});- const scheduled = selectCompaniesForMrp(- companies.data,- plans,- withPlanningWork- );+ const scheduled = selectCompaniesForMrp(due, plans, withPlanningWork);logger.info("Companies scheduled for MRP", {+ tick: tick.toAbsoluteString(),companies: companies.data.length,+ due: due.length,scheduled: scheduled.length});if (scheduled.length === 0) {logger.warn("No companies to run MRP for", {- companies: companies.data.length+ companies: companies.data.length,+ due: due.length});}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 5370f78010..2b21a836e0 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# Zeile verweist auf Daten außerhalb dieses Unternehmemsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# Zeile verweist auf Daten außerhalb dieses Unternehmens, daher kann sie nicht gesichert werden. Wenn Sie sie überspringen, wird alles andere gesichert.} other {# Zeilen verweisen auf Daten außerhalb dieses Unternehmens, daher können sie nicht gesichert werden. Wenn Sie sie überspringen, wird alles andere gesichert.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# Woche} other {# Wochen}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {Der Planer behandelt diese Komponente als einen starren Körper – einen Schritt in der Anleitung. Führen Sie den Plan erneut aus, um dies anzuwenden.} other {Der Planer behandelt diese # Komponenten als einen starren Körper – einen Schritt in der Anleitung. Führen Sie den Plan erneut aus, um dies anzuwenden.}}"@@ -107,6 +111,10 @@ msgstr "{0} kann nicht gelöscht werden, da es noch verwendet wird von: {where}.msgid "{0} cells with deltas"msgstr "{0} Zellen mit Deltas"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} verbraucht"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} Werte"msgid "{0} values missing"msgstr "{0} Werte fehlen"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} wird als {name} gespeichert"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# Konto mit einem Saldo} other {# Konten mit Saldenmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# Kurs} other {# Kurse}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# weitere nach {fenceLabel}} other {# weitere nach {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# Los auflösen} other {# Lose auflösen}}"@@ -340,6 +356,9 @@ msgstr "{days}T"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo} bucht dies in Ihr Ledger, daher schiebt Carbon es nicht. Ihre gespeicherte Auswahl wird beibehalten, falls sich dies ändert."+msgid "{dismissed} dismissed"+msgstr "{dismissed} zurückgewiesen"+msgid "{done} of {total} phases complete"msgstr "{done} von {total} Phasen abgeschlossen"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} weitere: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} eingefügt, {updated} aktualisiert, {0} benötigen Behebung, {1} übersprungen."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# Tag} other {# Tage}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# Zeile} other {# Zeilen}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# Phase verbleibend} other {# Phasen verbleibenmsgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} Ressourcen · {reservationCount} Reservierungen · {jobCount} Fertigungsaufträge"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} Berechtigungen"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Ordnen Sie zunächst das # verbleibmsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} können nicht eingeplant werden"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} Fertigungsaufträge aktualisiert"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} hochgeladen — Felder wurden aus dem Dokument ausgefüllt."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 Arbeitsgänge"+msgid "0 suggests a move for any date difference."+msgstr "0 schlägt das Umlagern für jeden Datumsunterschied vor."+msgid "0-4 weeks"msgstr "0-4 Wochen"@@ -518,9 +543,6 @@ msgstr "1 Entwurfs-Buchungszeile"msgid "1 job created"msgstr "1 Auftrag erstellt"-msgid "1 job updated"-msgstr "1 Auftrag aktualisiert"-msgid "1 part skipped — it already has an open job"msgstr "1 Teil übersprungen — es hat bereits einen offenen Auftrag"@@ -530,6 +552,9 @@ msgstr "1 Teil übersprungen — es gibt nichts zu produzieren"msgid "1 problem — not published"msgstr "1 Problem — nicht veröffentlicht"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Einkauf = {conversionFactor} Bestände"+msgid "1 suggested batch"msgstr "1 empfohlenes Los"@@ -542,6 +567,9 @@ msgstr "12 monatliche Perioden"msgid "13+ weeks"msgstr "13+ Wochen"+msgid "1st Negative On Hand"+msgstr "1. Negativer Bestand"+msgid "1Y"msgstr "1 Jahr"@@ -1082,6 +1110,9 @@ msgstr "Ein Schritt benötigt einen Namen."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Eine gespeicherte Buchung eines Arbeitsplatzes oder Werkers für den zeitlichen Umfang eines plazierten Arbeitsgangs — die materialisierte Ausgabe eines Planungslaufs und das, was die Prognose zeichnet."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Ein Vorschlag, den MRP nach jedem Durchlauf erstellt: Neue Deckung bestellen oder Eigenfertigung durchführen, oder eine offene Bestellungsposition oder einen Fertigungsauftrag vorziehen, verschieben, erhöhen, verringern oder abbrechen. Wenden Sie ihn von der Planungsseite an, verwerfen Sie ihn oder weisen Sie ihn zu."+msgid "A supplier contact and location are optional"msgstr "Ein Lieferantenkontakt und ein Standort sind optional"@@ -2006,6 +2037,12 @@ msgstr "Ein Arbeitsgang dieses Auftrags läuft in diesem Batch"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "Die Position eines Arbeitsgangs in der Warteschlange seines Arbeitsplatzes — die Reihenfolge, in der die Fertigung die Arbeit aufnimmt. Die Engine nummeriert sie nach Platzierungsreihenfolge (frühester prognostizierter Start zuerst); das Neuordnen von Karten auf der Arbeitsplatz-Tafel setzt sie außer Kraft, ohne die Daten zu ändern."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Ein unerwarteter Fehler ist beim Verbinden mit Onshape aufgetreten. Speichern Sie die Integrationseinstellungen, um es erneut zu versuchen."@@ -2167,6 +2204,9 @@ msgstr "Preisregeln anwenden"msgid "Apply Rules On Top"msgstr "Wenden Sie Regeln Oben An"+msgid "Apply Suggested Changes"+msgstr "Vorgeschlagene Änderungen anwenden"+msgid "Apply suggestions"msgstr "Vorschläge anwenden"@@ -2824,6 +2864,9 @@ msgstr "Zuweisen an"msgid "Assign to Groups"msgstr "Gruppen zuweisen"+msgid "Assign to Me"+msgstr "Mir zuweisen"+msgid "Assigned"msgstr "Zugewiesen"@@ -2836,6 +2879,9 @@ msgstr "Mir zugewiesen"msgid "Assignee"msgstr "Bearbeiter"+msgid "Assignees"+msgstr "Bearbeiter"+msgid "Assignment"msgstr "Aufgabe"@@ -3491,12 +3537,18 @@ msgstr "Änderungsmitteilung abbrechen"msgid "Cancel Job"msgstr "Auftrag abbrechen"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Auftrag stornieren"msgid "Cancel Purchase Order"msgstr "Bestellung stornieren"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Rückgabe stornieren"@@ -3548,6 +3600,12 @@ msgstr "Kann nicht in den Teile-Bucket ohne Element-ID verschoben werden"msgid "Cannot place order - no supplier associated with this item"msgstr "Bestellung kann nicht aufgegeben werden - kein Lieferant mit diesem Artikel verknüpft"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Bestellung nicht möglich — {count} Artikel haben keinen Lieferanten"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Bestellung nicht möglich — 1 Artikel hat keinen Lieferanten"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Kann nicht buchen – Lieferung enthält abgelaufene verfolgte Entitäten."@@ -3753,6 +3811,9 @@ msgstr "Typ ändern"msgid "Changed By"msgstr "Geändert von"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Nur für diese Ansicht geändert. Der Planungshorizont des Artikels wird nicht aktualisiert."+msgid "Changelog"msgstr "Änderungslog"@@ -3853,6 +3914,9 @@ msgstr "Wählen Sie, wie Sie Positionen zu dieser Rückgabe hinzufügen möchtenmsgid "Choose what appears on the printed job traveler."msgstr "Wählen Sie, was auf der gedruckten Laufkarte erscheint."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Legen Sie fest, wann MRP automatisch neu berechnet wird. Sie können es jederzeit auf den Planungsseiten mit „Neu berechnen“ selbst erneut ausführen."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Wählen Sie, ob der Bill-of-Material-Explorer auf Artikeln, Angeboten und Fertigungsaufträgen jede Position mit ihrer Beschreibung oder ihrer Artikel-ID beschriftet."@@ -4068,6 +4132,9 @@ msgstr "Unternehmen"msgid "Company"msgstr "Unternehmen"+msgid "Company default"+msgstr "Unternehmensstandard"+msgid "Company group"msgstr "Unternehmensgruppe"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Dokument konnte nicht gelesen werden: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Konnte {0} nicht freigeben: {1}"@@ -5093,6 +5162,9 @@ msgstr "Abteilung erstellt"msgid "Created failure mode"msgstr "Fehlermodus erstellt"+msgid "Created from planning"+msgstr "Aus der Planung erstellt"+msgid "Created gauge type"msgstr "Prüfmittelart erstellt"@@ -5671,6 +5743,15 @@ msgstr "Dezimalstellen"msgid "Declining balance"msgstr "Degressive Abschreibung"+msgid "Decrease"+msgstr "Verringern"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Tief in der Nacht, {name}."@@ -5737,6 +5818,9 @@ msgstr "Standard-Aufwandskonto für Instandhaltung von Anlagen und Einrichtungenmsgid "Default GL expense account for periodic depreciation runs."msgstr "Standard-Aufwandskonto für regelmäßige Abschreibungsläufe."+msgid "Default horizon (days)"+msgstr "Standard-Horizont (Tage)"+msgid "Default Method"msgstr "Standardmethode"@@ -5788,6 +5872,15 @@ msgstr "Standard-Nutzungsdauer, die in dieser Klasse auf neuen Vermögenswertenmsgid "Defaults"msgstr "Standardwerte"+msgid "Defer"+msgstr "Verschieben"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Latente Steueraufwendungen"@@ -6368,6 +6461,9 @@ msgstr "Entdeckung"msgid "Dismiss"msgstr "Verwerfen"+msgid "Dismissed"+msgstr "Zurückgewiesen"+msgid "Dispatch"msgstr "Instandhaltungsauftrag"@@ -6744,6 +6840,9 @@ msgstr "Die Fremdarbeitsgänge jedes Lieferanten aus jedem Fertigungsauftrag wermsgid "Each, lb, ft…"msgstr "Stück, kg, m…"+msgid "Earlier weeks are consumed first."+msgstr "Frühere Wochen werden zuerst verbraucht."+msgid "Earliest operation start"msgstr "Frühestmöglicher Operationsbeginn"@@ -7503,6 +7602,9 @@ msgstr "Ereignistyp"msgid "Events"msgstr "Ereignisse"+msgid "Every 3 hours"+msgstr "Alle 3 Stunden"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Alle unternehmensbezogenen Datensätze. Zugangsdaten, Integrations-Tokens und Webhooks sind nie enthalten."@@ -7635,6 +7737,15 @@ msgstr "Erwarteter Eingang"msgid "Expected Receipt Date"msgstr "Erwartetes Eingangsdatum"+msgid "Expedite"+msgstr "Beschleunigen"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Aufwandskonto für Kundensalden, die beim Debitoren-Abgleich als uneinbringlich abgeschrieben werden"@@ -8112,12 +8223,18 @@ msgstr "Fehler beim Aktualisieren der Inventur"msgid "Failed to update item cost"msgstr "Fehler beim Aktualisieren der Artikelkosten"+msgid "Failed to update job"+msgstr "Fertigungsauftrag konnte nicht aktualisiert werden"+msgid "Failed to update lead times"msgstr "Aktualisierung der Beschaffungszeiten fehlgeschlagen"msgid "Failed to update opportunity with purchase order"msgstr "Verkaufschance konnte nicht mit Bestellung aktualisiert werden"+msgid "Failed to update purchase order line"+msgstr "Bestellposition konnte nicht aktualisiert werden"+msgid "Failed to update quote line"msgstr "Angebotsposition konnte nicht aktualisiert werden"@@ -8315,6 +8432,9 @@ msgstr "Vorname"msgid "First Operation"msgstr "Erste Operation"+msgid "First week the projected stock goes below zero"+msgstr "Erste Woche, in der der prognostizierte Bestand unter Null fällt"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Anlage"@@ -8381,6 +8501,12 @@ msgstr "für alles. Sie werden die richtige Person hinzuziehen."msgid "Forecast"msgstr "Prognose"+msgid "Forecast consumption"+msgstr "Prognose-Verbrauch"++msgid "Forecast Consumption"+msgstr "Prognose-Verbrauch"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Prognosemethode: <0>{0}</0>. Diese Zeile wurde nicht von laufenden Fertigungsaufträgen abgeleitet, daher sind keine übergeordneten Quellen verfügbar."@@ -8829,8 +8955,8 @@ msgstr "Hat Arbeitsgänge, die nicht eingeplant werden können"msgid "Headers"msgstr "Header"-msgid "healthy"-msgstr "fehlerfrei"+msgid "Healthy"+msgstr "Fehlerfrei"msgid "Help"msgstr "Hilfe"@@ -8979,6 +9105,9 @@ msgstr "Wie viele Tage nach dem Berechnungsdatum der Frühzahlungsrabatt noch vemsgid "How many days after the calculation date the full amount is due."msgstr "Wie viele Tage nach dem Berechnungsdatum der volle Betrag fällig ist."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Die Anzahl der Tage, um die eine offene Bestellung vom benötigten Datum abweichen darf, bevor MRP eine Verschiebung vorschlägt. Eingestellt unter Einstellungen → Planung; Standard: 7 Tage."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Wie viele Tage ab dem Rechnungsdatum dieser Kunde zum Zahlen bekommt; bestimmt das Standard-Fälligkeitsdatum auf Kundenrechnungen."@@ -9253,6 +9382,9 @@ msgstr "In diesem Schritt"msgid "In use"msgstr "In Gebrauch"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "In der Zeitzone Ihres Unternehmens ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "Bearbeiten Sie in Ihren Enterprise-Einstellungen unter Developer die Berechtigungen der privaten OAuth-Anwendung, um „Application can write to your documents\" einzuschließen, dann speichern Sie die Integrationseinstellungen erneut."@@ -9265,9 +9397,6 @@ msgstr "In-App-Benachrichtigungen werden immer zugestellt. Wählen Sie, welche Tmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "In-App-Benachrichtigungen werden immer zugestellt. Wählen Sie, welche Themen Sie auch per E-Mail erreichen."-msgid "inactive"-msgstr "inaktiv"-msgid "Inactive"msgstr "Inaktiv"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Incoterm-Ort"+msgid "Increase"+msgstr "Erhöhen"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Indirekt"@@ -9364,6 +9502,9 @@ msgstr "Geerbt aus der Gruppe: ob dieses Konto zum Gewinnvortrag (Erträge) gescmsgid "Inherited from the parent group."msgstr "Geerbt aus der übergeordneten Gruppe."+msgid "inherits {inheritedName}"+msgstr "erbt {inheritedName}"+msgid "Input"msgstr "Eingabe"@@ -9893,6 +10034,9 @@ msgstr "Auftragspriorität"msgid "Job readable"msgstr "Auftrag lesbar"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Fertigungsauftrag-Laufkarte"@@ -10108,9 +10252,15 @@ msgstr "Zuletzt verwendet"msgid "Late in the evening, {name}."msgstr "Spät am Abend, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Spätere Wochen werden verbraucht, sobald frühere aufgebraucht sind."+msgid "Latest operation end"msgstr "Ende der neuesten Operation"+msgid "Latest Order Date"+msgstr "Spätestes Bestelldatum"+msgid "Latitude"msgstr "Breitengrad"@@ -10153,6 +10303,9 @@ msgstr "Lassen Sie das Feld leer, um die nächste Revision automatisch zu verwenmsgid "Leave empty for exact match"msgstr "Leer lassen für exakte Übereinstimmung"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Leer lassen oder 0 eingeben, um alles anzuzeigen, das MRP plant."+msgid "Leave this page"msgstr "Diese Seite verlassen"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Zeilen"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Positionen erscheinen hier, nachdem ein Wareneingang aus einer Bestellung gebucht wurde, und nur für Mengen, die nicht bereits für eine andere Lieferantenrückgabe genehmigt wurden. Verwenden Sie Hinzufügen für eine blinde Rückgabe."+msgstr "Positionen erscheinen hier, sobald ein Bestellungs-Wareneingang gebucht wurde, und nur für Mengen, die nicht bereits für eine andere Lieferantenrückgabe genehmigt wurden. Verwenden Sie „Artikel hinzufügen\" für eine Blindrückgabe."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Positionen erscheinen hier, nachdem eine Lieferung eines Kundenauftrags gebucht wurde, und nur für Mengen, die nicht bereits durch ein anderes RMA autorisiert wurden. Verwenden Sie Position hinzufügen für blinde Rückgaben."@@ -10441,6 +10594,12 @@ msgstr "Lange Beschreibung"msgid "Longitude"msgstr "Längengrad"+msgid "Look ahead (weeks)"+msgstr "Vorausschau (Wochen)"++msgid "Look back (weeks)"+msgstr "Rückblick (Wochen)"+msgid "Looks empty here"msgstr "Sieht hier leer aus"@@ -10570,6 +10729,12 @@ msgstr "Instandhaltungstyp"msgid "Make"msgstr "Herstellen"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "{quantity} herstellen"+msgid "Make Active"msgstr "Aktivieren"@@ -10847,6 +11012,9 @@ msgstr "Werkstoff-Artikel"msgid "Material Planning"msgstr "Materialplanung"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "Die Materialplanung zeigt nur die Maßnahmen und vorgeschlagenen Bestellungen an, die innerhalb dieser Anzahl von Tagen ab heute fällig werden, damit entfernte Anforderungen bis zu ihrer Relevanz außer Sicht bleiben. Der eigene Planungshorizont eines Artikels setzt diesen Standard außer Kraft."+msgid "Material Properties"msgstr "Materialeigenschaften"@@ -11231,6 +11399,18 @@ msgstr "MRP (Planung)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP wird automatisch alle 3 Stunden ausgeführt, aber Sie können es hier manuell ausführen."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP wird jeden Tag um {time} ({timeZone}) automatisch ausgeführt, aber Sie können es hier manuell ausführen."++msgid "MRP Schedule"+msgstr "MRP-Terminplan"++msgid "MRP Suggestions"+msgstr "MRP-Vorschläge"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP schlägt das Umlagern einer bestehenden Bestellung nur vor, wenn ihr Datum um mehr als diese Anzahl von Tagen abweicht. Kleinere Abweichungen werden ignoriert, damit die Aufgabenliste ruhig bleibt."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Mehrere Fertigungsaufträge können auf diesem Verfahren gleichzeitig laufen — z. B. Lasertisch, Ofen oder Galvanikbad."@@ -11498,9 +11678,6 @@ msgstr "Neue Zahlungsbedingung"msgid "New Picking List"msgstr "Neue Kommissionierliste"-msgid "New PO"-msgstr "Neue Bestellung"-msgid "New Price Override"msgstr "Neue Preisübersteuerung"@@ -12140,7 +12317,7 @@ msgid "No results found"msgstr "Keine Ergebnisse gefunden"msgid "No returnable lines for this customer"-msgstr "Keine rückgabefähigen Positionen für diesen Kunden"+msgstr "Keine Rückgabepositionen für diesen Kunden"msgid "No returnable lines for this supplier"msgstr "Keine rückgabefähigen Positionen für diesen Lieferanten"@@ -12205,6 +12382,9 @@ msgstr "Keine Lagereinheit"msgid "No storage units or tracking numbers match."msgstr "Keine Lagereinheiten oder Verfolgungsnummern stimmen überein."+msgid "No Supplier"+msgstr "Kein Lieferant"+msgid "No suppliers yet"msgstr "Noch keine Lieferanten"@@ -12555,6 +12735,9 @@ msgstr "Pünktliche Lieferung"msgid "Onboard your agent to Carbon"msgstr "Ihren Agenten bei Carbon registrieren"+msgid "Once a day"+msgstr "Einmal täglich"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Offener Fertigungsauftrag-Bedarf plus ausstehende Umlagerungen aus diesemsgid "Open jobs"msgstr "Offene Fertigungsaufträge"+msgid "Open Jobs"+msgstr "Offene Fertigungsaufträge"+msgid "Open menu"msgstr "Menü öffnen"msgid "Open navigation"msgstr "Navigation öffnen"+msgid "Open Orders"+msgstr "Offene Bestellungen"+msgid "Open payables by supplier and age"msgstr "Offene Verbindlichkeiten nach Lieferant und Fälligkeitsdauer"@@ -12932,9 +13121,18 @@ msgstr "{0} × {substitute} für diesen Fertigungsauftrag bestellen"msgid "Order {0} for this job"msgstr "{0} für diesen Auftrag bestellen"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "{quantity} bestellen"+msgid "Order by"msgstr "Bestellung bis"+msgid "Order By"+msgstr "Sortieren nach"+msgid "Order date"msgstr "Bestelldatum"@@ -13091,6 +13289,9 @@ msgstr "Verantwortlicher"msgid "Owner (cost center)"msgstr "Verantwortlicher (Kostenstelle)"+msgid "Ownership"+msgstr "Zuständigkeit"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Verwaltet: {0}"@@ -13569,9 +13770,36 @@ msgstr "Geplante Zeit"msgid "Planning"msgstr "Planung"+msgid "Planning action"+msgstr "Planungsaktion"++msgid "Planning horizon"+msgstr "Planungshorizont"++msgid "Planning Horizon"+msgstr "Planungshorizont"++msgid "Planning Horizon (Days)"+msgstr "Planungshorizont (Tage)"++msgid "Planning Horizon:"+msgstr "Planungshorizont:"++msgid "Planning Ownership"+msgstr "Planungseigentümer"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Planungsrunden schlugen eine Auffüllung bis zu einem ganzen Vielfachen dieser Zahl vor."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "Die Planung zeigt nur die Maßnahmen und vorgeschlagenen Bestellungen an, die innerhalb dieser Anzahl von Tagen fällig werden. Leer lassen, um den Standard des Unternehmens zu verwenden, oder 0 eingeben, um alles für diesen Artikel anzuzeigen."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Untere Grenze der Planung für eine vorgeschlagene Auffüllungsmenge; unterscheidet sich vom MOQ des Lieferanten, der im Datensatz des Lieferanten-Teils lebt."@@ -13980,6 +14208,9 @@ msgstr "Projektplan"msgid "Project start"msgstr "Projektstart"+msgid "Projected"+msgstr "Prognostiziert"+msgid "Projected completion"msgstr "Geplante Fertigstellung"@@ -14001,6 +14232,12 @@ msgstr "Geplante Lagerbestandserschöpfung in der Woche vom {0}"msgid "Projected stock"msgstr "Geplanter Bestand"+msgid "Projected stock by week"+msgstr "Prognostizierter Bestand pro Woche"++msgid "Projected stock is already below zero this week"+msgstr "Der prognostizierte Bestand liegt bereits unter Null diese Woche"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Erwarteter Fehlbestand in der Woche von {0}"@@ -14139,6 +14376,9 @@ msgstr "Bestellung"msgid "Purchase Order Amount"msgstr "Bestellmenge"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Genehmigungsregel für Bestellung"@@ -14166,6 +14406,9 @@ msgstr "Bestellungen"msgid "Purchase Orders and Planning"msgstr "Bestellungen und Planung"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Bestellungen erforderlich"@@ -14272,9 +14515,6 @@ msgstr "Menge"msgid "Qty On Hand"msgstr "Bestandsmenge"-msgid "Qty to Order"-msgstr "Bestellmenge"-msgid "Qty. Complete"msgstr "Menge abgeschlossen"@@ -14568,6 +14808,9 @@ msgstr "Angebotsbereit"msgid "ready to keep or revert"msgstr "bereit zum Behalten oder Zurücksetzen"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Kundenaufträge verbrauchen zunächst die Bedarfsprognose ihrer Woche, dann frühere und spätere Wochen im Fenster des Unternehmens. Daher werden Prognose- und tatsächlicher Bedarf nie beide für dieselben Einheiten eingeplant."+msgid "Real-time inventory and shop-floor visibility"msgstr "Echtzeit-Bestandsverwaltung und Shopfloor-Sichtbarkeit"@@ -14880,9 +15123,15 @@ msgstr "Freigabenkontrolle"msgid "Release Job"msgstr "Auftrag freigeben"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Fertigungsaufträge freigeben"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Freigegeben"@@ -15034,6 +15283,9 @@ msgstr "Label-Vorschau wird gerendert..."msgid "Reopen"msgstr "Wieder öffnen"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Neu anordnen"@@ -15221,6 +15473,12 @@ msgstr "Reparatur erforderlich"msgid "Requires staffing"msgstr "Erfordert Personal"+msgid "Reschedule tolerance"+msgstr "Verschiebungstoleranz"++msgid "Reschedule Tolerance"+msgstr "Umplanungstoleranz"+msgid "Reserve floor"msgstr "Reservemindestbestand"@@ -15279,6 +15537,12 @@ msgstr "Ressourcen"msgid "Resources"msgstr "Ressourcen"+msgid "Responsible employee"+msgstr "Verantwortlicher Mitarbeiter"++msgid "Responsible Employee"+msgstr "Verantwortlicher Mitarbeiter"+msgid "Restock"msgstr "Wiederauffüllung"@@ -15654,6 +15918,9 @@ msgstr "Durchlauf-ID"msgid "Run month-end close and standard reconciliations"msgstr "Monatsabschluss durchführen und standardmäßige Abstimmungen durchführen"+msgid "Run MRP"+msgstr "MRP ausführen"+msgid "Run payment batches and track aging"msgstr "Zahlungschargen ausführen und Fälligkeitsanalyse verfolgen"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "Arbeitsgänge wählen"msgid "Select posted receipt lines from this supplier to return."-msgstr "Wählen Sie gebuchte Wareneingangspositionen von diesem Lieferant aus, um sie zurückzusenden."+msgstr "Wählen Sie gebuchte Wareneingangspositionen von diesem Lieferanten zur Rücksendung aus."msgid "Select posted shipment lines to this customer to return."msgstr "Gebuchte Lieferpositionen an diesen Kunden zur Rückgabe auswählen."@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "Sitzung gesperrt"msgid "Set a customer on this return to add from a shipment."-msgstr "Legen Sie einen Kunden für diese Rückgabe fest, um aus einer Lieferung hinzuzufügen."+msgstr "Legen Sie einen Kunden für diese Rücksendung fest, um aus einer Lieferung hinzuzufügen."msgid "Set a supplier on this return to add from a receipt."msgstr "Wählen Sie einen Lieferanten für diese Rückgabe aus, um Positionen von einem Wareneingang hinzuzufügen."@@ -17243,6 +17510,9 @@ msgstr "Starten"msgid "Start {0} Day Free Trial"msgstr "Starten Sie die {0}-tägige kostenlose Testversion"+msgid "Start By"+msgstr "Starten nach"+msgid "Start counting"msgstr "Zählung starten"@@ -17386,6 +17656,9 @@ msgstr "Schritte werden eigenständig erstellt und dann als ein Stück zusammengmsgid "Still dark out on the floor."msgstr "Es ist noch dunkel auf der Werkstatt."+msgid "Stock Availability"+msgstr "Bestandsverfügbarkeit"+msgid "Stock movement corrected"msgstr "Lagerbewegung korrigiert"@@ -17624,6 +17897,15 @@ msgstr "Abgleich vorschlagen"msgid "Suggest with AI"msgstr "Mit KI vorschlagen"+msgid "Suggested Jobs"+msgstr "Vorgeschlagene Fertigungsaufträge"++msgid "Suggested Orders"+msgstr "Vorgeschlagene Bestellungen"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Vorgeschlagene Bestellungen erforderlich nach dem Planungshorizont dieses Artikels. Erweitern Sie den Horizont, um sie einzuschließen."+msgid "Suggested orders you haven't placed yet."msgstr "Vorgeschlagene Bestellungen, die Sie noch nicht aufgegeben haben."@@ -17874,7 +18156,7 @@ msgstr "Synchronisieren"msgid "Sync Activity"msgstr "Synchronisierungsaktivität"-msgid "sync off"+msgid "Sync Off"msgstr "Synchronisierung aus"msgid "Sync operation"@@ -18642,6 +18924,9 @@ msgstr "Der Prozentsatz des Kassenrabatts. Verwenden Sie 0 für keinen Rabatt."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "Der Berechtigungssatz, den neue Mitarbeiter dieses Typs automatisch erhalten; durch die Bearbeitung hier wird nur die Vorlage für zukünftige Mitarbeiter geändert – vorhandene Mitarbeiter behalten das, was sie haben, es sei denn, es wird explizit in großen Mengen aktualisiert."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "Die Person, der eine Planungsaktion zugewiesen ist: der Verantwortliche des Artikels an diesem Standort, sonst der Verantwortliche der Artikelgruppe, sonst der Verantwortliche des Standorts, sonst der Standard des Unternehmens."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Die Fabriken, Lagerhäuser und Standorte, an denen sich Ihre Arbeit und Bestände befinden"@@ -18663,6 +18948,9 @@ msgstr "Die Verfahren, die dieser Arbeitsplatz ausführen kann; erscheint in Vermsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "Der Provider bietet keine Dimensionsziele. Aktivieren Sie die Funktion zuerst beim Provider (z. B. Tracking-Kategorien, Klassenverfolgung oder Felder)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Die Mengenestaffeln, zu denen diese Position bewertet ist; jede Spalte hat seinen eigenen Stückpreis für Käufer–Lieferant-Verhandlungen und für die Umwandlung in nachgelagerte Dokumente."@@ -18991,6 +19279,9 @@ msgstr "Diese Buchungssätze sind noch Entwurf, sodass ihre Sollposten und Habenmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Diese Arbeitsgänge nutzen ein Verfahren mit mehreren Lieferanten. Wählen Sie für jeden einen Lieferanten."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Diese Bestellungen konnten nicht geladen werden. Schließen und öffnen Sie erneut, um es zu versuchen."+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."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Toleranz (+/-)"+msgid "Tolerance (days)"+msgstr "Toleranz (Tage)"+msgid "Tomorrow"msgstr "Morgen"@@ -19530,7 +19824,7 @@ msgid "Total Hours"msgstr "Gesamtstunden"msgid "Total Indirect Cost"-msgstr "Gesamte indirekte Kosten"+msgstr "Indirekte Gesamtkosten"msgid "Total Material Cost"msgstr "Gesamte Materialkosten"@@ -19847,8 +20141,8 @@ msgstr "Rückgängig machen"msgid "Ungroup"msgstr "Gruppierung aufheben"-msgid "unhealthy"-msgstr "ungesund"+msgid "Unhealthy"+msgstr "Ungesund"msgid "Uninstall"msgstr "Deinstallieren"@@ -20936,6 +21230,9 @@ msgstr "Wenn sich {name} ändert"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Wenn die Haltbarkeit eines Fertigprodukts auf „Berechnet\" eingestellt ist, wählen Sie aus, welche verbrauchten Eingaben die Berechnung speisen."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Wenn ein Kundenauftrag oder Fertigungsauftrag in einer Woche ohne verbleibende Prognose landet, verbraucht er die Prognose aus nahegelegenen Wochen, anstatt hinzugerechnet zu werden. Setzen Sie beide auf 0, um nur innerhalb derselben Woche zu verrechnen."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Wenn ein Serial oder Batch abläuft, und was passiert, wenn er danach verwendet wird — eine Unternehmensrichtlinie kann Warnung, Blockierung oder BlockMitÜberschreitung sein."@@ -21128,6 +21425,9 @@ msgstr "Wer wird auf was und in welchem Format geschult. Ihre Aufgabe: Schützenmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Wer muss Angebote, Bestellungen und Käufe genehmigen – und wann"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Wer ist Eigentümer von MRP-Planungsaktionen. Standorte erben den Unternehmensstandard; Artikelgruppen erben ihren Standort. Die spezifischste Zuweisung gewinnt, und jeder Artikel kann auf seiner Registerkarte „Planung\" eine Übersteuerung vornehmen."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Wer sollte Benachrichtigungen für wartungsbezogene Instandhaltungsaufträge erhalten?"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 1fbf5a1945..b648447191 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# row links to data outside this company, so a safety cmsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# week} other {# weeks}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"@@ -107,6 +111,10 @@ msgstr "{0} cannot be deleted because it is still in use by {where}. Change thosmsgid "{0} cells with deltas"msgstr "{0} cells with deltas"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} consumed"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} values"msgid "{0} values missing"msgstr "{0} values missing"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr "{0} was released with a problem: {1}"+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} will be saved as {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# account with a balance} other {# accounts with amsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# course} other {# courses}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"@@ -340,6 +356,9 @@ msgstr "{days}d"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."+msgid "{dismissed} dismissed"+msgstr "{dismissed} dismissed"+msgid "{done} of {total} phases complete"msgstr "{done} of {total} phases complete"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} more: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# day} other {# days}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# line} other {# lines}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# phase left} other {# phases left}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgid "{scopeCount} permissions"msgstr "{scopeCount} permissions"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Map the # remaining required accounmsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} can't be scheduled"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} jobs updated"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} uploaded — fields filled from the document."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 operations"+msgid "0 suggests a move for any date difference."+msgstr "0 suggests a move for any date difference."+msgid "0-4 weeks"msgstr "0-4 weeks"@@ -518,9 +543,6 @@ msgstr "1 draft journal entry"msgid "1 job created"msgstr "1 job created"-msgid "1 job updated"-msgstr "1 job updated"-msgid "1 part skipped — it already has an open job"msgstr "1 part skipped — it already has an open job"@@ -530,6 +552,9 @@ msgstr "1 part skipped — nothing to make"msgid "1 problem — not published"msgstr "1 problem — not published"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Purchase = {conversionFactor} Inventory"+msgid "1 suggested batch"msgstr "1 suggested batch"@@ -542,6 +567,9 @@ msgstr "12 monthly periods"msgid "13+ weeks"msgstr "13+ weeks"+msgid "1st Negative On Hand"+msgstr "1st Negative On Hand"+msgid "1Y"msgstr "1Y"@@ -1082,6 +1110,9 @@ msgstr "A step needs a name."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgid "A supplier contact and location are optional"msgstr "A supplier contact and location are optional"@@ -2006,6 +2037,12 @@ msgstr "An operation on this job runs in this batch"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr "An order raised from Material Planning follows the same approval rule as any other purchase order."++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."@@ -2167,6 +2204,9 @@ msgstr "Apply pricing rules"msgid "Apply Rules On Top"msgstr "Apply Rules On Top"+msgid "Apply Suggested Changes"+msgstr "Apply Suggested Changes"+msgid "Apply suggestions"msgstr "Apply suggestions"@@ -2824,6 +2864,9 @@ msgstr "Assign To"msgid "Assign to Groups"msgstr "Assign to Groups"+msgid "Assign to Me"+msgstr "Assign to Me"+msgid "Assigned"msgstr "Assigned"@@ -2836,6 +2879,9 @@ msgstr "Assigned to Me"msgid "Assignee"msgstr "Assignee"+msgid "Assignees"+msgstr "Assignees"+msgid "Assignment"msgstr "Assignment"@@ -3491,12 +3537,18 @@ msgstr "Cancel Change Notice"msgid "Cancel Job"msgstr "Cancel Job"+msgid "Cancel job {target}"+msgstr "Cancel job {target}"+msgid "Cancel Order"msgstr "Cancel Order"msgid "Cancel Purchase Order"msgstr "Cancel Purchase Order"+msgid "Cancel purchase order {target}"+msgstr "Cancel purchase order {target}"+msgid "Cancel Return"msgstr "Cancel Return"@@ -3548,6 +3600,12 @@ msgstr "Cannot move to parts bucket without item ID"msgid "Cannot place order - no supplier associated with this item"msgstr "Cannot place order - no supplier associated with this item"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Cannot place the order — {count} items have no supplier"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Cannot place the order — 1 item has no supplier"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Cannot post — shipment contains expired tracked entities."@@ -3753,6 +3811,9 @@ msgstr "Change Type"msgid "Changed By"msgstr "Changed By"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Changed for this view only. The item's planning horizon is not updated."+msgid "Changelog"msgstr "Changelog"@@ -3853,6 +3914,9 @@ msgstr "Choose how to add lines to this return."msgid "Choose what appears on the printed job traveler."msgstr "Choose what appears on the printed job traveler."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."@@ -4068,6 +4132,9 @@ msgstr "Companies"msgid "Company"msgstr "Company"+msgid "Company default"+msgstr "Company default"+msgid "Company group"msgstr "Company group"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Could not read the document: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Could not release {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "Created department"msgid "Created failure mode"msgstr "Created failure mode"+msgid "Created from planning"+msgstr "Created from planning"+msgid "Created gauge type"msgstr "Created gauge type"@@ -5671,6 +5743,15 @@ msgstr "Decimal Places"msgid "Declining balance"msgstr "Declining balance"+msgid "Decrease"+msgstr "Decrease"++msgid "Decrease job {target} to {amount}"+msgstr "Decrease job {target} to {amount}"++msgid "Decrease purchase order {target} to {amount}"+msgstr "Decrease purchase order {target} to {amount}"+msgid "Deep in the small hours, {name}."msgstr "Deep in the small hours, {name}."@@ -5737,6 +5818,9 @@ msgstr "Default GL expense account for equipment and facility maintenance."msgid "Default GL expense account for periodic depreciation runs."msgstr "Default GL expense account for periodic depreciation runs."+msgid "Default horizon (days)"+msgstr "Default horizon (days)"+msgid "Default Method"msgstr "Default Method"@@ -5788,6 +5872,15 @@ msgstr "Default useful life that pre-fills on new assets in this class."msgid "Defaults"msgstr "Defaults"+msgid "Defer"+msgstr "Defer"++msgid "Defer job {target} to {date}"+msgstr "Defer job {target} to {date}"++msgid "Defer purchase order {target} to {date}"+msgstr "Defer purchase order {target} to {date}"+msgid "Deferred Tax Expense"msgstr "Deferred Tax Expense"@@ -6368,6 +6461,9 @@ msgstr "Discovery"msgid "Dismiss"msgstr "Dismiss"+msgid "Dismissed"+msgstr "Dismissed"+msgid "Dispatch"msgstr "Dispatch"@@ -6744,6 +6840,9 @@ msgstr "Each supplier's outside operations from every job go on one new purchasemsgid "Each, lb, ft…"msgstr "Each, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "Earlier weeks are consumed first."+msgid "Earliest operation start"msgstr "Earliest operation start"@@ -7503,6 +7602,9 @@ msgstr "Event Type"msgid "Events"msgstr "Events"+msgid "Every 3 hours"+msgstr "Every 3 hours"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Every company-scoped record. Credentials, integration tokens and webhooks are never included."@@ -7635,6 +7737,15 @@ msgstr "Expected Receipt"msgid "Expected Receipt Date"msgstr "Expected Receipt Date"+msgid "Expedite"+msgstr "Expedite"++msgid "Expedite job {target} to {date}"+msgstr "Expedite job {target} to {date}"++msgid "Expedite purchase order {target} to {date}"+msgstr "Expedite purchase order {target} to {date}"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Expense account for customer balances written off as uncollectable on AR settlement"@@ -8112,12 +8223,18 @@ msgstr "Failed to update count"msgid "Failed to update item cost"msgstr "Failed to update item cost"+msgid "Failed to update job"+msgstr "Failed to update job"+msgid "Failed to update lead times"msgstr "Failed to update lead times"msgid "Failed to update opportunity with purchase order"msgstr "Failed to update opportunity with purchase order"+msgid "Failed to update purchase order line"+msgstr "Failed to update purchase order line"+msgid "Failed to update quote line"msgstr "Failed to update quote line"@@ -8315,6 +8432,9 @@ msgstr "First Name"msgid "First Operation"msgstr "First Operation"+msgid "First week the projected stock goes below zero"+msgstr "First week the projected stock goes below zero"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "First-year additional deduction taken before the regular MACRS schedule begins."@@ -8381,6 +8501,12 @@ msgstr "for anything. They'll pull in the right person."msgid "Forecast"msgstr "Forecast"+msgid "Forecast consumption"+msgstr "Forecast consumption"++msgid "Forecast Consumption"+msgstr "Forecast Consumption"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."@@ -8829,8 +8955,8 @@ msgstr "Has operations that can't be scheduled"msgid "Headers"msgstr "Headers"-msgid "healthy"-msgstr "healthy"+msgid "Healthy"+msgstr "Healthy"msgid "Help"msgstr "Help"@@ -8979,6 +9105,9 @@ msgstr "How many days after the calculation date the early-payment discount is smsgid "How many days after the calculation date the full amount is due."msgstr "How many days after the calculation date the full amount is due."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."@@ -9253,6 +9382,9 @@ msgstr "In this step"msgid "In use"msgstr "In use"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "In your company's time zone ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."@@ -9265,9 +9397,6 @@ msgstr "In-app notifications are always delivered. Choose which topics also reacmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "In-app notifications are always delivered. Choose which topics also reach you by email."-msgid "inactive"-msgstr "inactive"-msgid "Inactive"msgstr "Inactive"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Incoterm Location"+msgid "Increase"+msgstr "Increase"++msgid "Increase job {target} to {amount}"+msgstr "Increase job {target} to {amount}"++msgid "Increase purchase order {target} to {amount}"+msgstr "Increase purchase order {target} to {amount}"+msgid "Indirect"msgstr "Indirect"@@ -9364,6 +9502,9 @@ msgstr "Inherited from the group: whether this account closes to retained earninmsgid "Inherited from the parent group."msgstr "Inherited from the parent group."+msgid "inherits {inheritedName}"+msgstr "inherits {inheritedName}"+msgid "Input"msgstr "Input"@@ -9893,6 +10034,9 @@ msgstr "Job Priority"msgid "Job readable"msgstr "Job readable"+msgid "Job released"+msgstr "Job released"+msgid "Job Traveler"msgstr "Job Traveler"@@ -10108,9 +10252,15 @@ msgstr "Last used"msgid "Late in the evening, {name}."msgstr "Late in the evening, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Later weeks are consumed once earlier ones are used up."+msgid "Latest operation end"msgstr "Latest operation end"+msgid "Latest Order Date"+msgstr "Latest Order Date"+msgid "Latitude"msgstr "Latitude"@@ -10153,6 +10303,9 @@ msgstr "Leave blank to use the next revision automatically"msgid "Leave empty for exact match"msgstr "Leave empty for exact match"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Leave empty, or enter 0, to show everything MRP plans."+msgid "Leave this page"msgstr "Leave this page"@@ -10441,6 +10594,12 @@ msgstr "Long Description"msgid "Longitude"msgstr "Longitude"+msgid "Look ahead (weeks)"+msgstr "Look ahead (weeks)"++msgid "Look back (weeks)"+msgstr "Look back (weeks)"+msgid "Looks empty here"msgstr "Looks empty here"@@ -10570,6 +10729,12 @@ msgstr "Maintenance Type"msgid "Make"msgstr "Make"+msgid "Make {amount} for {date}"+msgstr "Make {amount} for {date}"++msgid "Make {quantity}"+msgstr "Make {quantity}"+msgid "Make Active"msgstr "Make Active"@@ -10847,6 +11012,9 @@ msgstr "Material item"msgid "Material Planning"msgstr "Material Planning"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgid "Material Properties"msgstr "Material Properties"@@ -11231,6 +11399,18 @@ msgstr "MRP (planning)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP runs automatically every 3 hours, but you can run it manually here."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."++msgid "MRP Schedule"+msgstr "MRP Schedule"++msgid "MRP Suggestions"+msgstr "MRP Suggestions"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"@@ -11498,9 +11678,6 @@ msgstr "New Payment Term"msgid "New Picking List"msgstr "New Picking List"-msgid "New PO"-msgstr "New PO"-msgid "New Price Override"msgstr "New Price Override"@@ -12205,6 +12382,9 @@ msgstr "No storage unit"msgid "No storage units or tracking numbers match."msgstr "No storage units or tracking numbers match."+msgid "No Supplier"+msgstr "No Supplier"+msgid "No suppliers yet"msgstr "No suppliers yet"@@ -12555,6 +12735,9 @@ msgstr "On-time delivery"msgid "Onboard your agent to Carbon"msgstr "Onboard your agent to Carbon"+msgid "Once a day"+msgstr "Once a day"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Open job demand plus outstanding transfers out of this bin"msgid "Open jobs"msgstr "Open jobs"+msgid "Open Jobs"+msgstr "Open Jobs"+msgid "Open menu"msgstr "Open menu"msgid "Open navigation"msgstr "Open navigation"+msgid "Open Orders"+msgstr "Open Orders"+msgid "Open payables by supplier and age"msgstr "Open payables by supplier and age"@@ -12932,9 +13121,18 @@ msgstr "Order {0} × {substitute} for this job"msgid "Order {0} for this job"msgstr "Order {0} for this job"+msgid "Order {amount} for {date}"+msgstr "Order {amount} for {date}"++msgid "Order {quantity}"+msgstr "Order {quantity}"+msgid "Order by"msgstr "Order by"+msgid "Order By"+msgstr "Order By"+msgid "Order date"msgstr "Order date"@@ -13091,6 +13289,9 @@ msgstr "Owner"msgid "Owner (cost center)"msgstr "Owner (cost center)"+msgid "Ownership"+msgstr "Ownership"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Owns: {0}"@@ -13569,9 +13770,36 @@ msgstr "Planned time"msgid "Planning"msgstr "Planning"+msgid "Planning action"+msgstr "Planning action"++msgid "Planning horizon"+msgstr "Planning horizon"++msgid "Planning Horizon"+msgstr "Planning Horizon"++msgid "Planning Horizon (Days)"+msgstr "Planning Horizon (Days)"++msgid "Planning Horizon:"+msgstr "Planning Horizon:"++msgid "Planning Ownership"+msgstr "Planning Ownership"++msgid "Planning purchase orders need approval"+msgstr "Planning purchase orders need approval"++msgid "Planning purchase orders skip approval"+msgstr "Planning purchase orders skip approval"+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Planning rounds suggested replenishment up to a whole multiple of this number."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."@@ -13980,6 +14208,9 @@ msgstr "Project Plan"msgid "Project start"msgstr "Project start"+msgid "Projected"+msgstr "Projected"+msgid "Projected completion"msgstr "Projected completion"@@ -14001,6 +14232,12 @@ msgstr "Projected on hand"msgid "Projected stock"msgstr "Projected stock"+msgid "Projected stock by week"+msgstr "Projected stock by week"++msgid "Projected stock is already below zero this week"+msgstr "Projected stock is already below zero this week"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Projected stockout the week of {0}"@@ -14139,6 +14376,9 @@ msgstr "Purchase Order"msgid "Purchase Order Amount"msgstr "Purchase Order Amount"+msgid "Purchase Order Approval"+msgstr "Purchase Order Approval"+msgid "Purchase Order approval rule"msgstr "Purchase Order approval rule"@@ -14166,6 +14406,9 @@ msgstr "Purchase Orders"msgid "Purchase Orders and Planning"msgstr "Purchase Orders and Planning"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgid "Purchase orders required"msgstr "Purchase orders required"@@ -14272,9 +14515,6 @@ msgstr "Qty"msgid "Qty On Hand"msgstr "Qty On Hand"-msgid "Qty to Order"-msgstr "Qty to Order"-msgid "Qty. Complete"msgstr "Qty. Complete"@@ -14568,6 +14808,9 @@ msgstr "Ready for Quote"msgid "ready to keep or revert"msgstr "ready to keep or revert"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgid "Real-time inventory and shop-floor visibility"msgstr "Real-time inventory and shop-floor visibility"@@ -14880,9 +15123,15 @@ msgstr "Release Control"msgid "Release Job"msgstr "Release Job"+msgid "Release job {target} by {date}"+msgstr "Release job {target} by {date}"+msgid "Release Jobs"msgstr "Release Jobs"+msgid "Release purchase order {target} by {date}"+msgstr "Release purchase order {target} by {date}"+msgid "Released"msgstr "Released"@@ -15034,6 +15283,9 @@ msgstr "Rendering label preview..."msgid "Reopen"msgstr "Reopen"+msgid "Reopen as Revision"+msgstr "Reopen as Revision"+msgid "Reorder"msgstr "Reorder"@@ -15221,6 +15473,12 @@ msgstr "Requires Repair"msgid "Requires staffing"msgstr "Requires staffing"+msgid "Reschedule tolerance"+msgstr "Reschedule tolerance"++msgid "Reschedule Tolerance"+msgstr "Reschedule Tolerance"+msgid "Reserve floor"msgstr "Reserve floor"@@ -15279,6 +15537,12 @@ msgstr "resources"msgid "Resources"msgstr "Resources"+msgid "Responsible employee"+msgstr "Responsible employee"++msgid "Responsible Employee"+msgstr "Responsible Employee"+msgid "Restock"msgstr "Restock"@@ -15654,6 +15918,9 @@ msgstr "Run ID"msgid "Run month-end close and standard reconciliations"msgstr "Run month-end close and standard reconciliations"+msgid "Run MRP"+msgstr "Run MRP"+msgid "Run payment batches and track aging"msgstr "Run payment batches and track aging"@@ -17243,6 +17510,9 @@ msgstr "Start"msgid "Start {0} Day Free Trial"msgstr "Start {0} Day Free Trial"+msgid "Start By"+msgstr "Start By"+msgid "Start counting"msgstr "Start counting"@@ -17386,6 +17656,9 @@ msgstr "Steps built on their own, then fitted as one piece: in the step that usemsgid "Still dark out on the floor."msgstr "Still dark out on the floor."+msgid "Stock Availability"+msgstr "Stock Availability"+msgid "Stock movement corrected"msgstr "Stock movement corrected"@@ -17624,6 +17897,15 @@ msgstr "Suggest Match"msgid "Suggest with AI"msgstr "Suggest with AI"+msgid "Suggested Jobs"+msgstr "Suggested Jobs"++msgid "Suggested Orders"+msgstr "Suggested Orders"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgid "Suggested orders you haven't placed yet."msgstr "Suggested orders you haven't placed yet."@@ -17874,8 +18156,8 @@ msgstr "Sync"msgid "Sync Activity"msgstr "Sync Activity"-msgid "sync off"-msgstr "sync off"+msgid "Sync Off"+msgstr "Sync Off"msgid "Sync operation"msgstr "Sync operation"@@ -18642,6 +18924,9 @@ msgstr "The percentage of the cash discount. Use 0 for no discount."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "The plants, warehouses, and sites where your work and stock live"@@ -18663,6 +18948,9 @@ msgstr "The processes this work center can run; appears in process-pickers whenmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgid "The purchase order"+msgstr "The purchase order"+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."@@ -18991,6 +19279,9 @@ msgstr "These journal entries are still Draft, so their debits and credits aren'msgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "These operations use a process with multiple suppliers. Choose a supplier for each."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "These orders could not be loaded. Close and reopen to try again."+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."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Tolerance (+/-)"+msgid "Tolerance (days)"+msgstr "Tolerance (days)"+msgid "Tomorrow"msgstr "Tomorrow"@@ -19847,8 +20141,8 @@ msgstr "Undo"msgid "Ungroup"msgstr "Ungroup"-msgid "unhealthy"-msgstr "unhealthy"+msgid "Unhealthy"+msgstr "Unhealthy"msgid "Uninstall"msgstr "Uninstall"@@ -20936,6 +21230,9 @@ msgstr "When {name} changes"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."@@ -21128,6 +21425,9 @@ msgstr "Who gets trained on what, in what format. Your part: protect the hands-omsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Who has to approve quotes, orders, and purchases — and when"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Who should receive notifications for maintenance-related dispatches?"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 2799f88815..e802603a48 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# fila vincula a datos fuera de esta empresa, por lo qumsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# fila vincula a datos fuera de esta empresa, por lo que no se puede hacer backup. Omitirla permite hacer backup del resto.} other {# filas vinculan a datos fuera de esta empresa, por lo que no se pueden hacer backup. Omitirlas permite hacer backup del resto.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# semana} other {# semanas}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {El planificador trata este componente como un cuerpo rígido — un paso en las instrucciones. Vuelve a ejecutar la planificación para aplicar.} other {El planificador trata estos # componentes como un cuerpo rígido — un paso en las instrucciones. Vuelve a ejecutar la planificación para aplicar.}}"@@ -107,6 +111,10 @@ msgstr "{0} no se puede eliminar porque todavía está en uso por {where}. Cambimsgid "{0} cells with deltas"msgstr "{0} celdas con diferencias"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} consumido"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} valores"msgid "{0} values missing"msgstr "{0} valores faltantes"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} se guardará como {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# cuenta con saldo} other {# cuentas con saldo}}"msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# curso} other {# cursos}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# más después de {fenceLabel}} other {# más después de {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Disolver # lote de producción} other {Disolver # lotes de producción}}"@@ -340,6 +356,9 @@ msgstr "{days}d"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo} publica esto en tu libro mayor, por lo que Carbon no lo envía. Tu opción guardada se mantiene en caso de que eso cambie."+msgid "{dismissed} dismissed"+msgstr "{dismissed} descartado"+msgid "{done} of {total} phases complete"msgstr "{done} de {total} fases completadas"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} más: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} insertados, {updated} actualizados, {0} necesitan corrección, {1} omitidos."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# día} other {# días}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# línea} other {# líneas}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# fase restante} other {# fases restantes}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} Recursos · {reservationCount} reservaciones · {jobCount} Órdenes de trabajo"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} permisos"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Asigna primero la # cuenta requeridmsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} no puede ser programado"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} órdenes de trabajo actualizadas"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "Se ha subido {uploadedFileName} — se han completado los campos a partir del documento."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 operaciones"+msgid "0 suggests a move for any date difference."+msgstr "0 sugiere un cambio para cualquier diferencia de fecha."+msgid "0-4 weeks"msgstr "0-4 semanas"@@ -518,9 +543,6 @@ msgstr "1 apunte de borrador"msgid "1 job created"msgstr "1 trabajo creado"-msgid "1 job updated"-msgstr "1 trabajo actualizado"-msgid "1 part skipped — it already has an open job"msgstr "1 pieza omitida — ya tiene un trabajo abierto"@@ -530,6 +552,9 @@ msgstr "1 pieza omitida — no hay nada que fabricar"msgid "1 problem — not published"msgstr "1 problema — no publicado"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Compra = {conversionFactor} Inventario"+msgid "1 suggested batch"msgstr "1 lote sugerido"@@ -542,6 +567,9 @@ msgstr "12 períodos mensuales"msgid "13+ weeks"msgstr "13+ semanas"+msgid "1st Negative On Hand"+msgstr "Primer negativo en existencias"+msgid "1Y"msgstr "1 año"@@ -1082,6 +1110,9 @@ msgstr "Un paso necesita un nombre."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Una reserva almacenada de un centro de trabajo u operario para el lapso de tiempo colocado de una operación — el resultado materializado de una ejecución de programación, y lo que el Pronóstico dibuja."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Una sugerencia que MRP escribe después de cada ejecución: Pedir o Fabricar nuevo suministro, o Adelantar, Diferir, Aumentar, Disminuir o Cancelar una línea de orden de compra abierta u orden de trabajo. Aplícala desde la página de planificación, descártala o asígnala."+msgid "A supplier contact and location are optional"msgstr "Un contacto de proveedor y una ubicación son opcionales"@@ -1506,7 +1537,7 @@ msgid "Add from library…"msgstr "Agregar de la biblioteca…"msgid "Add from receipt"-msgstr "Agregar desde recepción"+msgstr "Agregar desde Recepción"msgid "Add from shipment"msgstr "Agregar desde envío"@@ -2006,6 +2037,12 @@ msgstr "Una operación de este trabajo se ejecuta en este lote"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "La posición de una operación en la cola de su centro de trabajo — el orden en que el piso toma el trabajo. El motor lo numera según el orden de colocación (inicio proyectado más temprano primero); reordenar tarjetas en el tablero de centros de trabajo la reemplaza sin cambiar fechas."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Ocurrió un error inesperado al conectar con Onshape. Guarde la configuración de integración e intente de nuevo."@@ -2167,6 +2204,9 @@ msgstr "Aplicar reglas de precios"msgid "Apply Rules On Top"msgstr "Aplicar reglas en la parte superior"+msgid "Apply Suggested Changes"+msgstr "Aplicar cambios sugeridos"+msgid "Apply suggestions"msgstr "Aplicar sugerencias"@@ -2824,6 +2864,9 @@ msgstr "Asignar a"msgid "Assign to Groups"msgstr "Asignar a Grupos"+msgid "Assign to Me"+msgstr "Asignarme"+msgid "Assigned"msgstr "Asignado"@@ -2836,6 +2879,9 @@ msgstr "Asignado a mí"msgid "Assignee"msgstr "Asignado a"+msgid "Assignees"+msgstr "Asignados"+msgid "Assignment"msgstr "Asignación"@@ -3491,12 +3537,18 @@ msgstr "Cancelar Aviso de Cambio"msgid "Cancel Job"msgstr "Cancelar Trabajo"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Cancelar pedido"msgid "Cancel Purchase Order"msgstr "Cancelar orden de compra"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Cancelar Devolución"@@ -3548,6 +3600,12 @@ msgstr "No se puede mover al depósito de piezas sin ID de artículo"msgid "Cannot place order - no supplier associated with this item"msgstr "No se puede realizar el pedido - no hay proveedor asociado a este artículo"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "No se puede realizar el pedido: {count} artículos no tienen proveedor"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "No se puede realizar el pedido: 1 artículo no tiene proveedor"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "No se puede publicar — el envío contiene entidades rastreadas vencidas."@@ -3753,6 +3811,9 @@ msgstr "Cambiar Tipo"msgid "Changed By"msgstr "Cambiado por"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Cambió solo para esta vista. El horizonte de planificación del artículo no se actualiza."+msgid "Changelog"msgstr "Registro de cambios"@@ -3853,6 +3914,9 @@ msgstr "Elija cómo agregar líneas a esta devolución."msgid "Choose what appears on the printed job traveler."msgstr "Elija qué aparece en la hoja viajera de la orden de trabajo impresa."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Elige cuándo MRP se recalcula automáticamente. Aún puedes ejecutarlo manualmente en cualquier momento con Recalcular en las páginas de Planificación."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Elija si el explorador de lista de materiales en artículos, cotizaciones y órdenes de trabajo etiqueta cada línea con su descripción o el ID del artículo."@@ -4068,6 +4132,9 @@ msgstr "Empresas"msgid "Company"msgstr "Empresa"+msgid "Company default"+msgstr "Valor predeterminado de la empresa"+msgid "Company group"msgstr "Grupo de empresas"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "No se pudo leer el documento: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "No se pudo liberar {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "Departamento creado"msgid "Created failure mode"msgstr "Modo de fallo creado"+msgid "Created from planning"+msgstr "Creado desde la planificación"+msgid "Created gauge type"msgstr "Se creó el tipo de instrumento"@@ -5671,6 +5743,15 @@ msgstr "Lugares Decimales"msgid "Declining balance"msgstr "Saldo decreciente"+msgid "Decrease"+msgstr "Reducir"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Horas profundas de la madrugada, {name}."@@ -5737,6 +5818,9 @@ msgstr "Cuenta de gasto contable predeterminada para mantenimiento de equipo e imsgid "Default GL expense account for periodic depreciation runs."msgstr "Cuenta de gasto contable predeterminada para ejecuciones de depreciación periódicas."+msgid "Default horizon (days)"+msgstr "Horizonte predeterminado (días)"+msgid "Default Method"msgstr "Método Predeterminado"@@ -5788,6 +5872,15 @@ msgstr "Vida útil predeterminada que se completa previamente en nuevos activosmsgid "Defaults"msgstr "Valores predeterminados"+msgid "Defer"+msgstr "Diferir"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Gasto por impuesto diferido"@@ -6368,6 +6461,9 @@ msgstr "Descubrimiento"msgid "Dismiss"msgstr "Descartar"+msgid "Dismissed"+msgstr "Descartado"+msgid "Dispatch"msgstr "Orden de mantenimiento"@@ -6744,6 +6840,9 @@ msgstr "Las operaciones externas de cada proveedor de cada orden de trabajo se cmsgid "Each, lb, ft…"msgstr "Cada, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "Las semanas anteriores se consumen primero."+msgid "Earliest operation start"msgstr "Inicio más temprano de la operación"@@ -7503,6 +7602,9 @@ msgstr "Tipo de Evento"msgid "Events"msgstr "Eventos"+msgid "Every 3 hours"+msgstr "Cada 3 horas"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Todos los registros de la empresa. Las credenciales, los tokens de integración y los webhooks nunca se incluyen."@@ -7635,6 +7737,15 @@ msgstr "Recepción Esperada"msgid "Expected Receipt Date"msgstr "Fecha de Recepción Esperada"+msgid "Expedite"+msgstr "Adelantar"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Cuenta de gastos para saldos de clientes cancelados como incobrables en la liquidación de cuentas por cobrar"@@ -8112,12 +8223,18 @@ msgstr "Error al actualizar el recuento"msgid "Failed to update item cost"msgstr "Error al actualizar el costo del artículo"+msgid "Failed to update job"+msgstr "Error al actualizar la orden de trabajo"+msgid "Failed to update lead times"msgstr "Error al actualizar los plazos de entrega"msgid "Failed to update opportunity with purchase order"msgstr "Error al actualizar la oportunidad con la orden de compra"+msgid "Failed to update purchase order line"+msgstr "Error al actualizar la línea de orden de compra"+msgid "Failed to update quote line"msgstr "Error al actualizar la línea de cotización"@@ -8315,6 +8432,9 @@ msgstr "Nombre"msgid "First Operation"msgstr "Primera Operación"+msgid "First week the projected stock goes below zero"+msgstr "Primera semana las existencias proyectadas descienden por debajo de cero"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Activo Fijo"@@ -8381,6 +8501,12 @@ msgstr "para cualquier cosa. Ellos traerán a la persona indicada."msgid "Forecast"msgstr "Pronóstico"+msgid "Forecast consumption"+msgstr "Pronóstico de consumo"++msgid "Forecast Consumption"+msgstr "Consumo de Pronóstico"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Método de pronóstico: <0>{0}</0>. Esta fila no se derivó de órdenes de trabajo activas, por lo que no hay fuentes principales disponibles."@@ -8829,8 +8955,8 @@ msgstr "Tiene operaciones que no pueden ser programadas"msgid "Headers"msgstr "Encabezados"-msgid "healthy"-msgstr "saludable"+msgid "Healthy"+msgstr "Saludable"msgid "Help"msgstr "Ayuda"@@ -8979,6 +9105,9 @@ msgstr "Cuántos días después de la fecha de cálculo el descuento por pago anmsgid "How many days after the calculation date the full amount is due."msgstr "Cuántos días después de la fecha de cálculo el monto completo es debido."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Cuántos días una orden abierta puede atrasarse desde la fecha en que se necesita antes de que MRP sugiera adelantarla. Configurar en Configuración → Planificación; el valor predeterminado es 7 días."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Cuántos días desde la fecha de la factura este cliente tiene para pagar; determina la fecha de vencimiento predeterminada en las facturas de clientes."@@ -9253,6 +9382,9 @@ msgstr "En este paso"msgid "In use"msgstr "En uso"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "En la zona horaria de tu empresa ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "En la configuración de empresa en Desarrollador, edite los permisos de la aplicación OAuth privada para incluir «La aplicación puede escribir en sus documentos», luego guarde la configuración de integración nuevamente."@@ -9265,9 +9397,6 @@ msgstr "Las notificaciones en la aplicación siempre se entregan. Elija qué temmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Las notificaciones en la aplicación siempre se entregan. Elija qué temas también le llegan por correo electrónico."-msgid "inactive"-msgstr "inactivo"-msgid "Inactive"msgstr "Inactivo"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Ubicación del Incoterm"+msgid "Increase"+msgstr "Aumentar"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Indirecto"@@ -9364,6 +9502,9 @@ msgstr "Heredado del grupo: si esta cuenta se cierra a Resultados acumulados (inmsgid "Inherited from the parent group."msgstr "Heredado del grupo padre."+msgid "inherits {inheritedName}"+msgstr "hereda {inheritedName}"+msgid "Input"msgstr "Entrada"@@ -9893,6 +10034,9 @@ msgstr "Prioridad del trabajo"msgid "Job readable"msgstr "Trabajo legible"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Hoja viajera"@@ -10108,9 +10252,15 @@ msgstr "Último uso"msgid "Late in the evening, {name}."msgstr "Noche avanzada, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Las semanas posteriores se consumen una vez que se agotan las anteriores."+msgid "Latest operation end"msgstr "Fin de la última operación"+msgid "Latest Order Date"+msgstr "Última fecha de orden"+msgid "Latitude"msgstr "Latitud"@@ -10153,6 +10303,9 @@ msgstr "Dejar en blanco para usar la siguiente revisión automáticamente"msgid "Leave empty for exact match"msgstr "Dejar vacío para coincidencia exacta"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Dejar vacío o ingrese 0 para mostrar todo lo que MRP planifica."+msgid "Leave this page"msgstr "Salir de esta página"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Líneas"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Las líneas aparecen aquí una vez que se ha contabilizado una recepción de orden de compra, y solo para cantidades que no estén ya autorizadas en otra devolución de proveedor. Usa Agregar artículo de línea para una devolución ciega."+msgstr "Las líneas aparecen aquí después de que se ha contabilizado una recepción de orden de compra, y solo para cantidades que no hayan sido autorizadas en otro retorno de proveedor. Utilice Agregar Artículo de Línea para una devolución sin documentación."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Las líneas aparecen aquí una vez que se ha contabilizado un envío de pedido de venta, y solo para cantidades no autorizadas en otro RMA. Use Agregar artículo de línea para una devolución a ciegas."@@ -10441,6 +10594,12 @@ msgstr "Descripción Larga"msgid "Longitude"msgstr "Longitud"+msgid "Look ahead (weeks)"+msgstr "Mirar adelante (semanas)"++msgid "Look back (weeks)"+msgstr "Mirar atrás (semanas)"+msgid "Looks empty here"msgstr "Se ve vacío aquí"@@ -10570,6 +10729,12 @@ msgstr "Tipo de Mantenimiento"msgid "Make"msgstr "Fabricar"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "Fabricar {quantity}"+msgid "Make Active"msgstr "Activar"@@ -10847,6 +11012,9 @@ msgstr "Artículo de material"msgid "Material Planning"msgstr "Planificación de materiales"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "La planificación de material muestra solo acciones y órdenes sugeridas vencidas dentro de este número de días a partir de hoy, por lo que las necesidades lejanas se mantienen fuera del camino hasta que sean importantes. El horizonte de planificación propio del artículo anula este valor predeterminado."+msgid "Material Properties"msgstr "Propiedades del Material"@@ -11231,6 +11399,18 @@ msgstr "MRP (planificación)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP se ejecuta automáticamente cada 3 horas, pero puedes ejecutarlo manualmente aquí."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP se ejecuta automáticamente todos los días a {time} ({timeZone}), pero puede ejecutarlo manualmente aquí."++msgid "MRP Schedule"+msgstr "Programa MRP"++msgid "MRP Suggestions"+msgstr "Sugerencias MRP"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP sugiere mover una orden existente solo cuando su fecha está desfasada más de esta cantidad de días. Los pequeños desfases se dejan sin cambios para mantener la lista de tareas tranquila."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Múltiples Órdenes de trabajo pueden ejecutarse en este Proceso simultáneamente — por ejemplo, una mesa láser, horno o baño de galvanoplastia"@@ -11498,9 +11678,6 @@ msgstr "Nuevas condiciones de pago"msgid "New Picking List"msgstr "Nueva Lista de Picking"-msgid "New PO"-msgstr "Nuevo PO"-msgid "New Price Override"msgstr "Nueva sobrescritura de precio"@@ -12205,6 +12382,9 @@ msgstr "Sin unidad de almacenamiento"msgid "No storage units or tracking numbers match."msgstr "No coinciden unidades de almacenamiento ni números de seguimiento."+msgid "No Supplier"+msgstr "Sin proveedor"+msgid "No suppliers yet"msgstr "Sin proveedores aún"@@ -12555,6 +12735,9 @@ msgstr "Entrega a tiempo"msgid "Onboard your agent to Carbon"msgstr "Integra tu agente en Carbon"+msgid "Once a day"+msgstr "Una vez al día"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Demanda de trabajo abierto más transferencias pendientes de este contenmsgid "Open jobs"msgstr "Órdenes de trabajo abiertas"+msgid "Open Jobs"+msgstr "Órdenes de trabajo Abiertas"+msgid "Open menu"msgstr "Abrir menú"msgid "Open navigation"msgstr "Abrir navegación"+msgid "Open Orders"+msgstr "Órdenes Abiertas"+msgid "Open payables by supplier and age"msgstr "Cuentas por pagar abiertas por proveedor y antigüedad"@@ -12932,9 +13121,18 @@ msgstr "Ordenar {0} × {substitute} para esta orden de trabajo"msgid "Order {0} for this job"msgstr "Pedir {0} para este trabajo"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "Pedir {quantity}"+msgid "Order by"msgstr "Ordenar por"+msgid "Order By"+msgstr "Ordenar por"+msgid "Order date"msgstr "Fecha del pedido"@@ -13091,6 +13289,9 @@ msgstr "Propietario"msgid "Owner (cost center)"msgstr "Propietario (centro de costos)"+msgid "Ownership"+msgstr "Responsabilidad"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Propietario: {0}"@@ -13569,9 +13770,36 @@ msgstr "Tiempo planificado"msgid "Planning"msgstr "Planificación"+msgid "Planning action"+msgstr "Acción de planificación"++msgid "Planning horizon"+msgstr "Horizonte de planificación"++msgid "Planning Horizon"+msgstr "Horizonte de Planificación"++msgid "Planning Horizon (Days)"+msgstr "Horizonte de Planificación (Días)"++msgid "Planning Horizon:"+msgstr "Horizonte de Planificación:"++msgid "Planning Ownership"+msgstr "Responsabilidad de Planificación"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Las rondas de planificación sugirieron reabastecimiento hasta un múltiplo entero de este número."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "La planificación muestra solo acciones y órdenes sugeridas vencidas dentro de este número de días. Dejar vacío para usar el predeterminado de la empresa, o ingrese 0 para mostrar todo para este artículo."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Límite inferior de planificación en una cantidad de reabastecimiento sugerida; distinto del MOQ de un proveedor, que vive en el registro de piezas del proveedor."@@ -13980,6 +14208,9 @@ msgstr "Plan de Proyecto"msgid "Project start"msgstr "Inicio del proyecto"+msgid "Projected"+msgstr "Proyectado"+msgid "Projected completion"msgstr "Finalización proyectada"@@ -14001,6 +14232,12 @@ msgstr "Falta de inventario proyectada la semana del {0}"msgid "Projected stock"msgstr "Stock proyectado"+msgid "Projected stock by week"+msgstr "Existencias proyectadas por semana"++msgid "Projected stock is already below zero this week"+msgstr "Las existencias proyectadas ya están por debajo de cero esta semana"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Rotura de stock proyectada la semana del {0}"@@ -14139,6 +14376,9 @@ msgstr "Orden de Compra"msgid "Purchase Order Amount"msgstr "Monto de Orden de Compra"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Regla de aprobación de orden de compra"@@ -14166,6 +14406,9 @@ msgstr "Órdenes de Compra"msgid "Purchase Orders and Planning"msgstr "Órdenes de Compra y Planificación"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Órdenes de compra requeridas"@@ -14272,9 +14515,6 @@ msgstr "Cant."msgid "Qty On Hand"msgstr "Cantidad Disponible"-msgid "Qty to Order"-msgstr "Cantidad a Pedir"-msgid "Qty. Complete"msgstr "Cant. Completada"@@ -14568,6 +14808,9 @@ msgstr "Listo para cotizar"msgid "ready to keep or revert"msgstr "listo para mantener o revertir"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Las órdenes reales consumen el pronóstico de demanda de su propia semana primero, luego las semanas anteriores y posteriores dentro de la ventana de la empresa, por lo que el pronóstico y la demanda real nunca se planifican ambos para las mismas unidades."+msgid "Real-time inventory and shop-floor visibility"msgstr "Visibilidad del inventario y la planta de producción en tiempo real"@@ -14880,9 +15123,15 @@ msgstr "Control de liberación"msgid "Release Job"msgstr "Liberar Trabajo"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Liberar órdenes de trabajo"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Liberado"@@ -15034,6 +15283,9 @@ msgstr "Renderizando vista previa de etiqueta..."msgid "Reopen"msgstr "Reabrir"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Reordenar"@@ -15221,6 +15473,12 @@ msgstr "Requiere Reparación"msgid "Requires staffing"msgstr "Requiere personal"+msgid "Reschedule tolerance"+msgstr "Tolerancia de reprogramación"++msgid "Reschedule Tolerance"+msgstr "Tolerancia de Reprogramación"+msgid "Reserve floor"msgstr "Piso de reserva"@@ -15279,6 +15537,12 @@ msgstr "recursos"msgid "Resources"msgstr "Recursos"+msgid "Responsible employee"+msgstr "Empleado Responsable"++msgid "Responsible Employee"+msgstr "Empleado Responsable"+msgid "Restock"msgstr "Reabastecer"@@ -15654,6 +15918,9 @@ msgstr "ID de Ejecución"msgid "Run month-end close and standard reconciliations"msgstr "Ejecutar cierre de fin de mes y conciliaciones estándar"+msgid "Run MRP"+msgstr "Ejecutar MRP"+msgid "Run payment batches and track aging"msgstr "Ejecutar lotes de pago y rastrear antigüedad"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "Seleccionar operaciones"msgid "Select posted receipt lines from this supplier to return."-msgstr "Selecciona líneas de recepción contabilizadas de este proveedor para devolver."+msgstr "Seleccionar líneas de recepción contabilizadas de este proveedor para devolver."msgid "Select posted shipment lines to this customer to return."msgstr "Seleccionar líneas de envío contabilizadas a este cliente para devolver."@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "Sesión bloqueada"msgid "Set a customer on this return to add from a shipment."-msgstr "Establece un cliente en esta devolución para agregar desde un envío."+msgstr "Establezca un cliente en esta devolución para agregar desde un envío."msgid "Set a supplier on this return to add from a receipt."msgstr "Establecer un proveedor en esta devolución para agregar desde una recepción."@@ -17243,6 +17510,9 @@ msgstr "Iniciar"msgid "Start {0} Day Free Trial"msgstr "Iniciar prueba gratuita de {0} días"+msgid "Start By"+msgstr "Comenzar por"+msgid "Start counting"msgstr "Iniciar conteo"@@ -17386,6 +17656,9 @@ msgstr "Los pasos se construyen por su cuenta, luego se ajustan como una sola pimsgid "Still dark out on the floor."msgstr "Todavía está oscuro en el taller."+msgid "Stock Availability"+msgstr "Disponibilidad de existencias"+msgid "Stock movement corrected"msgstr "Movimiento de stock corregido"@@ -17624,6 +17897,15 @@ msgstr "Sugerir Coincidencia"msgid "Suggest with AI"msgstr "Sugerir con IA"+msgid "Suggested Jobs"+msgstr "Órdenes de trabajo Sugeridas"++msgid "Suggested Orders"+msgstr "Órdenes Sugeridas"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Órdenes sugeridas requeridas después del horizonte de planificación del artículo. Extienda el horizonte para incluirlas."+msgid "Suggested orders you haven't placed yet."msgstr "Pedidos sugeridos que aún no ha realizado."@@ -17874,8 +18156,8 @@ msgstr "Sincronizar"msgid "Sync Activity"msgstr "Actividad de sincronización"-msgid "sync off"-msgstr "sync desactivado"+msgid "Sync Off"+msgstr "Sync desactivado"msgid "Sync operation"msgstr "Operación de sincronización"@@ -18642,6 +18924,9 @@ msgstr "El porcentaje del descuento en efectivo. Utiliza 0 para sin descuento."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "El conjunto de permisos que reciben automáticamente los nuevos empleados de este tipo; editar aquí cambia la plantilla solo para futuras contrataciones - los empleados existentes conservan lo que tienen a menos que se actualicen explícitamente en masa."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "La persona a quien se asigna una acción de planificación: el propietario del artículo en esa ubicación; en su defecto, el del grupo de artículos; en su defecto, el de la ubicación; en su defecto, el valor predeterminado de la empresa."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Las plantas, almacenes y sitios donde viven tu trabajo e inventario"@@ -18663,6 +18948,9 @@ msgstr "Los procesos que puede ejecutar este centro de trabajo; aparece en selecmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "El proveedor no ofrece destinos de dimensión. Habilita la función en el proveedor primero (p. ej. categorías de seguimiento, seguimiento de clases o campos)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Los puntos de ruptura de cantidad a los que se cotiza esta línea; cada columna lleva su propio precio por unidad para la negociación comprador-proveedor y para la conversión a documentos posteriores."@@ -18991,6 +19279,9 @@ msgstr "Estos asientos aún están en Borrador, por lo que sus debe y haber no emsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Estas operaciones utilizan un proceso con múltiples proveedores. Elija un proveedor para cada una."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Estas órdenes no se pudieron cargar. Cierre y reabra para intentar de nuevo."+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."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Tolerancia (+/-)"+msgid "Tolerance (days)"+msgstr "Tolerancia (días)"+msgid "Tomorrow"msgstr "Mañana"@@ -19847,8 +20141,8 @@ msgstr "Deshacer"msgid "Ungroup"msgstr "Desagrupar"-msgid "unhealthy"-msgstr "insalubre"+msgid "Unhealthy"+msgstr "Insalubre"msgid "Uninstall"msgstr "Desinstalar"@@ -20936,6 +21230,9 @@ msgstr "Cuando {name} cambia"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Cuando la vida de anaquel del producto terminado se establece en Calculada, selecciona qué materiales consumidos alimentan el cálculo."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Cuando un pedido de venta u orden de trabajo llega en una semana sin pronóstico restante, consume pronóstico de semanas cercanas en lugar de ser contado además. Establezca ambos en 0 para compensar únicamente dentro de la misma semana."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Cuando un serial o lote caduca, y qué sucede si se usa después — una política de la empresa puede Advertir, Bloquear o Bloquear con anulación."@@ -21128,6 +21425,9 @@ msgstr "Quién recibe capacitación sobre qué, en qué formato. Tu parte: protemsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Quién debe aprobar cotizaciones, pedidos y compras — y cuándo"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Quién posee las acciones de planificación de MRP. Las ubicaciones heredan el valor predeterminado de la empresa; los grupos de artículos heredan su ubicación. La asignación más específica gana, y cada artículo puede sobrescribir en su pestaña de Planificación."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "¿Quién debe recibir notificaciones para órdenes de mantenimiento relacionadas?"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 196f2a3045..cedce292ad 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# ligne se connecte à des données en dehors de cettemsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# ligne se connecte à des données en dehors de cette Société, donc elle ne peut pas être sauvegardée. L'ignorer sauvegarde tout le reste.} other {# lignes se connectent à des données en dehors de cette Société, donc elles ne peuvent pas être sauvegardées. Les ignorer sauvegarde tout le reste.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# semaine} other {# semaines}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {Le planificateur traite ce composant comme un corps rigide — une étape dans les instructions. Réexécutez la planification pour appliquer.} other {Le planificateur traite ces # composants comme un corps rigide — une étape dans les instructions. Réexécutez la planification pour appliquer.}}"@@ -107,6 +111,10 @@ msgstr "{0} ne peut pas être supprimé car il est encore utilisé par {where}.msgid "{0} cells with deltas"msgstr "{0} cellules avec écarts"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} consommé"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} valeurs"msgid "{0} values missing"msgstr "{0} valeurs manquantes"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} sera enregistré en tant que {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# compte avec un solde} other {# comptes avec un somsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# cours} other {# cours}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# plus après {fenceLabel}} other {# plus après {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Dissoudre # lot de production} other {Dissoudre # lots de production}}"@@ -340,6 +356,9 @@ msgstr "{days}j"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "${delegatedTo} publie ceci dans votre grand livre, donc Carbon ne le pousse pas. Votre choix enregistré est conservé au cas où cela changerait."+msgid "{dismissed} dismissed"+msgstr "{dismissed} écartés"+msgid "{done} of {total} phases complete"msgstr "{done} sur {total} phases terminées"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} autres : {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} insérés, {updated} mis à jour, {0} nécessitent correction, {1} ignorés."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# jour} other {# jours}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# ligne} other {# lignes}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# phase restante} other {# phases restantes}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} Ressources · {reservationCount} réservations · {jobCount} Ordres de fabrication"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} autorisations"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Mapper d'abord le # compte requis rmsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} ne peuvent pas être planifiés"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} ordres de fabrication mis à jour"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} téléchargé — champs remplis à partir du document."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 opération"+msgid "0 suggests a move for any date difference."+msgstr "0 suggère un déplacement pour toute différence de date."+msgid "0-4 weeks"msgstr "0-4 semaines"@@ -518,9 +543,6 @@ msgstr "1 ligne d'écriture en brouillon"msgid "1 job created"msgstr "1 tâche créée"-msgid "1 job updated"-msgstr "1 tâche mise à jour"-msgid "1 part skipped — it already has an open job"msgstr "1 pièce ignorée — elle a déjà une tâche ouverte"@@ -530,6 +552,9 @@ msgstr "1 pièce ignorée — rien à fabriquer"msgid "1 problem — not published"msgstr "1 problème — non publié"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Achat = {conversionFactor} Stocks"+msgid "1 suggested batch"msgstr "1 lot de production suggéré"@@ -542,6 +567,9 @@ msgstr "12 périodes mensuelles"msgid "13+ weeks"msgstr "13+ semaines"+msgid "1st Negative On Hand"+msgstr "1ère Quantité Négative"+msgid "1Y"msgstr "1 an"@@ -1082,6 +1110,9 @@ msgstr "Une étape doit avoir un nom."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Une réservation stockée d'un poste de travail ou d'un opérateur pour la durée planifiée d'une opération — le résultat matérialisé d'une exécution de planning, et ce que la Prévision affiche."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Une suggestion que MRP rédige après chaque exécution : Commander ou Fabriquer un nouvel approvisionnement, ou Accélérer, Reporter, Augmenter, Diminuer ou Annuler une ligne de bon de commande ouverte ou un ordre de fabrication ouvert. Appliquez-le depuis la page de planification, écartez-le ou attribuez-le."+msgid "A supplier contact and location are optional"msgstr "Un contact fournisseur et un site sont facultatifs"@@ -1506,7 +1537,7 @@ msgid "Add from library…"msgstr "Ajouter à partir de la bibliothèque…"msgid "Add from receipt"-msgstr "Ajouter depuis une réception"+msgstr "Ajouter d'une réception"msgid "Add from shipment"msgstr "Ajouter depuis l'expédition"@@ -2006,6 +2037,12 @@ msgstr "Une opération de cet OF s'exécute dans ce lot"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "La position d'une opération dans la file d'attente de son poste de travail — l'ordre dans lequel l'atelier exécute le travail. Le moteur la numérote d'après l'ordre de placement (le démarrage projeté le plus tôt d'abord) ; le réordonnancement des cartes sur le Tableau des postes de travail la remplace sans modifier les dates."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Une erreur inattendue s'est produite lors de la connexion à Onshape. Enregistrez les paramètres d'intégration pour réessayer."@@ -2167,6 +2204,9 @@ msgstr "Appliquer les règles de tarification"msgid "Apply Rules On Top"msgstr "Appliquer les règles en premier"+msgid "Apply Suggested Changes"+msgstr "Appliquer les modifications suggérées"+msgid "Apply suggestions"msgstr "Appliquer les suggestions"@@ -2824,6 +2864,9 @@ msgstr "Attribuer à"msgid "Assign to Groups"msgstr "Attribuer à des groupes"+msgid "Assign to Me"+msgstr "M'attribuer"+msgid "Assigned"msgstr "Assigné"@@ -2836,6 +2879,9 @@ msgstr "Assigné à moi"msgid "Assignee"msgstr "Assignataire"+msgid "Assignees"+msgstr "Assignés"+msgid "Assignment"msgstr "Affectation"@@ -3491,12 +3537,18 @@ msgstr "Annuler l'avis de modification"msgid "Cancel Job"msgstr "Annuler le travail"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Annuler la commande"msgid "Cancel Purchase Order"msgstr "Annuler le bon de commande"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Annuler le retour"@@ -3548,6 +3600,12 @@ msgstr "Impossible de déplacer vers le compartiment des pièces sans ID d'articmsgid "Cannot place order - no supplier associated with this item"msgstr "Impossible de passer la commande - aucun fournisseur associé à cet article"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Impossible de passer la commande — {count} articles n'ont pas de fournisseur"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Impossible de passer la commande — 1 article n'a pas de fournisseur"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Impossible de publier — l'expédition contient des entités suivies expirées."@@ -3753,6 +3811,9 @@ msgstr "Changer le type"msgid "Changed By"msgstr "Modifié par"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Modifié pour cette vue uniquement. L'horizon de planification de l'article n'est pas mis à jour."+msgid "Changelog"msgstr "Journal des modifications"@@ -3853,6 +3914,9 @@ msgstr "Choisissez comment ajouter des lignes à ce retour."msgid "Choose what appears on the printed job traveler."msgstr "Choisir ce qui apparaît sur la fiche suiveuse d'ordre de fabrication imprimée."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Choisissez quand le MRP se recalcule automatiquement. Vous pouvez toujours l'exécuter manuellement à tout moment avec Recalculer sur les pages de Planification."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Choisissez si l'explorateur de nomenclature sur les articles, les devis et les ordres de fabrication étiquette chaque ligne avec sa description ou son ID article."@@ -4068,6 +4132,9 @@ msgstr "Entreprises"msgid "Company"msgstr "Société"+msgid "Company default"+msgstr "Valeur par défaut de la société"+msgid "Company group"msgstr "Groupe de sociétés"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Impossible de lire le document : {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Impossible de lancer {0} : {1}"@@ -5093,6 +5162,9 @@ msgstr "Département créé"msgid "Created failure mode"msgstr "Mode de défaillance créé"+msgid "Created from planning"+msgstr "Créé depuis la planification"+msgid "Created gauge type"msgstr "Type d'instrument créé"@@ -5671,6 +5743,15 @@ msgstr "Décimales"msgid "Declining balance"msgstr "Amortissement dégressif"+msgid "Decrease"+msgstr "Diminuer"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Au cœur de la nuit, {name}."@@ -5737,6 +5818,9 @@ msgstr "Compte général de charge par défaut pour la maintenance des équipememsgid "Default GL expense account for periodic depreciation runs."msgstr "Compte général de charge par défaut pour les cycles d'amortissement périodiques."+msgid "Default horizon (days)"+msgstr "Horizon par défaut (jours)"+msgid "Default Method"msgstr "Méthode par défaut"@@ -5788,6 +5872,15 @@ msgstr "Durée d'utilité par défaut qui se remplit préalablement sur les nouvmsgid "Defaults"msgstr "Paramètres par défaut"+msgid "Defer"+msgstr "Reporter"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Charge d'Impôt Différé"@@ -6368,6 +6461,9 @@ msgstr "Découverte"msgid "Dismiss"msgstr "Fermer"+msgid "Dismissed"+msgstr "Écartée"+msgid "Dispatch"msgstr "Intervention de maintenance"@@ -6744,6 +6840,9 @@ msgstr "Les opérations externalisées de chaque fournisseur de chaque ordre demsgid "Each, lb, ft…"msgstr "Chacun, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "Les semaines antérieures sont consommées en premier."+msgid "Earliest operation start"msgstr "Début d'opération le plus tôt"@@ -7503,6 +7602,9 @@ msgstr "Type d'événement"msgid "Events"msgstr "Événements"+msgid "Every 3 hours"+msgstr "Toutes les 3 heures"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Tous les enregistrements de l'entreprise. Les identifiants, jetons d'intégration et webhooks ne sont jamais inclus."@@ -7635,6 +7737,15 @@ msgstr "Réception prévue"msgid "Expected Receipt Date"msgstr "Date de réception prévue"+msgid "Expedite"+msgstr "Avancer"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Compte de charge pour les soldes clients radiés comme irrécouvrables lors du règlement des comptes clients"@@ -8112,12 +8223,18 @@ msgstr "Impossible de mettre à jour le nombre"msgid "Failed to update item cost"msgstr "Impossible de mettre à jour le coût de l'article"+msgid "Failed to update job"+msgstr "Échec de la mise à jour de l'ordre de fabrication"+msgid "Failed to update lead times"msgstr "Échec de la mise à jour des délais d'approvisionnement"msgid "Failed to update opportunity with purchase order"msgstr "Impossible de mettre à jour l'opportunité avec le bon de commande"+msgid "Failed to update purchase order line"+msgstr "Échec de la mise à jour de la ligne de bon de commande"+msgid "Failed to update quote line"msgstr "Impossible de mettre à jour la ligne de devis"@@ -8315,6 +8432,9 @@ msgstr "Prénom"msgid "First Operation"msgstr "Première opération"+msgid "First week the projected stock goes below zero"+msgstr "Première semaine où le stock projeté devient négatif"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Immobilisation"@@ -8381,6 +8501,12 @@ msgstr "pour n'importe quoi. Ils vont faire intervenir la bonne personne."msgid "Forecast"msgstr "Prévision"+msgid "Forecast consumption"+msgstr "Prévision de consommation"++msgid "Forecast Consumption"+msgstr "Consommation des prévisions"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Méthode de prévision : <0>{0}</0>. Cette ligne n'a pas été dérivée des ordres de fabrication actifs, donc aucune source parent n'est disponible."@@ -8829,8 +8955,8 @@ msgstr "Contient des opérations qui ne peuvent pas être planifiées"msgid "Headers"msgstr "En-têtes"-msgid "healthy"-msgstr "sain"+msgid "Healthy"+msgstr "Sain"msgid "Help"msgstr "Aide"@@ -8979,6 +9105,9 @@ msgstr "Combien de jours après la date de calcul la remise pour paiement anticimsgid "How many days after the calculation date the full amount is due."msgstr "Combien de jours après la date de calcul le montant total est dû."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Nombre de jours qu'une commande ouverte peut arriver avant ou après la date à laquelle elle est nécessaire avant que MRP ne suggère de la reprogrammer. À définir dans Paramètres → Planification ; la valeur par défaut est 7 jours."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Combien de jours à partir de la date de facture ce client a pour payer; détermine la date d'échéance par défaut sur les factures clients."@@ -9253,6 +9382,9 @@ msgstr "À cette étape"msgid "In use"msgstr "En cours d'utilisation"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "Dans le fuseau horaire de votre Société ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "Dans vos paramètres Enterprise sous Développeur, modifiez les autorisations de l'application OAuth privée pour inclure « L'application peut écrire dans vos documents », puis enregistrez à nouveau les paramètres d'intégration."@@ -9265,9 +9397,6 @@ msgstr "Les notifications dans l'application sont toujours livrées. Choisissezmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Les notifications dans l'application sont toujours livrées. Choisissez les sujets qui vous parviennent également par e-mail."-msgid "inactive"-msgstr "inactif"-msgid "Inactive"msgstr "Inactif"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Lieu Incoterm"+msgid "Increase"+msgstr "Augmenter"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Indirect"@@ -9364,6 +9502,9 @@ msgstr "Hérité du groupe : si ce compte se ferme sur le report à nouveau (promsgid "Inherited from the parent group."msgstr "Hérité du groupe parent."+msgid "inherits {inheritedName}"+msgstr "hérite de {inheritedName}"+msgid "Input"msgstr "Entrée"@@ -9893,6 +10034,9 @@ msgstr "Priorité du travail"msgid "Job readable"msgstr "Travail lisible"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Fiche suiveuse"@@ -10022,7 +10166,7 @@ msgid "Labor & Machine Variance (default)"msgstr "Écart de main-d'œuvre et machine (par défaut)"msgid "Labor Costs"-msgstr "Coûts de main-d'œuvre"+msgstr "Coûts de Main-d'œuvre"msgid "Labor Hours"msgstr "Heures de main-d'œuvre"@@ -10108,9 +10252,15 @@ msgstr "Dernière utilisation"msgid "Late in the evening, {name}."msgstr "Tard en soirée, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Les semaines suivantes sont consommées une fois que les semaines antérieures sont épuisées."+msgid "Latest operation end"msgstr "Fin de la dernière opération"+msgid "Latest Order Date"+msgstr "Date limite de commande"+msgid "Latitude"msgstr "Latitude"@@ -10153,6 +10303,9 @@ msgstr "Laisser vide pour utiliser automatiquement la prochaine révision"msgid "Leave empty for exact match"msgstr "Laisser vide pour une correspondance exacte"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Laisser vide ou entrer 0 pour afficher tout ce que le MRP planifie."+msgid "Leave this page"msgstr "Quitter cette page"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Lignes"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Les lignes apparaissent ici une fois qu'une réception de bon de commande a été comptabilisée, et uniquement pour les quantités non déjà autorisées sur un autre retour fournisseur. Utilisez Ajouter un article de ligne pour un retour en aveugle."+msgstr "Les lignes apparaissent ici une fois qu'une réception de bon de commande a été comptabilisée, et uniquement pour les quantités non déjà autorisées sur un autre retour fournisseur. Utilisez Ajouter une ligne d'article pour un retour en aveugle."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Les lignes apparaissent ici une fois qu'une expédition de commande client a été comptabilisée, et uniquement pour les quantités non déjà autorisées sur un autre RMA. Utilisez Ajouter article de ligne pour un retour en aveugle."@@ -10441,6 +10594,12 @@ msgstr "Description longue"msgid "Longitude"msgstr "Longitude"+msgid "Look ahead (weeks)"+msgstr "Horizon prévisionnel (semaines)"++msgid "Look back (weeks)"+msgstr "Historique (semaines)"+msgid "Looks empty here"msgstr "Ça semble vide ici"@@ -10493,7 +10652,7 @@ msgid "Machine"msgstr "Machine"msgid "Machine Costs"-msgstr "Coûts de machine"+msgstr "Coûts Machine"msgid "Machine Hours"msgstr "Heures de machine"@@ -10570,6 +10729,12 @@ msgstr "Type de maintenance"msgid "Make"msgstr "Fabriquer"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "Fabriquer {quantity}"+msgid "Make Active"msgstr "Rendre actif"@@ -10746,7 +10911,7 @@ msgid "Marks the person off for every day in the range. They won't be scheduledmsgstr "Marque la personne comme absente pour chaque jour de la plage. Ils ne seront pas programmés pendant leur absence."msgid "Markup by Category"-msgstr "Majoration par catégorie"+msgstr "Majoration par Catégorie"msgid "Markup Percent"msgstr "Pourcentage de majoration"@@ -10847,6 +11012,9 @@ msgstr "Article de matière"msgid "Material Planning"msgstr "Planification des matériaux"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "La planification des matières n'affiche que les actions et les ordres suggérés dus dans ce nombre de jours à partir d'aujourd'hui, afin que les besoins éloignés restent hors du chemin jusqu'à ce qu'ils deviennent pertinents. L'horizon de planification propre de l'article remplace cette valeur par défaut."+msgid "Material Properties"msgstr "Propriétés des matériaux"@@ -11231,6 +11399,18 @@ msgstr "MRP (planification)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP s'exécute automatiquement toutes les 3 heures, mais vous pouvez l'exécuter manuellement ici."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP s'exécute automatiquement chaque jour à {time} ({timeZone}), mais vous pouvez l'exécuter manuellement ici."++msgid "MRP Schedule"+msgstr "Planification MRP"++msgid "MRP Suggestions"+msgstr "Suggestions MRP"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "La planification (MRP) ne propose de déplacer une commande existante que si sa date s'écarte de plus de ce nombre de jours. Les petits écarts sont laissés de côté pour que la liste de tâches reste calme."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Plusieurs ordres de fabrication peuvent s'exécuter sur ce procédé en même temps — par exemple une table laser, un four ou un bain de galvanoplastie"@@ -11498,9 +11678,6 @@ msgstr "Nouvelles conditions de paiement"msgid "New Picking List"msgstr "Nouvelle Liste de Prélèvement"-msgid "New PO"-msgstr "Nouveau BC"-msgid "New Price Override"msgstr "Nouvelle substitution de prix"@@ -12205,6 +12382,9 @@ msgstr "Aucune unité de stockage"msgid "No storage units or tracking numbers match."msgstr "Aucune unité de stockage ou numéro de suivi ne correspond."+msgid "No Supplier"+msgstr "Aucun fournisseur"+msgid "No suppliers yet"msgstr "Aucun fournisseur pour le moment"@@ -12555,6 +12735,9 @@ msgstr "Livraison à temps"msgid "Onboard your agent to Carbon"msgstr "Intégrez votre agent à Carbon"+msgid "Once a day"+msgstr "Une fois par jour"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Besoins d'ordres de fabrication ouverts plus les transferts en suspens hmsgid "Open jobs"msgstr "Ordres de fabrication ouverts"+msgid "Open Jobs"+msgstr "Ordres de fabrication Ouverts"+msgid "Open menu"msgstr "Ouvrir le menu"msgid "Open navigation"msgstr "Ouvrir la navigation"+msgid "Open Orders"+msgstr "Commandes Ouvertes"+msgid "Open payables by supplier and age"msgstr "Dettes fournisseurs ouvertes par fournisseur et ancienneté"@@ -12932,9 +13121,18 @@ msgstr "Commander {0} × {substitute} pour cet ordre de fabrication"msgid "Order {0} for this job"msgstr "Commander {0} pour cette tâche"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "Commander {quantity}"+msgid "Order by"msgstr "Commander par"+msgid "Order By"+msgstr "Trier par"+msgid "Order date"msgstr "Date de commande"@@ -13091,6 +13289,9 @@ msgstr "Propriétaire"msgid "Owner (cost center)"msgstr "Propriétaire (centre de coûts)"+msgid "Ownership"+msgstr "Propriétaire"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Responsable de : {0}"@@ -13569,9 +13770,36 @@ msgstr "Temps planifié"msgid "Planning"msgstr "Planification"+msgid "Planning action"+msgstr "Action de planification"++msgid "Planning horizon"+msgstr "Horizon de planification"++msgid "Planning Horizon"+msgstr "Horizon de Planification"++msgid "Planning Horizon (Days)"+msgstr "Horizon de Planification (Jours)"++msgid "Planning Horizon:"+msgstr "Horizon de Planification :"++msgid "Planning Ownership"+msgstr "Responsabilité de planification"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Les cycles de planification ont suggéré un réapprovisionnement jusqu'à un multiple entier de ce nombre."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "La planification n'affiche que les actions et les ordres suggérés dus dans ce nombre de jours. Laisser vide pour utiliser la valeur par défaut de la société, ou entrer 0 pour afficher tout pour cet article."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Limite inférieure de la planification pour une quantité de réapprovisionnement suggérée; différente du MOQ d'un fournisseur, qui se trouve sur l'enregistrement pièce-fournisseur."@@ -13980,6 +14208,9 @@ msgstr "Plan de projet"msgid "Project start"msgstr "Démarrage du projet"+msgid "Projected"+msgstr "Prévue"+msgid "Projected completion"msgstr "Achèvement projeté"@@ -14001,6 +14232,12 @@ msgstr "Rupture de stock projetée la semaine du {0}"msgid "Projected stock"msgstr "Stock projeté"+msgid "Projected stock by week"+msgstr "Stock projeté par semaine"++msgid "Projected stock is already below zero this week"+msgstr "Le stock projeté est déjà négatif cette semaine"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Rupture de stock prévue la semaine du {0}"@@ -14139,6 +14376,9 @@ msgstr "Bon de commande"msgid "Purchase Order Amount"msgstr "Montant du bon de commande"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Règle d'approbation de bon de commande"@@ -14166,6 +14406,9 @@ msgstr "Bons de commande"msgid "Purchase Orders and Planning"msgstr "Bons de commande et planification"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Bons de commande requis"@@ -14272,9 +14515,6 @@ msgstr "Qté"msgid "Qty On Hand"msgstr "Quantité Disponible"-msgid "Qty to Order"-msgstr "Qté à commander"-msgid "Qty. Complete"msgstr "Qté. Complète"@@ -14568,6 +14808,9 @@ msgstr "Prêt pour devis"msgid "ready to keep or revert"msgstr "prêt à conserver ou à revenir en arrière"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Les commandes réelles consomment d'abord la prévision de besoins de leur propre semaine, puis celles des semaines antérieures et ultérieures dans la fenêtre de la société, de sorte que la prévision et les besoins réels ne sont jamais planifiés ensemble pour les mêmes unités."+msgid "Real-time inventory and shop-floor visibility"msgstr "Visibilité en temps réel de l'inventaire et de l'atelier"@@ -14880,9 +15123,15 @@ msgstr "Contrôle de lancement"msgid "Release Job"msgstr "Lancer le travail"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Lancer les ordres de fabrication"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Libéré"@@ -15034,6 +15283,9 @@ msgstr "Rendu de l'aperçu de l'étiquette..."msgid "Reopen"msgstr "Rouvrir"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Réorganiser"@@ -15221,6 +15473,12 @@ msgstr "Nécessite une réparation"msgid "Requires staffing"msgstr "Nécessite du personnel"+msgid "Reschedule tolerance"+msgstr "Tolérance de reprogrammation"++msgid "Reschedule Tolerance"+msgstr "Tolérance de reprogrammation"+msgid "Reserve floor"msgstr "Plancher de réserve"@@ -15279,6 +15537,12 @@ msgstr "ressources"msgid "Resources"msgstr "Ressources"+msgid "Responsible employee"+msgstr "Employé responsable"++msgid "Responsible Employee"+msgstr "Employé responsable"+msgid "Restock"msgstr "Réapprovisionnement"@@ -15654,6 +15918,9 @@ msgstr "ID de passage"msgid "Run month-end close and standard reconciliations"msgstr "Exécuter la clôture de fin de mois et les rapprochements standard"+msgid "Run MRP"+msgstr "Exécuter le MRP"+msgid "Run payment batches and track aging"msgstr "Exécuter des lots de paiement et suivre l'ancienneté"@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "Session verrouillée"msgid "Set a customer on this return to add from a shipment."-msgstr "Définissez un client sur ce retour pour ajouter depuis une expédition."+msgstr "Définissez un client sur ce retour pour ajouter à partir d'une expédition."msgid "Set a supplier on this return to add from a receipt."msgstr "Définir un fournisseur sur ce retour pour ajouter à partir d'une réception."@@ -17243,6 +17510,9 @@ msgstr "Démarrer"msgid "Start {0} Day Free Trial"msgstr "Commencer l'essai gratuit de {0} jours"+msgid "Start By"+msgstr "À partir de"+msgid "Start counting"msgstr "Commencer le comptage"@@ -17386,6 +17656,9 @@ msgstr "Les étapes sont construites indépendamment, puis assemblées en une semsgid "Still dark out on the floor."msgstr "Toujours sombre à l'atelier."+msgid "Stock Availability"+msgstr "Disponibilité du stock"+msgid "Stock movement corrected"msgstr "Mouvement de stock corrigé"@@ -17624,6 +17897,15 @@ msgstr "Suggérer une correspondance"msgid "Suggest with AI"msgstr "Suggérer avec l'IA"+msgid "Suggested Jobs"+msgstr "Ordres de fabrication Suggérés"++msgid "Suggested Orders"+msgstr "Commandes Suggérées"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Les ordres suggérés requis après l'horizon de planification de cet article. Étendre l'horizon pour les inclure."+msgid "Suggested orders you haven't placed yet."msgstr "Commandes suggérées que vous n'avez pas encore passées."@@ -17874,8 +18156,8 @@ msgstr "Synchroniser"msgid "Sync Activity"msgstr "Activité de synchronisation"-msgid "sync off"-msgstr "synchronisation désactivée"+msgid "Sync Off"+msgstr "Synchronisation désactivée"msgid "Sync operation"msgstr "Opération de synchronisation"@@ -18642,6 +18924,9 @@ msgstr "Le pourcentage de remise en trésorerie. Utilisez 0 pour aucune remise."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "L'ensemble d'autorisations que les nouveaux employés de ce type reçoivent automatiquement; la modification ici change uniquement le modèle pour les embauches futures - les employés existants conservent ce qu'ils ont sauf s'ils sont explicitement mis à jour en masse."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "La personne à qui l'action de planification est attribuée : le propriétaire de l'article sur ce site, sinon celui du groupe d'articles, sinon celui du site, sinon la valeur par défaut de la société."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Les usines, entrepôts et sites où se trouvent votre travail et vos stocks"@@ -18663,6 +18948,9 @@ msgstr "Les procédés que ce poste de travail peut exécuter ; apparaît dans lmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "Le fournisseur n'offre pas de cibles de dimension. Activez d'abord la fonctionnalité chez le fournisseur (par exemple, catégories de suivi, suivi des classes ou champs)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Les points d'arrêt de quantité à laquelle cette ligne est tarifée; chaque colonne porte son propre prix par unité pour la négociation acheteur-fournisseur et la conversion en documents aval."@@ -18991,6 +19279,9 @@ msgstr "Ces écritures de journal sont encore Brouillon, de sorte que leurs débmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Ces opérations utilisent un procédé avec plusieurs fournisseurs. Choisissez un fournisseur pour chacune."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Ces ordres n'ont pas pu être chargés. Fermer et rouvrir pour réessayer."+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."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Tolérance (+/-)"+msgid "Tolerance (days)"+msgstr "Tolérance (jours)"+msgid "Tomorrow"msgstr "Demain"@@ -19847,8 +20141,8 @@ msgstr "Annuler"msgid "Ungroup"msgstr "Dégrouper"-msgid "unhealthy"-msgstr "malsain"+msgid "Unhealthy"+msgstr "Malsain"msgid "Uninstall"msgstr "Désinstaller"@@ -20936,6 +21230,9 @@ msgstr "Quand {name} change"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Quand la durée de conservation d'un produit fini est définie sur Calculée, choisissez quelles entrées consommées alimentent le calcul."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Quand une commande client ou un ordre de fabrication arrive dans une semaine sans prévision restante, elle prélève la prévision des semaines proches au lieu de s'ajouter à celle-ci. Définissez les deux à 0 pour équilibrer uniquement dans la même semaine."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Quand un numéro de série ou un lot de production expire, et ce qui se passe en cas d'utilisation après — une politique de société peut Avertir, Bloquer, ou Bloquer avec remplacement."@@ -21128,6 +21425,9 @@ msgstr "Qui reçoit une formation sur quoi, dans quel format. Votre rôle : protmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Qui doit approuver les devis, les commandes et les achats — et quand"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Qui possède les actions de planification du MRP. Les sites héritent de la valeur par défaut de la société ; les groupes d'articles héritent de celle de leur site. L'affectation la plus spécifique prime, et chaque article peut la remplacer sur son onglet Planification."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Qui devrait recevoir des notifications pour les interventions de maintenance ?"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 604ef07b6b..662e71d31a 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# पंक्ति इस कंपनी के बmsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# पंक्ति इस कंपनी के बाहर डेटा से जुड़ी है, इसलिए इसे बैकअप नहीं किया जा सकता। इसे छोड़ने से सब कुछ और बैकअप हो जाता है।} other {# पंक्तियाँ इस कंपनी के बाहर डेटा से जुड़ी हैं, इसलिए उन्हें बैकअप नहीं किया जा सकता। उन्हें छोड़ने से सब कुछ और बैकअप हो जाता है।}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# सप्ताह} other {# सप्ताह}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {योजनाकार इस घटक को एक कठोर शरीर मानता है — निर्देशों में एक चरण। योजना को पुनः चलाएं और लागू करें।} other {योजनाकार इन # घटकों को एक कठोर शरीर मानता है — निर्देशों में एक चरण। योजना को पुनः चलाएं और लागू करें।}}"@@ -107,6 +111,10 @@ msgstr "{0} को हटाया नहीं जा सकता क्योmsgid "{0} cells with deltas"msgstr "{0} अंतर वाली कोशिकाएँ"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} उपयोग किया गया"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} मान"msgid "{0} values missing"msgstr "{0} मान गायब हैं"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} को {name} के रूप में सहेजा जाएगा"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# शेष राशि वाला खाता}msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# कोर्स} other {# कोर्स}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# अधिक {fenceLabel} के बाद} other {# अधिक {fenceLabel} के बाद}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# बैच विघटित करें} other {# बैच विघटित करें}}"@@ -340,6 +356,9 @@ msgstr "{days}d"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo} यह आपके लेजर में पोस्ट करता है, इसलिए Carbon इसे पुश नहीं करता है। आपकी सहेजी गई पसंद को इस बात के मामले में रखा जाता है कि यह बदल जाए।"+msgid "{dismissed} dismissed"+msgstr "{dismissed} खारिज किया गया"+msgid "{done} of {total} phases complete"msgstr "{done} में से {total} चरण पूर्ण"@@ -360,6 +379,9 @@ msgstr "और {hiddenCount}: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} सम्मिलित किया गया, {updated} अपडेट किया गया, {0} को ठीक करने की आवश्यकता है, {1} छोड़ा गया।"+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# दिन} other {# दिन}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# लाइन} other {# लाइनें}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# चरण बचा} other {# चरण बmsgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} संसाधन · {reservationCount} आरक्षण · {jobCount} जॉब"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} अनुमतियाँ"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {पहले # शेष आवशmsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} को शेड्यूल नहीं किया जा सकता"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} जॉब अपडेट किए गए"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} अपलोड हो गया — दस्तावेज़ से फ़ील्ड भर दिए गए हैं।"@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 ऑपरेशन"+msgid "0 suggests a move for any date difference."+msgstr "0 किसी भी तारीख के अंतर के लिए स्थानांतरण का सुझाव देता है।"+msgid "0-4 weeks"msgstr "0-4 सप्ताह"@@ -518,9 +543,6 @@ msgstr "1 ड्राफ्ट जर्नल प्रविष्टि"msgid "1 job created"msgstr "1 नौकरी बनाई गई"-msgid "1 job updated"-msgstr "1 नौकरी अपडेट की गई"-msgid "1 part skipped — it already has an open job"msgstr "1 पार्ट छोड़ा गया — इसके पास पहले से एक खुला जॉब है"@@ -530,6 +552,9 @@ msgstr "1 पार्ट छोड़ा गया — कुछ भी बनmsgid "1 problem — not published"msgstr "1 समस्या — प्रकाशित नहीं"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 खरीद = {conversionFactor} इन्वेंटरी"+msgid "1 suggested batch"msgstr "1 सुझाया गया बैच"@@ -542,6 +567,9 @@ msgstr "12 मासिक अवधियाँ"msgid "13+ weeks"msgstr "13+ सप्ताह"+msgid "1st Negative On Hand"+msgstr "1st नकारात्मक स्टॉक"+msgid "1Y"msgstr "1 वर्ष"@@ -1082,6 +1110,9 @@ msgstr "एक चरण को एक नाम की आवश्यकताmsgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "एक वर्क सेंटर या ऑपरेटर की एक संग्रहीत बुकिंग एक ऑपरेशन की रखी गई समय अवधि के लिए — एक शेड्यूलिंग रन का मूर्त आउटपुट, और जो पूर्वानुमान में दिखाई देता है।"+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "एक सुझाव जो MRP प्रत्येक रन के बाद लिखता है: नई आपूर्ति के लिए ऑर्डर करें या निर्माण करें, या किसी खुली क्रय आदेश पंक्ति या जॉब को तेज़ करें, स्थगित करें, बढ़ाएं, घटाएं या रद्द करें। इसे योजना पृष्ठ से लागू करें, इसे खारिज करें, या इसे असाइन करें।"+msgid "A supplier contact and location are optional"msgstr "आपूर्तिकर्ता संपर्क और स्थान वैकल्पिक हैं"@@ -2006,6 +2037,12 @@ msgstr "इस जॉब की एक प्रक्रिया इस बैmsgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "एक ऑपरेशन की वर्क सेंटर की कतार में स्थिति — वह क्रम जिसमें फ्लोर काम लेता है। इंजन इसे प्लेसमेंट क्रम से संख्या देता है (सबसे पहली अनुमानित शुरुआत पहले); वर्क सेंटर बोर्ड पर कार्ड्स को पुनः क्रमित करना तारीख बदले बिना इसे निरस्त करता है।"+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Onshape से कनेक्ट करते समय एक अप्रत्याशित त्रुटि हुई। एकीकरण सेटिंग्स को सहेजें और फिर से कोशिश करें।"@@ -2167,6 +2204,9 @@ msgstr "मूल्य निर्धारण नियम लागू कmsgid "Apply Rules On Top"msgstr "शीर्ष पर नियम लागू करें"+msgid "Apply Suggested Changes"+msgstr "सुझाए गए परिवर्तन लागू करें"+msgid "Apply suggestions"msgstr "सुझाव लागू करें"@@ -2824,6 +2864,9 @@ msgstr "को असाइन करें"msgid "Assign to Groups"msgstr "समूहों को असाइन करें"+msgid "Assign to Me"+msgstr "मुझे असाइन करें"+msgid "Assigned"msgstr "नियुक्त"@@ -2836,6 +2879,9 @@ msgstr "मुझे असाइन किया गया"msgid "Assignee"msgstr "असाइनी"+msgid "Assignees"+msgstr "असाइनियां"+msgid "Assignment"msgstr "असाइनमेंट"@@ -3491,12 +3537,18 @@ msgstr "परिवर्तन सूचना को रद्द करेmsgid "Cancel Job"msgstr "नौकरी रद्द करें"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "ऑर्डर रद्द करें"msgid "Cancel Purchase Order"msgstr "क्रय आदेश रद्द करें"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "रिटर्न रद्द करें"@@ -3548,6 +3600,12 @@ msgstr "आइटम आईडी के बिना पार्ट्स बmsgid "Cannot place order - no supplier associated with this item"msgstr "इस आइटम के साथ कोई आपूर्तिकर्ता जुड़ा नहीं है - ऑर्डर नहीं दे सकते"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "ऑर्डर नहीं दिया जा सकता — {count} आइटम का कोई आपूर्तिकर्ता नहीं है"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "ऑर्डर नहीं दिया जा सकता — 1 आइटम का कोई आपूर्तिकर्ता नहीं है"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "पोस्ट नहीं कर सकते — शिपमेंट में समाप्त ट्रैक किए गए इकाइयां हैं।"@@ -3753,6 +3811,9 @@ msgstr "प्रकार बदलें"msgid "Changed By"msgstr "द्वारा परिवर्तित"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "केवल इस दृश्य के लिए बदला गया। आइटम की योजना क्षितिज अपडेट नहीं की गई है।"+msgid "Changelog"msgstr "परिवर्तन लॉग"@@ -3853,6 +3914,9 @@ msgstr "इस रिटर्न में पंक्तियाँ कैmsgid "Choose what appears on the printed job traveler."msgstr "मुद्रित जॉब ट्रैवलर पर क्या दिखाई दे, इसे चुनें।"+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "चुनें कि MRP अपने आप कब पुनर्गणना करेगा। आप योजना पृष्ठों पर किसी भी समय Recalculate के साथ इसे स्वयं चला सकते हैं।"+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "चुनें कि आइटम, कोटेशन और जॉब पर बिल ऑफ मैटेरियल एक्सप्लोरर प्रत्येक पंक्ति को इसके विवरण या आइटम ID के साथ दिखाएगा।"@@ -4068,6 +4132,9 @@ msgstr "कंपनियां"msgid "Company"msgstr "कंपनी"+msgid "Company default"+msgstr "कंपनी डिफ़ॉल्ट"+msgid "Company group"msgstr "कंपनी समूह"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "दस्तावेज़ नहीं पढ़ा जा सका: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "जारी नहीं कर सके {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "विभाग बनाया गया"msgid "Created failure mode"msgstr "विफलता मोड बनाया गया"+msgid "Created from planning"+msgstr "योजना से बनाया गया"+msgid "Created gauge type"msgstr "गेज प्रकार बनाया गया"@@ -5671,6 +5743,15 @@ msgstr "दशमलव स्थान"msgid "Declining balance"msgstr "ह्रासमान शेष"+msgid "Decrease"+msgstr "घटाएं"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "गहरी रात में, {name}।"@@ -5737,6 +5818,9 @@ msgstr "उपकरण और सुविधा रखरखाव के लmsgid "Default GL expense account for periodic depreciation runs."msgstr "आवधिक मूल्यह्रास रन के लिए डिफ़ॉल्ट सामान्य खाता बही व्यय खाता।"+msgid "Default horizon (days)"+msgstr "डिफ़ॉल्ट क्षितिज (दिन)"+msgid "Default Method"msgstr "डिफ़ॉल्ट विधि"@@ -5788,6 +5872,15 @@ msgstr "डिफ़ॉल्ट उपयोगी जीवन जो इसmsgid "Defaults"msgstr "डिफ़ॉल्ट"+msgid "Defer"+msgstr "स्थगित करें"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "आस्थगित कर व्यय"@@ -6368,6 +6461,9 @@ msgstr "खोज"msgid "Dismiss"msgstr "खारिज करें"+msgid "Dismissed"+msgstr "खारिज किया गया"+msgid "Dispatch"msgstr "रखरखाव कार्य"@@ -6744,6 +6840,9 @@ msgstr "प्रत्येक आपूर्तिकर्ता की बmsgid "Each, lb, ft…"msgstr "प्रत्येक, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "पहले के सप्ताह सबसे पहले उपयोग किए जाते हैं।"+msgid "Earliest operation start"msgstr "सबसे पहले संचालन शुरू"@@ -7503,6 +7602,9 @@ msgstr "ईवेंट प्रकार"msgid "Events"msgstr "घटनाएं"+msgid "Every 3 hours"+msgstr "हर 3 घंटे में"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "हर कंपनी-स्कोप्ड रिकॉर्ड। साख, एकीकरण टोकन और वेबहुक कभी शामिल नहीं होते हैं।"@@ -7635,6 +7737,15 @@ msgstr "अपेक्षित रसीद"msgid "Expected Receipt Date"msgstr "अपेक्षित प्राप्ति तारीख"+msgid "Expedite"+msgstr "तेज़ी से करें"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "ग्राहक शेष राशि के लिए व्यय खाता जो प्राप्य खाते समझौते पर अनिर्धारक के रूप में लिखा गया है"@@ -8112,12 +8223,18 @@ msgstr "गणना अपडेट करने में विफल"msgid "Failed to update item cost"msgstr "आइटम लागत अपडेट करने में विफल"+msgid "Failed to update job"+msgstr "जॉब को अपडेट करने में विफल"+msgid "Failed to update lead times"msgstr "लीड टाइम अपडेट करने में विफल"msgid "Failed to update opportunity with purchase order"msgstr "क्रय आदेश के साथ अवसर अपडेट करने में विफल"+msgid "Failed to update purchase order line"+msgstr "क्रय आदेश पंक्ति को अपडेट करने में विफल"+msgid "Failed to update quote line"msgstr "कोटेशन पंक्ति अपडेट करने में विफल"@@ -8315,6 +8432,9 @@ msgstr "पहला नाम"msgid "First Operation"msgstr "पहली ऑपरेशन"+msgid "First week the projected stock goes below zero"+msgstr "पहला सप्ताह जब प्रक्षेपित स्टॉक शून्य से नीचे चला जाता है"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "स्थिर संपत्ति"@@ -8381,6 +8501,12 @@ msgstr "किसी भी चीज़ के लिए। वे सहीmsgid "Forecast"msgstr "पूर्वानुमान"+msgid "Forecast consumption"+msgstr "पूर्वानुमान की खपत"++msgid "Forecast Consumption"+msgstr "पूर्वानुमान खपत"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "पूर्वानुमान विधि: <0>{0}</0>। यह पंक्ति कार्यरत जॉब से व्युत्पन्न नहीं की गई थी, इसलिए कोई मूल स्रोत उपलब्ध नहीं है।"@@ -8829,7 +8955,7 @@ msgstr "ऐसे ऑपरेशन हैं जिन्हें शेडmsgid "Headers"msgstr "हेडर"-msgid "healthy"+msgid "Healthy"msgstr "स्वस्थ"msgid "Help"@@ -8979,6 +9105,9 @@ msgstr "गणना की तारीख के बाद कितने दmsgid "How many days after the calculation date the full amount is due."msgstr "गणना की तारीख के बाद कितने दिनों में पूरी राशि देय है।"+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "एक खुला ऑर्डर आवश्यक तारीख से कितने दिन आगे आ सकता है, इससे पहले कि MRP इसे स्थानांतरित करने का सुझाव दे। सेटिंग्स → योजना में सेट करें; डिफ़ॉल्ट 7 दिन है।"+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "यह ग्राहक को चालान तारीख से भुगतान करने के लिए कितने दिन दिए जाते हैं; ग्राहक चालान पर डिफ़ॉल्ट नियत तिथि निर्धारित करता है।"@@ -9253,6 +9382,9 @@ msgstr "इस चरण में"msgid "In use"msgstr "उपयोग में"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "आपकी कंपनी के समय क्षेत्र ({companyTimeZone}) में।"+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "अपनी Enterprise सेटिंग्स में Developer के अंतर्गत, निजी OAuth एप्लिकेशन की अनुमतियों को संपादित करें ताकि « Application can write to your documents » को शामिल किया जा सके, फिर एकीकरण सेटिंग्स को फिर से सहेजें।"@@ -9265,9 +9397,6 @@ msgstr "इन-ऐप सूचनाएं हमेशा दी जातीmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "इन-ऐप सूचनाएं हमेशा दी जाती हैं। चुनें कि कौन से विषय आपको ईमेल द्वारा भी पहुंचें।"-msgid "inactive"-msgstr "निष्क्रिय"-msgid "Inactive"msgstr "निष्क्रिय"@@ -9325,6 +9454,15 @@ msgstr "इनकोटर्म"msgid "Incoterm Location"msgstr "इनकोटर्म स्थान"+msgid "Increase"+msgstr "बढ़ाएं"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "अप्रत्यक्ष"@@ -9364,6 +9502,9 @@ msgstr "समूह से विरासत में मिली: क्यmsgid "Inherited from the parent group."msgstr "मूल समूह से विरासत में मिला।"+msgid "inherits {inheritedName}"+msgstr "{inheritedName} से विरासत"+msgid "Input"msgstr "इनपुट"@@ -9893,6 +10034,9 @@ msgstr "नौकरी प्राथमिकता"msgid "Job readable"msgstr "नौकरी पठनीय"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "जॉब ट्रैवलर"@@ -10108,9 +10252,15 @@ msgstr "अंतिम उपयोग"msgid "Late in the evening, {name}."msgstr "शाम को देर में, {name}।"+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "बाद के सप्ताह तब उपयोग किए जाते हैं जब पहले वाले समाप्त हो जाते हैं।"+msgid "Latest operation end"msgstr "नवीनतम ऑपरेशन अंत"+msgid "Latest Order Date"+msgstr "नवीनतम आदेश तारीख"+msgid "Latitude"msgstr "अक्षांश"@@ -10153,6 +10303,9 @@ msgstr "अगले रिवीजन को स्वचालित रूmsgid "Leave empty for exact match"msgstr "सटीक मिलान के लिए खाली छोड़ें"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "MRP द्वारा योजनाबद्ध सब कुछ दिखाने के लिए खाली छोड़ें, या 0 दर्ज करें।"+msgid "Leave this page"msgstr "इस पृष्ठ को छोड़ें"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "पंक्तियाँ"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "एक बार क्रय आदेश की प्राप्ति पोस्ट किए जाने के बाद यहां पंक्तियां दिखाई देंगी, और केवल उन मात्राओं के लिए जो पहले से किसी अन्य आपूर्तिकर्ता रिटर्न पर अधिकृत नहीं हैं। एक अंधी रिटर्न के लिए पंक्ति आइटम जोड़ें का उपयोग करें।"+msgstr "एक क्रय आदेश प्राप्ति पोस्ट किए जाने के बाद पंक्तियां यहां दिखाई देती हैं, और केवल उन मात्राओं के लिए जो किसी अन्य आपूर्तिकर्ता रिटर्न पर पहले से अधिकृत नहीं हैं। ब्लाइंड रिटर्न के लिए पंक्ति आइटम जोड़ें का उपयोग करें।"msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "पंक्तियाँ यहाँ दिखाई देती हैं जब विक्रय आदेश की शिपमेंट पोस्ट की जाती है, और केवल उन मात्राओं के लिए जो पहले से किसी अन्य RMA पर अधिकृत नहीं हैं। एक अंधी रिटर्न के लिए पंक्ति मद जोड़ें का उपयोग करें।"@@ -10441,6 +10594,12 @@ msgstr "लंबा विवरण"msgid "Longitude"msgstr "देशांतर"+msgid "Look ahead (weeks)"+msgstr "आगे देखें (सप्ताह)"++msgid "Look back (weeks)"+msgstr "पीछे देखें (सप्ताह)"+msgid "Looks empty here"msgstr "यहाँ खाली लगता है"@@ -10570,6 +10729,12 @@ msgstr "रखरखाव प्रकार"msgid "Make"msgstr "बनाएं"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "{quantity} बनाएं"+msgid "Make Active"msgstr "सक्रिय करें"@@ -10847,6 +11012,9 @@ msgstr "सामग्री आइटम"msgid "Material Planning"msgstr "सामग्री योजना"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "सामग्री योजना केवल आज से इतने दिनों के भीतर देय कार्रवाई और सुझाए गए आदेश दिखाती है, ताकि दूर की आवश्यकताएं तब तक दूर रहें जब तक वे महत्वपूर्ण न हों। आइटम की अपनी योजना क्षितिज इस डिफ़ॉल्ट को ओवरराइड करती है।"+msgid "Material Properties"msgstr "सामग्री गुण"@@ -11231,6 +11399,18 @@ msgstr "MRP (योजना)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP हर 3 घंटे में स्वचालित रूप से चलता है, लेकिन आप इसे यहां मैन्युअल रूप से चला सकते हैं।"+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP हर दिन {time} ({timeZone}) पर स्वचालित रूप से चलता है, लेकिन आप इसे यहां मैन्युअली भी चला सकते हैं।"++msgid "MRP Schedule"+msgstr "MRP शेड्यूल"++msgid "MRP Suggestions"+msgstr "MRP सुझाव"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP एक मौजूदा आदेश को स्थानांतरित करने का सुझाव देता है केवल जब इसकी तारीख इतने दिनों से अधिक भिन्न हो। छोटे अंतराल को अकेला छोड़ा जाता है ताकि कार्यसूची शांत रहे।"+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "एक ही समय में इस प्रक्रिया पर कई जॉब चल सकती हैं — उदाहरण के लिए, एक लेजर टेबल, फर्नेस, या प्लेटिंग बाथ"@@ -11498,9 +11678,6 @@ msgstr "नई भुगतान शर्तें"msgid "New Picking List"msgstr "नई पिकिंग सूची"-msgid "New PO"-msgstr "नया PO"-msgid "New Price Override"msgstr "नया मूल्य ओवरराइड"@@ -12140,7 +12317,7 @@ msgid "No results found"msgstr "कोई परिणाम नहीं मिला"msgid "No returnable lines for this customer"-msgstr "इस ग्राहक के लिए कोई लौटाई जा सकने वाली पंक्तियां नहीं"+msgstr "इस ग्राहक के लिए कोई रिटर्न योग्य पंक्तियां नहीं"msgid "No returnable lines for this supplier"msgstr "इस आपूर्तिकर्ता के लिए कोई रिटर्न योग्य पंक्तियाँ नहीं"@@ -12205,6 +12382,9 @@ msgstr "कोई भंडारण इकाई नहीं"msgid "No storage units or tracking numbers match."msgstr "कोई भंडारण इकाई या ट्रैकिंग संख्या मेल नहीं खाती।"+msgid "No Supplier"+msgstr "कोई आपूर्तिकर्ता नहीं"+msgid "No suppliers yet"msgstr "अभी तक कोई आपूर्तिकर्ता नहीं"@@ -12555,6 +12735,9 @@ msgstr "समय पर डिलीवरी"msgid "Onboard your agent to Carbon"msgstr "अपने एजेंट को Carbon पर ऑनबोर्ड करें"+msgid "Once a day"+msgstr "दिन में एक बार"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "खुली नौकरी की मांग प्लस इस बmsgid "Open jobs"msgstr "खुली जॉबें"+msgid "Open Jobs"+msgstr "खुली जॉब्स"+msgid "Open menu"msgstr "मेनू खोलें"msgid "Open navigation"msgstr "नेविगेशन खोलें"+msgid "Open Orders"+msgstr "खुले आदेश"+msgid "Open payables by supplier and age"msgstr "आपूर्तिकर्ता और आयु के अनुसार खुली देय राशि"@@ -12932,9 +13121,18 @@ msgstr "इस जॉब के लिए {0} × {substitute} ऑर्डरmsgid "Order {0} for this job"msgstr "इस कार्य के लिए {0} ऑर्डर करें"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "{quantity} ऑर्डर करें"+msgid "Order by"msgstr "आदेश दें"+msgid "Order By"+msgstr "क्रमांकित करें"+msgid "Order date"msgstr "ऑर्डर तारीख"@@ -13091,6 +13289,9 @@ msgstr "स्वामी"msgid "Owner (cost center)"msgstr "स्वामी (लागत केंद्र)"+msgid "Ownership"+msgstr "स्वामित्व"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "स्वामित्व: {0}"@@ -13569,9 +13770,36 @@ msgstr "योजनाबद्ध समय"msgid "Planning"msgstr "योजना"+msgid "Planning action"+msgstr "योजना कार्रवाई"++msgid "Planning horizon"+msgstr "योजना क्षितिज"++msgid "Planning Horizon"+msgstr "योजना क्षितिज"++msgid "Planning Horizon (Days)"+msgstr "योजना क्षितिज (दिन)"++msgid "Planning Horizon:"+msgstr "योजना क्षितिज:"++msgid "Planning Ownership"+msgstr "योजना स्वामित्व"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "योजना राउंड इस संख्या के पूरे गुणज तक पुनः भरण का सुझाव दिया।"+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "योजना केवल इतने दिनों के भीतर देय कार्रवाई और सुझाए गए आदेश दिखाती है। कंपनी डिफ़ॉल्ट का उपयोग करने के लिए खाली छोड़ें, या इस आइटम के लिए सब कुछ दिखाने के लिए 0 दर्ज करें।"+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "सुझाए गए पुनः भरण मात्रा पर योजना की निचली सीमा; एक आपूर्तिकर्ता के MOQ से अलग, जो आपूर्तिकर्ता-भाग रिकॉर्ड पर रहता है।"@@ -13980,6 +14208,9 @@ msgstr "प्रोजेक्ट प्लान"msgid "Project start"msgstr "प्रोजेक्ट शुरुआत"+msgid "Projected"+msgstr "अनुमानित"+msgid "Projected completion"msgstr "अनुमानित पूर्णता"@@ -14001,6 +14232,12 @@ msgstr "{0} के सप्ताह में अनुमानित स्msgid "Projected stock"msgstr "अनुमानित स्टॉक"+msgid "Projected stock by week"+msgstr "सप्ताह के अनुसार प्रक्षेपित स्टॉक"++msgid "Projected stock is already below zero this week"+msgstr "प्रक्षेपित स्टॉक पहले से ही इस सप्ताह शून्य से नीचे है"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "सप्ताह {0} में अनुमानित स्टॉक आउट"@@ -14139,6 +14376,9 @@ msgstr "क्रय आदेश"msgid "Purchase Order Amount"msgstr "क्रय आदेश राशि"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "क्रय आदेश अनुमोदन नियम"@@ -14166,6 +14406,9 @@ msgstr "क्रय आदेश"msgid "Purchase Orders and Planning"msgstr "क्रय आदेश और योजना"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "क्रय आदेश आवश्यक हैं"@@ -14272,9 +14515,6 @@ msgstr "मात्रा"msgid "Qty On Hand"msgstr "हाथ में मात्रा"-msgid "Qty to Order"-msgstr "ऑर्डर करने की मात्रा"-msgid "Qty. Complete"msgstr "मात्रा पूर्ण"@@ -14568,6 +14808,9 @@ msgstr "कोटेशन के लिए तैयार"msgid "ready to keep or revert"msgstr "रखने या पूर्ववत् करने के लिए तैयार"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "वास्तविक ऑर्डर पहले अपने सप्ताह के लिए मांग पूर्वानुमान का उपयोग करते हैं, फिर कंपनी की विंडो के भीतर उससे पहले और बाद के सप्ताहों में, इसलिए पूर्वानुमान और वास्तविक मांग कभी भी एक ही इकाइयों के लिए दोनों योजनाबद्ध नहीं होते।"+msgid "Real-time inventory and shop-floor visibility"msgstr "रीयल-टाइम इन्वेंटरी और शॉप-फ्लोर दृश्यमानता"@@ -14880,9 +15123,15 @@ msgstr "नियंत्रण जारी करें"msgid "Release Job"msgstr "जॉब जारी करें"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "जॉब को जारी करें"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "जारी किया गया"@@ -15034,6 +15283,9 @@ msgstr "लेबल पूर्वावलोकन प्रस्तुतmsgid "Reopen"msgstr "फिर से खोलें"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "पुनः क्रमित करें"@@ -15116,7 +15368,7 @@ msgid "Reports"msgstr "रिपोर्ट"msgid "Reprice with current rules"-msgstr "वर्तमान नियमों के साथ फिर से मूल्य निर्धारण करें"+msgstr "वर्तमान नियमों के साथ पुनः मूल्य निर्धारण करें"#. placeholder {0}: format(repricedPrice)msgid "Repricing with today's rules and costs gives <0>{0}</0>."@@ -15221,6 +15473,12 @@ msgstr "मरम्मत की आवश्यकता है"msgid "Requires staffing"msgstr "स्टाफिंग आवश्यक है"+msgid "Reschedule tolerance"+msgstr "पुनर्निर्धारण सहिष्णुता"++msgid "Reschedule Tolerance"+msgstr "पुनर्निर्धारण सहनशीलता"+msgid "Reserve floor"msgstr "रिज़र्व फ़्लोर"@@ -15279,6 +15537,12 @@ msgstr "संसाधन"msgid "Resources"msgstr "संसाधन"+msgid "Responsible employee"+msgstr "जिम्मेदार कर्मचारी"++msgid "Responsible Employee"+msgstr "जिम्मेदार कर्मचारी"+msgid "Restock"msgstr "पुनः स्टॉक करें"@@ -15654,6 +15918,9 @@ msgstr "रन आईडी"msgid "Run month-end close and standard reconciliations"msgstr "महीने के अंत का बंद करना और मानक समन्वय चलाएं"+msgid "Run MRP"+msgstr "MRP चलाएं"+msgid "Run payment batches and track aging"msgstr "भुगतान बैच चलाएं और उम्र ट्रैक करें"@@ -16087,7 +16354,7 @@ msgid "Search by linear issue title..."msgstr "Linear समस्या शीर्षक द्वारा खोजें..."msgid "Search by receipt, PO, or item"-msgstr "प्राप्ति, PO, या आइटम द्वारा खोजें"+msgstr "प्राप्ति, PO या आइटम द्वारा खोजें"msgid "Search by shipment, sales order, or item"msgstr "शिपमेंट, विक्रय आदेश, या आइटम के अनुसार खोजें"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "ऑपरेशन चुनें"msgid "Select posted receipt lines from this supplier to return."-msgstr "इस आपूर्तिकर्ता से रिटर्न करने के लिए पोस्ट की गई प्राप्ति पंक्तियां चुनें।"+msgstr "इस आपूर्तिकर्ता से वापसी के लिए पोस्ट की गई प्राप्ति पंक्तियों को चुनें।"msgid "Select posted shipment lines to this customer to return."msgstr "इस ग्राहक को भेजी गई शिपमेंट पंक्तियों को रिटर्न के लिए चुनें।"@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "सत्र लॉक किया गया"msgid "Set a customer on this return to add from a shipment."-msgstr "इस रिटर्न पर एक ग्राहक सेट करें शिपमेंट से जोड़ने के लिए।"+msgstr "शिपमेंट से जोड़ने के लिए इस वापसी पर एक ग्राहक सेट करें।"msgid "Set a supplier on this return to add from a receipt."msgstr "प्राप्ति से जोड़ने के लिए इस रिटर्न पर एक आपूर्तिकर्ता सेट करें।"@@ -17243,6 +17510,9 @@ msgstr "शुरू करें"msgid "Start {0} Day Free Trial"msgstr "{0} दिन की निःशुल्क परीक्षण शुरू करें"+msgid "Start By"+msgstr "शुरू करें"+msgid "Start counting"msgstr "गिनती शुरू करें"@@ -17386,6 +17656,9 @@ msgstr "चरणों को अलग से बनाया जाता हmsgid "Still dark out on the floor."msgstr "अभी भी फर्श पर अंधकार है।"+msgid "Stock Availability"+msgstr "स्टॉक उपलब्धता"+msgid "Stock movement corrected"msgstr "स्टॉक आंदोलन सही किया गया"@@ -17624,6 +17897,15 @@ msgstr "मिलान सुझाएं"msgid "Suggest with AI"msgstr "एआई के साथ सुझाएं"+msgid "Suggested Jobs"+msgstr "सुझाई गई जॉब्स"++msgid "Suggested Orders"+msgstr "सुझाए गए आदेश"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "इस आइटम के योजना क्षितिज के बाद आवश्यक सुझाए गए आदेश। उन्हें शामिल करने के लिए क्षितिज को विस्तारित करें।"+msgid "Suggested orders you haven't placed yet."msgstr "सुझाए गए ऑर्डर जो आपने अभी तक नहीं दिए हैं।"@@ -17874,7 +18156,7 @@ msgstr "सिंक करें"msgid "Sync Activity"msgstr "सिंक गतिविधि"-msgid "sync off"+msgid "Sync Off"msgstr "सिंक बंद"msgid "Sync operation"@@ -18642,6 +18924,9 @@ msgstr "नकद छूट का प्रतिशत। कोई छूटmsgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "अनुमति सेट जो इस प्रकार के नए कर्मचारी स्वचालित रूप से प्राप्त करते हैं; यहाँ संपादन केवल भविष्य की भर्ती के लिए टेम्पलेट को बदलता है - मौजूदा कर्मचारी जो उनके पास है वह रखते हैं जब तक कि स्पष्ट रूप से बड़े पैमाने पर अद्यतन नहीं किया जाता।"+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "वह व्यक्ति जिसे योजना कार्रवाई असाइन की गई है: उस स्थान पर आइटम का स्वामी, अन्यथा आइटम समूह का, अन्यथा स्थान का, अन्यथा कंपनी का डिफ़ॉल्ट।"+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "वह संयंत्र, गोदाम, और साइटें जहां आपका काम और स्टॉक रहता है"@@ -18663,6 +18948,9 @@ msgstr "प्रक्रियाएँ जो यह वर्क सेंmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "प्रदाता कोई आयाम लक्ष्य प्रदान नहीं करता है। पहले प्रदाता में सुविधा सक्षम करें (जैसे ट्रैकिंग श्रेणियां, कक्षा ट्रैकिंग, या फ़ील्ड)।"+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "मात्रा विभाजन बिंदु जिन पर इस पंक्ति की कीमत है; प्रत्येक कॉलम क्रेता-आपूर्तिकर्ता बातचीत और डाउनस्ट्रीम दस्तावेजों में परिवर्तित करने के लिए अपनी स्वयं की प्रति-यूनिट कीमत रखता है।"@@ -18991,6 +19279,9 @@ msgstr "ये जर्नल प्रविष्टियां अभीmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "ये ऑपरेशन कई आपूर्तिकर्ताओं के साथ एक प्रक्रिया का उपयोग करते हैं। प्रत्येक के लिए एक आपूर्तिकर्ता चुनें।"+msgid "These orders could not be loaded. Close and reopen to try again."+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 "ये पार्ट्स इसके द्वारा प्रतिस्थापित किए जा रहे हैं। प्रत्येक नियम पुराने पार्ट पर सेट है; नियम बदलने के लिए इसे खोलें।"@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "सहनशीलता (+/-)"+msgid "Tolerance (days)"+msgstr "सहनशीलता (दिन)"+msgid "Tomorrow"msgstr "कल"@@ -19847,7 +20141,7 @@ msgstr "पूर्ववत करें"msgid "Ungroup"msgstr "अनग्रुप करें"-msgid "unhealthy"+msgid "Unhealthy"msgstr "अस्वस्थ"msgid "Uninstall"@@ -20936,6 +21230,9 @@ msgstr "जब {name} परिवर्तन होता है"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "जब किसी तैयार उत्पाद की शेल्फ लाइफ को गणना के लिए सेट किया जाता है, तो चुनें कि गणना को कौन सी उपयोग की गई इनपुट प्रदान करती हैं।"+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "जब एक विक्रय आदेश या जॉब एक ऐसे सप्ताह में आता है जिसमें कोई पूर्वानुमान शेष नहीं है, तो यह पास के सप्ताहों से पूर्वानुमान का उपयोग करता है बजाय इसके कि इसे शीर्ष पर गिना जाए। दोनों को 0 पर सेट करें केवल उसी सप्ताह के भीतर समायोजित करने के लिए।"+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "जब एक सीरियल या बैच समाप्त हो जाता है, और उपयोग के बाद क्या होता है — एक कंपनी नीति सतर्क, अवरुद्ध, या ब्लॉकविदअधिग्रहण हो सकती है।"@@ -21128,6 +21425,9 @@ msgstr "कौन किस पर प्रशिक्षण पाता हmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "किसे कोटेशन, आदेश, और क्रय को अनुमोदन करना है — और कब"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "MRP योजना कार्यों का मालिक कौन है। स्थान कंपनी डिफ़ॉल्ट से विरासत में लेते हैं; आइटम समूह अपने स्थान से विरासत में लेते हैं। सबसे विशिष्ट असाइनमेंट लागू होता है, और प्रत्येक आइटम अपने योजना टैब पर मान अधिरोप कर सकता है।"+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "रखरखाव कार्य के लिए सूचना कौन प्राप्त करे?"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex e4a7234529..ef1b8bd437 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# riga si collega ai dati al di fuori di questa Aziendamsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# riga si collega ai dati al di fuori di questa Azienda, quindi non può essere sottoposta a backup. Ignorarla fa il backup di tutto il resto.} other {# righe si collegano ai dati al di fuori di questa Azienda, quindi non possono essere sottoposte a backup. Ignorarle fa il backup di tutto il resto.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# settimana} other {# settimane}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {Il pianificatore tratta questo componente come un corpo rigido — un passo nelle istruzioni. Riesegui la pianificazione per applicare.} other {Il pianificatore tratta questi # componenti come un corpo rigido — un passo nelle istruzioni. Riesegui la pianificazione per applicare.}}"@@ -107,6 +111,10 @@ msgstr "{0} non può essere eliminato perché è ancora in uso da {where}. Modifmsgid "{0} cells with deltas"msgstr "{0} celle con delta"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} consumato"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} valori"msgid "{0} values missing"msgstr "{0} valori mancanti"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} verrà salvato come {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# conto con saldo} other {# conti con saldo}}"msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# corso} other {# corsi}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# altri dopo {fenceLabel}} other {# altri dopo {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Sciogli # lotto di produzione} other {Sciogli # lotti di produzione}}"@@ -340,6 +356,9 @@ msgstr "{days}g"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "${delegatedTo} pubblica questo nel tuo libro mastro, quindi Carbon non lo invia. La tua scelta salvata viene mantenuta nel caso in cui ciò cambi."+msgid "{dismissed} dismissed"+msgstr "{dismissed} scartati"+msgid "{done} of {total} phases complete"msgstr "{done} di {total} fasi completate"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} altri: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} inseriti, {updated} aggiornati, {0} richiedono correzione, {1} saltati."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# giorno} other {# giorni}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# riga} other {# righe}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# fase rimanente} other {# fasi rimanenti}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} risorse · {reservationCount} prenotazioni · {jobCount} ordini di produzione"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} autorizzazioni"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Mappa prima il # account richiestomsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} non può essere programmato"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} ordini di produzione aggiornati"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} caricato — campi compilati dal documento."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 operazioni"+msgid "0 suggests a move for any date difference."+msgstr "0 suggerisce uno spostamento per qualsiasi differenza di data."+msgid "0-4 weeks"msgstr "0-4 settimane"@@ -518,9 +543,6 @@ msgstr "1 riga di registrazione in bozza"msgid "1 job created"msgstr "1 processo creato"-msgid "1 job updated"-msgstr "1 processo aggiornato"-msgid "1 part skipped — it already has an open job"msgstr "1 parte saltata — ha già un processo aperto"@@ -530,6 +552,9 @@ msgstr "1 parte saltata — niente da produrre"msgid "1 problem — not published"msgstr "1 problema — non pubblicato"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Acquisto = {conversionFactor} Magazzino"+msgid "1 suggested batch"msgstr "1 lotto di produzione suggerito"@@ -542,6 +567,9 @@ msgstr "12 periodi mensili"msgid "13+ weeks"msgstr "13+ settimane"+msgid "1st Negative On Hand"+msgstr "1ª giacenza negativa"+msgid "1Y"msgstr "1 anno"@@ -1082,6 +1110,9 @@ msgstr "Un passaggio ha bisogno di un nome."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Una prenotazione memorizzata di un centro di lavoro o di un operatore per l'intervallo di tempo assegnato di un'operazione — il risultato materializzato di un'esecuzione della programmazione, e ciò che la Previsione disegna."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Una proposta che l'MRP scrive dopo ogni ciclo: ordinare o produrre nuova copertura, oppure accelerare, rimandare, aumentare, diminuire o annullare una riga di ordine di acquisto aperta o un ordine di produzione. Applicarla dalla pagina di pianificazione, scartarla o assegnarla."+msgid "A supplier contact and location are optional"msgstr "Un contatto fornitore e un'ubicazione sono opzionali"@@ -1506,7 +1537,7 @@ msgid "Add from library…"msgstr "Aggiungi dalla libreria…"msgid "Add from receipt"-msgstr "Aggiungi da entrata merci"+msgstr "Aggiungi da Entrata merci"msgid "Add from shipment"msgstr "Aggiungi da spedizione"@@ -2006,6 +2037,12 @@ msgstr "Un'operazione di questa commessa è in questo lotto"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "La posizione dell'operazione nella coda del suo centro di lavoro — l'ordine in cui l'officina raccoglie il lavoro. Il motore lo numera in base all'ordine di posizionamento (inizio previsto più vicino per primo); il riordinamento delle schede sulla lavagna dei Centri di lavoro la sovrascrive senza modificare le date."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Si è verificato un errore imprevisto durante la connessione a Onshape. Salva le impostazioni di integrazione per riprovare."@@ -2167,6 +2204,9 @@ msgstr "Applica regole di prezzo"msgid "Apply Rules On Top"msgstr "Applica regole in alto"+msgid "Apply Suggested Changes"+msgstr "Applica Cambiamenti Proposti"+msgid "Apply suggestions"msgstr "Applica proposte"@@ -2824,6 +2864,9 @@ msgstr "Assegna a"msgid "Assign to Groups"msgstr "Assegna ai Gruppi"+msgid "Assign to Me"+msgstr "Assegna a Me"+msgid "Assigned"msgstr "Assegnato"@@ -2836,6 +2879,9 @@ msgstr "Assegnato a me"msgid "Assignee"msgstr "Assegnatario"+msgid "Assignees"+msgstr "Assegnatari"+msgid "Assignment"msgstr "Incarico"@@ -3491,12 +3537,18 @@ msgstr "Annulla avviso di modifica"msgid "Cancel Job"msgstr "Annulla Lavoro"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Annulla ordine"msgid "Cancel Purchase Order"msgstr "Annulla ordine d'acquisto"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Annulla Reso"@@ -3548,6 +3600,12 @@ msgstr "Impossibile spostare al bucket Componenti senza ID articolo"msgid "Cannot place order - no supplier associated with this item"msgstr "Impossibile effettuare l'ordine - nessun fornitore associato a questo articolo"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Impossibile effettuare l'ordine — {count} articoli non hanno un fornitore"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Impossibile effettuare l'ordine — 1 articolo non ha un fornitore"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Impossibile registrare — la spedizione contiene entità tracciate scadute."@@ -3753,6 +3811,9 @@ msgstr "Cambia Tipo"msgid "Changed By"msgstr "Modificato da"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Modificato solo per questa vista. L'orizzonte di pianificazione dell'articolo non viene aggiornato."+msgid "Changelog"msgstr "Cronologia"@@ -3853,6 +3914,9 @@ msgstr "Scegli come aggiungere righe a questo reso."msgid "Choose what appears on the printed job traveler."msgstr "Scegli cosa appare sul cartellino di produzione stampato."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Scegli quando MRP ricalcola automaticamente. Puoi comunque eseguirlo manualmente in qualsiasi momento con Ricalcola nelle pagine di Pianificazione."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Scegli se l'explorer della distinta dei materiali su articoli, offerte e ordini di produzione etichetta ogni riga con la sua descrizione o il suo ID articolo."@@ -4068,6 +4132,9 @@ msgstr "Aziende"msgid "Company"msgstr "Azienda"+msgid "Company default"+msgstr "Azienda predefinita"+msgid "Company group"msgstr "Gruppo aziendale"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Non è stato possibile leggere il documento: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Non è stato possibile rilasciare {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "Reparto creato"msgid "Created failure mode"msgstr "Modalità di guasto creata"+msgid "Created from planning"+msgstr "Creato dalla pianificazione"+msgid "Created gauge type"msgstr "Tipo di strumento creato"@@ -5671,6 +5743,15 @@ msgstr "Posizioni Decimali"msgid "Declining balance"msgstr "Quote decrescenti"+msgid "Decrease"+msgstr "Diminuisci"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Nel bel mezzo della notte, {name}."@@ -5737,6 +5818,9 @@ msgstr "Conto spesa predefinito per la manutenzione di impianti e strutture."msgid "Default GL expense account for periodic depreciation runs."msgstr "Conto spesa predefinito per i cicli di ammortamento periodici."+msgid "Default horizon (days)"+msgstr "Orizzonte predefinito (giorni)"+msgid "Default Method"msgstr "Metodo Predefinito"@@ -5788,6 +5872,15 @@ msgstr "Vita utile predefinita che viene precompilata su nuovi beni in questa clmsgid "Defaults"msgstr "Impostazioni predefinite"+msgid "Defer"+msgstr "Rinvia"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Imposte Differite - Spese"@@ -6368,6 +6461,9 @@ msgstr "Scoperta"msgid "Dismiss"msgstr "Ignora"+msgid "Dismissed"+msgstr "Scartato"+msgid "Dispatch"msgstr "Intervento di manutenzione"@@ -6744,6 +6840,9 @@ msgstr "Le operazioni esterne di ogni fornitore da ogni ordine di produzione venmsgid "Each, lb, ft…"msgstr "Ogni, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "Le settimane precedenti vengono consumate per prime."+msgid "Earliest operation start"msgstr "Inizio operazione anticipato"@@ -7503,6 +7602,9 @@ msgstr "Tipo di Evento"msgid "Events"msgstr "Eventi"+msgid "Every 3 hours"+msgstr "Ogni 3 ore"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Tutti i record dell'azienda. Credenziali, token di integrazione e webhook non sono mai inclusi."@@ -7635,6 +7737,15 @@ msgstr "Ricevimento Previsto"msgid "Expected Receipt Date"msgstr "Data di Ricezione Prevista"+msgid "Expedite"+msgstr "Anticipa"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Conto di Spesa per i saldi dei Clienti cancellati come inesigibili alla regolazione dei Crediti verso clienti"@@ -8112,12 +8223,18 @@ msgstr "Impossibile aggiornare il conteggio"msgid "Failed to update item cost"msgstr "Impossibile aggiornare il costo dell'articolo"+msgid "Failed to update job"+msgstr "Impossibile aggiornare l'ordine di produzione"+msgid "Failed to update lead times"msgstr "Impossibile aggiornare i lead time"msgid "Failed to update opportunity with purchase order"msgstr "Impossibile aggiornare l'opportunità con l'ordine di acquisto"+msgid "Failed to update purchase order line"+msgstr "Impossibile aggiornare la riga dell'ordine di acquisto"+msgid "Failed to update quote line"msgstr "Impossibile aggiornare la riga offerta"@@ -8315,6 +8432,9 @@ msgstr "Nome"msgid "First Operation"msgstr "Prima Operazione"+msgid "First week the projected stock goes below zero"+msgstr "Prima settimana in cui la giacenza proiettata scende sotto zero"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Immobilizzazione"@@ -8381,6 +8501,12 @@ msgstr "per qualsiasi cosa. Porteranno la persona giusta."msgid "Forecast"msgstr "Previsione"+msgid "Forecast consumption"+msgstr "Consumo della previsione"++msgid "Forecast Consumption"+msgstr "Consumo Previsione"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Metodo di previsione: <0>{0}</0>. Questa riga non è stata derivata da ordini di produzione attivi, quindi nessuna fonte padre è disponibile."@@ -8829,8 +8955,8 @@ msgstr "Ha operazioni che non possono essere programmate"msgid "Headers"msgstr "Intestazioni"-msgid "healthy"-msgstr "sano"+msgid "Healthy"+msgstr "Sano"msgid "Help"msgstr "Aiuto"@@ -8979,6 +9105,9 @@ msgstr "Quanti giorni dopo la data di calcolo lo sconto per pagamento anticipatomsgid "How many days after the calculation date the full amount is due."msgstr "Quanti giorni dopo la data di calcolo l'importo completo è dovuto."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Quanti giorni un ordine aperto può arrivare dalla data in cui è necessario prima che l'MRP suggerisca di spostarlo. Impostare in Impostazioni → Pianificazione; il valore predefinito è 7 giorni."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Quanti giorni dalla data della fattura questo cliente ha per pagare; determina la data di scadenza predefinita sulle fatture cliente."@@ -9253,6 +9382,9 @@ msgstr "In questo passo"msgid "In use"msgstr "In uso"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "Nel fuso orario della tua azienda ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "Nelle impostazioni Enterprise alla sezione Sviluppatore, modifica i permessi dell'applicazione OAuth privata per includere «L'applicazione può scrivere nei tuoi documenti», quindi salva nuovamente le impostazioni di integrazione."@@ -9265,9 +9397,6 @@ msgstr "Le notifiche in-app vengono sempre consegnate. Scegli quali argomenti vumsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Le notifiche in-app vengono sempre consegnate. Scegli quali argomenti vuoi ricevere anche per e-mail."-msgid "inactive"-msgstr "inattivo"-msgid "Inactive"msgstr "Inattivo"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Luogo Incoterm"+msgid "Increase"+msgstr "Aumenta"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Indiretto"@@ -9364,6 +9502,9 @@ msgstr "Ereditato dal gruppo: se questo conto si chiude agli utili non distribuimsgid "Inherited from the parent group."msgstr "Ereditato dal gruppo padre."+msgid "inherits {inheritedName}"+msgstr "eredita {inheritedName}"+msgid "Input"msgstr "Input"@@ -9893,6 +10034,9 @@ msgstr "Priorità del lavoro"msgid "Job readable"msgstr "Lavoro leggibile"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Cartellino di produzione"@@ -10108,9 +10252,15 @@ msgstr "Ultimo utilizzo"msgid "Late in the evening, {name}."msgstr "Tardi la sera, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Le settimane successive vengono consumate una volta che quelle precedenti si esauriscono."+msgid "Latest operation end"msgstr "Fine dell'ultimo operazione"+msgid "Latest Order Date"+msgstr "Data dell'Ultimo Ordine"+msgid "Latitude"msgstr "Latitudine"@@ -10153,6 +10303,9 @@ msgstr "Lascia vuoto per usare la prossima revisione automaticamente"msgid "Leave empty for exact match"msgstr "Lascia vuoto per una corrispondenza esatta"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Lascia vuoto, oppure inserisci 0, per mostrare tutto quello che l'MRP pianifica."+msgid "Leave this page"msgstr "Lascia questa pagina"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Righe"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Le righe appariranno qui una volta che un'entrata merci di un ordine di acquisto è stata registrata, e solo per le quantità non già autorizzate su un altro reso del fornitore. Utilizza Aggiungi riga per un reso cieco."+msgstr "Le righe appaiono qui una volta che un'Entrata merci è stata registrata, e solo per le Quantità non già autorizzate su un altro reso a Fornitore. Usa Aggiungi Elemento Riga per un reso cieco."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Le righe appariranno qui una volta che la spedizione dell'ordine di vendita è stata registrata, e solo per le quantità non già autorizzate su un altro RMA. Utilizza Aggiungi riga articolo per un reso cieco."@@ -10441,6 +10594,12 @@ msgstr "Descrizione Lunga"msgid "Longitude"msgstr "Longitudine"+msgid "Look ahead (weeks)"+msgstr "Sguardo in Avanti (settimane)"++msgid "Look back (weeks)"+msgstr "Sguardo Indietro (settimane)"+msgid "Looks empty here"msgstr "Sembra vuoto qui"@@ -10570,6 +10729,12 @@ msgstr "Tipo di Manutenzione"msgid "Make"msgstr "Produrre"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "Produrre {quantity}"+msgid "Make Active"msgstr "Rendi Attivo"@@ -10847,6 +11012,9 @@ msgstr "Articolo di Materiale"msgid "Material Planning"msgstr "Pianificazione del materiale"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "La pianificazione del materiale mostra solo le azioni e gli ordini suggeriti dovuti entro questo numero di giorni da oggi, così i fabbisogni lontani rimangono fuori dal percorso finché non importano. L'orizzonte di pianificazione dell'articolo sostituisce questo valore predefinito."+msgid "Material Properties"msgstr "Proprietà dei Materiali"@@ -11231,6 +11399,18 @@ msgstr "MRP (pianificazione)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP viene eseguito automaticamente ogni 3 ore, ma puoi eseguirlo manualmente qui."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP viene eseguito automaticamente ogni giorno alle {time} ({timeZone}), ma puoi eseguirlo manualmente qui."++msgid "MRP Schedule"+msgstr "Programma MRP"++msgid "MRP Suggestions"+msgstr "Proposte MRP"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP suggerisce di spostare un ordine esistente solo quando la sua data differisce di più di questo numero di giorni. Gli scostamenti minori vengono ignorati per mantenere l'elenco di lavoro tranquillo."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Più ordini di produzione possono essere eseguiti su questo processo contemporaneamente — ad esempio, un tavolo laser, un forno o un bagno di galvanica"@@ -11498,9 +11678,6 @@ msgstr "Nuova Condizione di pagamento"msgid "New Picking List"msgstr "Nuova Lista di prelievo"-msgid "New PO"-msgstr "Nuovo PO"-msgid "New Price Override"msgstr "Nuova Forzatura di prezzo"@@ -12140,7 +12317,7 @@ msgid "No results found"msgstr "Nessun risultato trovato"msgid "No returnable lines for this customer"-msgstr "Nessuna riga restituibile per questo cliente"+msgstr "Nessuna riga restituibile per questo Cliente"msgid "No returnable lines for this supplier"msgstr "Nessuna riga restituibile per questo fornitore"@@ -12205,6 +12382,9 @@ msgstr "Nessuna unità di stoccaggio"msgid "No storage units or tracking numbers match."msgstr "Nessuna unità di stoccaggio o numero di tracciamento corrisponde."+msgid "No Supplier"+msgstr "Nessun fornitore"+msgid "No suppliers yet"msgstr "Nessun fornitore ancora"@@ -12555,6 +12735,9 @@ msgstr "Consegna puntuale"msgid "Onboard your agent to Carbon"msgstr "Integra il tuo agente in Carbon"+msgid "Once a day"+msgstr "Una volta al giorno"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Fabbisogno aperto di ordini di produzione più trasferimenti in sospesomsgid "Open jobs"msgstr "Ordini di produzione aperti"+msgid "Open Jobs"+msgstr "Ordini di produzione aperti"+msgid "Open menu"msgstr "Apri menu"msgid "Open navigation"msgstr "Apri navigazione"+msgid "Open Orders"+msgstr "Ordini aperti"+msgid "Open payables by supplier and age"msgstr "Debiti aperti per fornitore e anzianità"@@ -12932,9 +13121,18 @@ msgstr "Ordina {0} × {substitute} per questo ordine di produzione"msgid "Order {0} for this job"msgstr "Ordina {0} per questo lavoro"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "Ordina {quantity}"+msgid "Order by"msgstr "Ordina entro"+msgid "Order By"+msgstr "Ordina per"+msgid "Order date"msgstr "Data dell'ordine"@@ -13091,6 +13289,9 @@ msgstr "Responsabile"msgid "Owner (cost center)"msgstr "Responsabile (Centro di costo)"+msgid "Ownership"+msgstr "Proprietà"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Possiede: {0}"@@ -13569,9 +13770,36 @@ msgstr "Tempo previsto"msgid "Planning"msgstr "Pianificazione"+msgid "Planning action"+msgstr "Proposta di pianificazione"++msgid "Planning horizon"+msgstr "Orizzonte di pianificazione"++msgid "Planning Horizon"+msgstr "Orizzonte di pianificazione"++msgid "Planning Horizon (Days)"+msgstr "Orizzonte di pianificazione (giorni)"++msgid "Planning Horizon:"+msgstr "Orizzonte di pianificazione:"++msgid "Planning Ownership"+msgstr "Responsabilità di Pianificazione"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "I cicli di pianificazione hanno suggerito il rifornimento fino a un multiplo intero di questo numero."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "La pianificazione mostra solo le azioni e gli ordini suggeriti dovuti entro questo numero di giorni. Lascia vuoto per usare il valore predefinito dell'azienda, oppure inserisci 0 per mostrare tutto per questo articolo."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Limite inferiore della pianificazione su una quantità di rifornimento suggerita; distinto dal MOQ di un fornitore, che risiede nel record della parte del fornitore."@@ -13980,6 +14208,9 @@ msgstr "Piano di Progetto"msgid "Project start"msgstr "Inizio progetto"+msgid "Projected"+msgstr "Proiettato"+msgid "Projected completion"msgstr "Completamento previsto"@@ -14001,6 +14232,12 @@ msgstr "Esaurimento delle scorte proiettato la settimana del {0}"msgid "Projected stock"msgstr "Stock previsto"+msgid "Projected stock by week"+msgstr "Giacenza proiettata per settimana"++msgid "Projected stock is already below zero this week"+msgstr "La giacenza proiettata è già sotto zero questa settimana"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Rottura di stock prevista nella settimana del {0}"@@ -14139,6 +14376,9 @@ msgstr "Ordine di Acquisto"msgid "Purchase Order Amount"msgstr "Importo Ordine di Acquisto"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Regola di approvazione dell'ordine di acquisto"@@ -14166,6 +14406,9 @@ msgstr "Ordini di Acquisto"msgid "Purchase Orders and Planning"msgstr "Ordini di Acquisto e Pianificazione"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Ordini di acquisto richiesti"@@ -14272,9 +14515,6 @@ msgstr "Qtà"msgid "Qty On Hand"msgstr "Qtà a Magazzino"-msgid "Qty to Order"-msgstr "Qtà da ordinare"-msgid "Qty. Complete"msgstr "Qtà. Completata"@@ -14568,6 +14808,9 @@ msgstr "Pronto per offerta"msgid "ready to keep or revert"msgstr "pronto per mantenere o ripristinare"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Gli ordini reali consumano il fabbisogno di previsione della loro stessa settimana per primo, quindi le settimane precedenti e successive entro la finestra aziendale, così previsione e fabbisogno effettivo non vengono mai entrambi pianificati per le stesse unità."+msgid "Real-time inventory and shop-floor visibility"msgstr "Visibilità dell'inventario e del reparto di produzione in tempo reale"@@ -14880,9 +15123,15 @@ msgstr "Controllo Rilascio"msgid "Release Job"msgstr "Rilascia Commessa"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Rilascia Ordini di produzione"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Rilasciato"@@ -15034,6 +15283,9 @@ msgstr "Rendering dell'anteprima dell'etichetta..."msgid "Reopen"msgstr "Riapri"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Riordina"@@ -15221,6 +15473,12 @@ msgstr "Richiede Riparazione"msgid "Requires staffing"msgstr "Richiede personale"+msgid "Reschedule tolerance"+msgstr "Tolleranza di riprogrammazione"++msgid "Reschedule Tolerance"+msgstr "Tolleranza di Riprogrammazione"+msgid "Reserve floor"msgstr "Limite di riserva"@@ -15279,6 +15537,12 @@ msgstr "risorse"msgid "Resources"msgstr "Risorse"+msgid "Responsible employee"+msgstr "Dipendente responsabile"++msgid "Responsible Employee"+msgstr "Dipendente Responsabile"+msgid "Restock"msgstr "Riapprovvigionamento"@@ -15654,6 +15918,9 @@ msgstr "ID Esecuzione"msgid "Run month-end close and standard reconciliations"msgstr "Esegui la chiusura di fine mese e le riconciliazioni standard"+msgid "Run MRP"+msgstr "Esegui MRP"+msgid "Run payment batches and track aging"msgstr "Esegui batch di pagamento e traccia l'invecchiamento"@@ -17243,6 +17510,9 @@ msgstr "Avvia"msgid "Start {0} Day Free Trial"msgstr "Inizia la prova gratuita di {0} giorni"+msgid "Start By"+msgstr "Inizia per"+msgid "Start counting"msgstr "Inizia il conteggio"@@ -17386,6 +17656,9 @@ msgstr "Passi costruiti separatamente, quindi montati come un'unica parte: nel pmsgid "Still dark out on the floor."msgstr "Ancora buio in officina."+msgid "Stock Availability"+msgstr "Disponibilità di Giacenza"+msgid "Stock movement corrected"msgstr "Movimento di magazzino corretto"@@ -17624,6 +17897,15 @@ msgstr "Suggerisci Corrispondenza"msgid "Suggest with AI"msgstr "Suggerisci con l'IA"+msgid "Suggested Jobs"+msgstr "Ordini di produzione suggeriti"++msgid "Suggested Orders"+msgstr "Ordini suggeriti"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Ordini suggeriti richiesti dopo l'orizzonte di pianificazione di questo articolo. Estendi l'orizzonte per includerli."+msgid "Suggested orders you haven't placed yet."msgstr "Ordini suggeriti che non hai ancora effettuato."@@ -17874,8 +18156,8 @@ msgstr "Sincronizza"msgid "Sync Activity"msgstr "Attività di sincronizzazione"-msgid "sync off"-msgstr "sincronizzazione disattivata"+msgid "Sync Off"+msgstr "Sincronizzazione disattivata"msgid "Sync operation"msgstr "Operazione di sincronizzazione"@@ -18642,6 +18924,9 @@ msgstr "La percentuale dello sconto di cassa. Utilizza 0 per nessuno sconto."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "Il set di autorizzazioni che i nuovi dipendenti di questo tipo ricevono automaticamente; la modifica qui cambia il modello solo per i futuri assunti - i dipendenti esistenti mantengono quello che hanno a meno che non vengono esplicitamente aggiornati in massa."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "La persona a cui è assegnata una proposta di pianificazione: il responsabile dell'articolo in quella ubicazione, altrimenti il responsabile del gruppo articoli, altrimenti il responsabile dell'ubicazione, altrimenti il valore predefinito dell'azienda."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Gli impianti, i depositi e i siti dove vivono il tuo lavoro e le tue giacenze"@@ -18663,6 +18948,9 @@ msgstr "I processi che questo centro di lavoro può eseguire; appare nelle selezmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "Il provider non offre target di dimensione. Abilita prima la funzione nel provider (ad es. categorie di tracciamento, tracciamento di classe o campi)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "I punti di rottura della quantità a cui questa riga è quotata; ogni colonna ha il proprio prezzo unitario per la negoziazione acquirente-fornitore e per la conversione a documenti a valle."@@ -18991,6 +19279,9 @@ msgstr "Queste voci di prima nota sono ancora Bozza, quindi i loro dare e averemsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Queste operazioni utilizzano un processo con più fornitori. Scegli un fornitore per ciascuna operazione."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Questi ordini non potevano essere caricati. Chiudi e riapri per riprovare."+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."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Tolleranza (+/-)"+msgid "Tolerance (days)"+msgstr "Tolleranza (giorni)"+msgid "Tomorrow"msgstr "Domani"@@ -19847,8 +20141,8 @@ msgstr "Annulla"msgid "Ungroup"msgstr "Separa"-msgid "unhealthy"-msgstr "anomalo"+msgid "Unhealthy"+msgstr "Anomalo"msgid "Uninstall"msgstr "Disinstalla"@@ -20936,6 +21230,9 @@ msgstr "Quando {name} cambia"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Quando la durata di conservazione di un prodotto finito è impostata su Calcolata, scegli quali input consumati alimentano il calcolo."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Quando un ordine di vendita o un ordine di produzione cade in una settimana senza previsione rimanente, consuma la previsione da settimane vicine anziché essere conteggiato in aggiunta. Impostare entrambi a 0 per compensare solo entro la stessa settimana."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Quando un numero di serie o un lotto scade, e cosa succede se usato dopo — una politica aziendale può Avvertire, Bloccare o BloccareCon Sostituzione."@@ -21128,6 +21425,9 @@ msgstr "Chi riceve la formazione su cosa, in quale formato. La tua parte: protegmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Chi deve approvare preventivi, ordini e acquisti — e quando"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Chi è responsabile delle azioni di pianificazione MRP. Le ubicazioni ereditano l'impostazione predefinita dell'azienda; i gruppi di articoli ereditano la loro ubicazione. L'assegnazione più specifica ha la priorità e ogni articolo può impostare una forzatura nella scheda Pianificazione."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Chi dovrebbe ricevere notifiche per interventi di manutenzione?"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 331b402688..7125b4cf90 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# 行はこの会社の外部のデータにリンクmsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# 行はこの会社の外部のデータにリンクしているため、バックアップできません。スキップすると、他のすべてがバックアップされます。} other {# 行はこの会社の外部のデータにリンクしているため、バックアップできません。スキップすると、他のすべてがバックアップされます。}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, other {#週}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {プランナーはこのコンポーネントを1つの剛体—指示書内の1つのステップとして扱います。プランを再実行して適用してください。} other {プランナーはこれら # 個のコンポーネントを1つの剛体—指示書内の1つのステップとして扱います。プランを再実行して適用してください。}}"@@ -107,6 +111,10 @@ msgstr "{0}は{where}でまだ使用されているため削除できませんmsgid "{0} cells with deltas"msgstr "{0}個のデルタを持つセル"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} 消費済"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0}個の値"msgid "{0} values missing"msgstr "{0}個の値が見つかりません"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} は {name} として保存されます"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# 件の残高のある勘定} other {# 件の残msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# コース} other {# コース}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, other {{fenceLabel}以降の追加 # 件}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# バッチを解散} other {# バッチを解散}}"@@ -340,6 +356,9 @@ msgstr "{days}日"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo}がこれをあなたの台帳に転記するため、Carbonはそれをプッシュしません。変更があった場合に備えて、保存された選択肢は保持されます。"+msgid "{dismissed} dismissed"+msgstr "{dismissed}件却下済み"+msgid "{done} of {total} phases complete"msgstr "{done} / {total} フェーズ完了"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} 件さらに表示: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} 件が挿入されました、{updated} 件が更新されました、{0} 件の修正が必要です、{1} 件がスキップされました。"+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, other {#日}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# 行} other {# 行}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# フェーズ残り} other {# フェーズ残msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} リソース · {reservationCount} 予約 · {jobCount} 製造指図"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} 個の権限"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {残りの # 個の必須勘定科msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount}はスケジュール化できません"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} 件の製造指図が更新されました"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} がアップロードされました — フィールドは文書から入力されました。"@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 件の工程"+msgid "0 suggests a move for any date difference."+msgstr "0 は任意の日付差異に対して移動を提案します。"+msgid "0-4 weeks"msgstr "0~4週間"@@ -518,9 +543,6 @@ msgstr "1 件の下書き仕訳行"msgid "1 job created"msgstr "1件のジョブが作成されました"-msgid "1 job updated"-msgstr "1件のジョブが更新されました"-msgid "1 part skipped — it already has an open job"msgstr "1個の部品はスキップ済 — 既に進行中の製造指図があります"@@ -530,6 +552,9 @@ msgstr "1個の部品はスキップ済 — 製造する必要がありませんmsgid "1 problem — not published"msgstr "1個の問題 — 公開済ではありません"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 購入 = {conversionFactor} 在庫管理"+msgid "1 suggested batch"msgstr "推奨バッチ 1 個"@@ -542,6 +567,9 @@ msgstr "12ヶ月間の期間"msgid "13+ weeks"msgstr "13週間以上"+msgid "1st Negative On Hand"+msgstr "初回マイナス在庫"+msgid "1Y"msgstr "1年"@@ -1082,6 +1110,9 @@ msgstr "ステップには名前が必要です。"msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "作業区または作業者の予約で、1つの工程の配置された時間帯のもの — スケジュール実行の具現化された出力で、予測が描画するもの"+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "MRPが各実行後に生成する提案:新しい供給を発注または内製する、もしくはオープン状態の発注書明細または製造指図を早める、延期する、数量を増やす、減らす、またはキャンセルする。計画ページから適用するか、却下するか、割り当ててください。"+msgid "A supplier contact and location are optional"msgstr "仕入先の担当者と拠点は任意です"@@ -2006,6 +2037,12 @@ msgstr "このジョブの工程がこのバッチで実行されます"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "作業区のキューにおける工程のポジション — 床がピックアップする順序。エンジンは配置順序(最初に予想される開始が最初)からそれに番号を付けます。作業区ボード上でカードを並べ替えることは、日付を変えずにそれを上書きします。"+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Onshapeへの接続中に予期しないエラーが発生しました。連携設定を保存して再度お試しください。"@@ -2167,6 +2204,9 @@ msgstr "価格設定ルールを適用"msgid "Apply Rules On Top"msgstr "上にルールを適用"+msgid "Apply Suggested Changes"+msgstr "提案された変更を適用"+msgid "Apply suggestions"msgstr "提案を適用"@@ -2824,6 +2864,9 @@ msgstr "割り当て先"msgid "Assign to Groups"msgstr "グループに割り当て"+msgid "Assign to Me"+msgstr "自分に割り当てる"+msgid "Assigned"msgstr "割り当て済み"@@ -2836,6 +2879,9 @@ msgstr "私に割り当てられた"msgid "Assignee"msgstr "担当者"+msgid "Assignees"+msgstr "担当者"+msgid "Assignment"msgstr "割り当て"@@ -3491,12 +3537,18 @@ msgstr "変更通知をキャンセル"msgid "Cancel Job"msgstr "ジョブをキャンセル"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "注文をキャンセル"msgid "Cancel Purchase Order"msgstr "発注書をキャンセル"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "返品をキャンセル"@@ -3548,6 +3600,12 @@ msgstr "品目IDなしで部品バケットに移動することはできませmsgid "Cannot place order - no supplier associated with this item"msgstr "発注できません - この品目に関連付けられた仕入先がありません"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "注文できません — {count} 件の品目に仕入先がありません"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "注文できません — 1 件の品目に仕入先がありません"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "投稿できません — 出荷に期限切れの追跡対象エンティティが含まれています。"@@ -3753,6 +3811,9 @@ msgstr "タイプを変更"msgid "Changed By"msgstr "変更者"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "このビューのみの変更です。品目の計画期間は更新されません。"+msgid "Changelog"msgstr "変更ログ"@@ -3853,6 +3914,9 @@ msgstr "この返品に明細を追加する方法を選択してください。msgid "Choose what appears on the printed job traveler."msgstr "印刷された製造指図現品票に表示される内容を選択します。"+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "MRPの自動再計算のタイミングを選択してください。計画ページの「再計算」でいつでも手動で実行できます。"+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "品目、見積、製造指図上の部品表エクスプローラーが各明細を説明またはアイテムIDのどちらでラベル付けするかを選択します。"@@ -4068,6 +4132,9 @@ msgstr "企業"msgid "Company"msgstr "会社"+msgid "Company default"+msgstr "会社のデフォルト"+msgid "Company group"msgstr "会社グループ"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "文書が読み込めません: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "{0}をリリースできませんでした: {1}"@@ -5093,6 +5162,9 @@ msgstr "部門を作成しました"msgid "Created failure mode"msgstr "障害モードを作成しました"+msgid "Created from planning"+msgstr "計画から作成"+msgid "Created gauge type"msgstr "測定器タイプを作成しました"@@ -5671,6 +5743,15 @@ msgstr "小数位数"msgid "Declining balance"msgstr "定率法"+msgid "Decrease"+msgstr "減少"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "真夜中ですね、{name}さん。"@@ -5737,6 +5818,9 @@ msgstr "設備と施設保全のデフォルトGL費用勘定科目"msgid "Default GL expense account for periodic depreciation runs."msgstr "定期的な減価償却実行のデフォルトGL費用勘定科目"+msgid "Default horizon (days)"+msgstr "デフォルト計画期間(日数)"+msgid "Default Method"msgstr "デフォルト方法"@@ -5788,6 +5872,15 @@ msgstr "このクラスの新しい資産に事前入力されるデフォルトmsgid "Defaults"msgstr "デフォルト"+msgid "Defer"+msgstr "延期"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "繰延税金費用"@@ -6368,6 +6461,9 @@ msgstr "発見"msgid "Dismiss"msgstr "閉じる"+msgid "Dismissed"+msgstr "却下済"+msgid "Dispatch"msgstr "保全指示"@@ -6744,6 +6840,9 @@ msgstr "各仕入先の全製造指図からの外注工程は、1つの新規msgid "Each, lb, ft…"msgstr "各、ポンド、フィート…"+msgid "Earlier weeks are consumed first."+msgstr "早い週から消費されます。"+msgid "Earliest operation start"msgstr "最早操作開始"@@ -7503,6 +7602,9 @@ msgstr "イベントタイプ"msgid "Events"msgstr "イベント"+msgid "Every 3 hours"+msgstr "3時間ごと"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "会社に属するすべてのレコード。認証情報、連携トークン、Webhookは含まれません。"@@ -7635,6 +7737,15 @@ msgstr "予想受取日"msgid "Expected Receipt Date"msgstr "予想受取日"+msgid "Expedite"+msgstr "前倒し"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "売掛金決済において回収不可能として償却された得意先残高の費用勘定"@@ -8112,12 +8223,18 @@ msgstr "カウントの更新に失敗しました"msgid "Failed to update item cost"msgstr "品目の原価を更新できませんでした"+msgid "Failed to update job"+msgstr "製造指図の更新に失敗しました"+msgid "Failed to update lead times"msgstr "リードタイムの更新に失敗しました"msgid "Failed to update opportunity with purchase order"msgstr "商談を発注書で更新できませんでした"+msgid "Failed to update purchase order line"+msgstr "発注書明細の更新に失敗しました"+msgid "Failed to update quote line"msgstr "見積明細を更新できませんでした"@@ -8315,6 +8432,9 @@ msgstr "名"msgid "First Operation"msgstr "最初の操作"+msgid "First week the projected stock goes below zero"+msgstr "予想在庫が初めてゼロを下回る週"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "固定資産"@@ -8381,6 +8501,12 @@ msgstr "何でも構いません。彼らが適切な人を連れてきます。msgid "Forecast"msgstr "予測"+msgid "Forecast consumption"+msgstr "予測所要量の消費"++msgid "Forecast Consumption"+msgstr "予測消費"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "予測方法:<0>{0}</0>。この行は稼働中の製造指図から派生していないため、親のソースは利用できません。"@@ -8829,7 +8955,7 @@ msgstr "スケジュール化できない工程があります"msgid "Headers"msgstr "ヘッダー"-msgid "healthy"+msgid "Healthy"msgstr "正常"msgid "Help"@@ -8979,6 +9105,9 @@ msgstr "計算日の後、早期支払割引が利用可能な日数。"msgid "How many days after the calculation date the full amount is due."msgstr "計算日から何日後に全額が期日となるか。"+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "MRPが移動を提案する前に、オープン状態の発注がそれが必要とされる日付から到着できる日数。設定 → 計画で設定します。デフォルトは7日です。"+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "得意先が支払うまでの請求書日付からの日数。得意先請求書のデフォルト期日を設定します"@@ -9253,6 +9382,9 @@ msgstr "このステップで"msgid "In use"msgstr "使用中"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "お客様の会社のタイムゾーン({companyTimeZone})です。"+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "Enterprise設定の開発者セクションで、プライベートOAuthアプリケーションの権限を編集して「アプリケーションはドキュメントに書き込むことができます」を含め、連携設定を再度保存してください。"@@ -9265,9 +9397,6 @@ msgstr "アプリ内通知は常に配信されます。どのトピックがメmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "アプリ内通知は常に配信されます。どのトピックがメールでも届くかを選択してください。"-msgid "inactive"-msgstr "無効"-msgid "Inactive"msgstr "無効"@@ -9325,6 +9454,15 @@ msgstr "インコタームズ"msgid "Incoterm Location"msgstr "インコタームズの場所"+msgid "Increase"+msgstr "増加"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "間接"@@ -9364,6 +9502,9 @@ msgstr "グループから継承:このアカウントが利益剰余金 (収msgid "Inherited from the parent group."msgstr "親グループから継承。"+msgid "inherits {inheritedName}"+msgstr "継承 {inheritedName}"+msgid "Input"msgstr "入力"@@ -9893,6 +10034,9 @@ msgstr "ジョブ優先度"msgid "Job readable"msgstr "ジョブ読取可能"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "現品票"@@ -10108,9 +10252,15 @@ msgstr "最後に使用"msgid "Late in the evening, {name}."msgstr "夜遅く、{name}さん。"+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "早い週が使い尽くされた後、後の週が消費されます。"+msgid "Latest operation end"msgstr "最終操作終了"+msgid "Latest Order Date"+msgstr "最新注文日付"+msgid "Latitude"msgstr "緯度"@@ -10153,6 +10303,9 @@ msgstr "空白のままにして、次のリビジョンを自動的に使用しmsgid "Leave empty for exact match"msgstr "正確な一致のために空のままにしてください"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "空のままにするか、0を入力して、MRPが計画するすべてを表示します。"+msgid "Leave this page"msgstr "このページを離れる"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "行"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "発注書の入荷が転記済になると、ここに明細が表示されます。ただし、他の仕入先返品で既に承認されていない数量のみです。その他の返品の場合は「明細を追加」を使用してください。"+msgstr "発注書入荷が転記されると、明細がここに表示され、別の仕入先リターンで既に承認されていない数量のみが対象です。ブラインドリターンの場合は「明細を追加」を使用してください。"msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "受注出荷が転記された後に、別のRMAで既に認可されていない数量のみが表示されます。目隠し返品の場合は「明細を追加」を使用してください。"@@ -10441,6 +10594,12 @@ msgstr "長い説明"msgid "Longitude"msgstr "経度"+msgid "Look ahead (weeks)"+msgstr "先を見る(週)"++msgid "Look back (weeks)"+msgstr "遡る(週)"+msgid "Looks empty here"msgstr "ここは空のようです"@@ -10570,6 +10729,12 @@ msgstr "保全タイプ"msgid "Make"msgstr "製造"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "{quantity} を製造"+msgid "Make Active"msgstr "アクティブにする"@@ -10847,6 +11012,9 @@ msgstr "材料品目"msgid "Material Planning"msgstr "材料計画"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "材料計画は、今日からこの日数以内に期限が到来するアクションと提案注文のみを表示するため、先のニーズは重要になるまで支障が生じません。品目独自の計画期間がこのデフォルトをオーバーライドします。"+msgid "Material Properties"msgstr "材料特性"@@ -11231,6 +11399,18 @@ msgstr "MRP (計画)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRPは3時間ごとに自動的に実行されますが、ここで手動で実行することもできます。"+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRPは毎日{time}({timeZone})に自動的に実行されますが、ここで手動で実行することもできます。"++msgid "MRP Schedule"+msgstr "MRP スケジュール"++msgid "MRP Suggestions"+msgstr "MRP 提案"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP は、既存の注文の日付がこの日数以上ずれている場合だけ、既存の注文の移動を提案します。より小さなギャップは放置されて、ワークリストは静かなままです。"+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "複数の製造指図がこの工法上で同時に実行できます—例:レーザーテーブル、炉、またはめっき槽"@@ -11498,9 +11678,6 @@ msgstr "新規支払条件"msgid "New Picking List"msgstr "新しいピッキングリスト"-msgid "New PO"-msgstr "新規PO"-msgid "New Price Override"msgstr "新規価格上書き"@@ -12140,7 +12317,7 @@ msgid "No results found"msgstr "検索結果が見つかりません"msgid "No returnable lines for this customer"-msgstr "この得意先の返品対象明細がありません"+msgstr "この得意先に返却可能な明細がありません"msgid "No returnable lines for this supplier"msgstr "この仕入先に返品対象の明細がありません。"@@ -12205,6 +12382,9 @@ msgstr "保管ユニットがありません"msgid "No storage units or tracking numbers match."msgstr "保管ユニットまたはトラッキング番号に一致するものはありません。"+msgid "No Supplier"+msgstr "仕入先なし"+msgid "No suppliers yet"msgstr "仕入先がまだありません"@@ -12555,6 +12735,9 @@ msgstr "オンタイム配送"msgid "Onboard your agent to Carbon"msgstr "エージェントを Carbon にオンボード"+msgid "Once a day"+msgstr "1日1回"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "このビンからの未処理転送を含むオープン製造指図所msgid "Open jobs"msgstr "オープン製造指図"+msgid "Open Jobs"+msgstr "オープン製造指図"+msgid "Open menu"msgstr "メニューを開く"msgid "Open navigation"msgstr "ナビゲーションを開く"+msgid "Open Orders"+msgstr "オープン注文"+msgid "Open payables by supplier and age"msgstr "仕入先・日数別オープン買掛金"@@ -12932,9 +13121,18 @@ msgstr "この製造指図に{0} × {substitute}を発注"msgid "Order {0} for this job"msgstr "このジョブ用に{0}を発注"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "{quantity} を注文"+msgid "Order by"msgstr "注文日"+msgid "Order By"+msgstr "順序"+msgid "Order date"msgstr "発注日"@@ -13091,6 +13289,9 @@ msgstr "責任者"msgid "Owner (cost center)"msgstr "責任者 (原価センター)"+msgid "Ownership"+msgstr "所有権"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "所有者: {0}"@@ -13569,9 +13770,36 @@ msgstr "予定時間"msgid "Planning"msgstr "計画"+msgid "Planning action"+msgstr "計画提案"++msgid "Planning horizon"+msgstr "計画期間"++msgid "Planning Horizon"+msgstr "計画期間"++msgid "Planning Horizon (Days)"+msgstr "計画期間(日数)"++msgid "Planning Horizon:"+msgstr "計画期間:"++msgid "Planning Ownership"+msgstr "計画所有権"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "計画ラウンドは、この数の整数倍まで補充を提案しました。"+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "計画はこの日数以内に期限が到来するアクションと提案注文のみを表示します。会社のデフォルトを使用する場合は空のままにするか、この品目のすべてを表示する場合は0を入力してください。"+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "計画の発注提案数量の下限。仕入先部品レコードにある仕入先のMOQとは別。"@@ -13980,6 +14208,9 @@ msgstr "プロジェクト計画"msgid "Project start"msgstr "プロジェクト開始"+msgid "Projected"+msgstr "予測"+msgid "Projected completion"msgstr "予測完了"@@ -14001,6 +14232,12 @@ msgstr "{0} の週の予測欠品"msgid "Projected stock"msgstr "予測在庫"+msgid "Projected stock by week"+msgstr "週別予想在庫"++msgid "Projected stock is already below zero this week"+msgstr "予想在庫は今週既にゼロを下回っています"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "{0}の週の欠品予測"@@ -14139,6 +14376,9 @@ msgstr "発注書"msgid "Purchase Order Amount"msgstr "発注書金額"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "発注書承認ルール"@@ -14166,6 +14406,9 @@ msgstr "発注書"msgid "Purchase Orders and Planning"msgstr "発注書と計画"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "発注書が必要です"@@ -14272,9 +14515,6 @@ msgstr "数量"msgid "Qty On Hand"msgstr "手持数量"-msgid "Qty to Order"-msgstr "注文数量"-msgid "Qty. Complete"msgstr "数量完了"@@ -14568,6 +14808,9 @@ msgstr "見積準備完了"msgid "ready to keep or revert"msgstr "保持または復元の準備完了"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "実際の注文は最初に自社の週の所要量予測を消費し、その後会社の時間枠内でそれより前の週と後の週を消費するため、予測と実績の所要量が同じユニットに対して両方計画されることはありません。"+msgid "Real-time inventory and shop-floor visibility"msgstr "リアルタイム在庫と工場フロアの可視性"@@ -14880,9 +15123,15 @@ msgstr "リリース管理"msgid "Release Job"msgstr "ジョブをリリース"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "製造指図をリリース"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "リリース済み"@@ -15034,6 +15283,9 @@ msgstr "ラベルプレビューをレンダリング中..."msgid "Reopen"msgstr "再オープン"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "並び替え"@@ -15116,7 +15368,7 @@ msgid "Reports"msgstr "レポート"msgid "Reprice with current rules"-msgstr "現在のルールで再価格設定"+msgstr "現在のルールで価格を再設定"#. placeholder {0}: format(repricedPrice)msgid "Repricing with today's rules and costs gives <0>{0}</0>."@@ -15221,6 +15473,12 @@ msgstr "修理が必要"msgid "Requires staffing"msgstr "スタッフが必要"+msgid "Reschedule tolerance"+msgstr "再スケジュール許容日数"++msgid "Reschedule Tolerance"+msgstr "スケジュール変更許容値"+msgid "Reserve floor"msgstr "予備床"@@ -15279,6 +15537,12 @@ msgstr "リソース"msgid "Resources"msgstr "リソース"+msgid "Responsible employee"+msgstr "責任従業員"++msgid "Responsible Employee"+msgstr "担当従業員"+msgid "Restock"msgstr "補充"@@ -15654,6 +15918,9 @@ msgstr "実行ID"msgid "Run month-end close and standard reconciliations"msgstr "月末クローズと標準的な照合を実行"+msgid "Run MRP"+msgstr "MRPを実行"+msgid "Run payment batches and track aging"msgstr "支払いバッチを実行し、経過期間を追跡する"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "工程を選択"msgid "Select posted receipt lines from this supplier to return."-msgstr "この仕入先からの転記済入荷明細を返品するために選択してください。"+msgstr "この仕入先からの転記済入荷明細を返品として選択してください。"msgid "Select posted shipment lines to this customer to return."msgstr "この得意先への転記済出荷明細を選択して返品する"@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "セッションがロック中"msgid "Set a customer on this return to add from a shipment."-msgstr "この返品に得意先を設定して出荷から追加してください。"+msgstr "出荷から追加するにはこのリターンに得意先を設定してください。"msgid "Set a supplier on this return to add from a receipt."msgstr "この返品に仕入先を設定して入荷から追加"@@ -17243,6 +17510,9 @@ msgstr "開始"msgid "Start {0} Day Free Trial"msgstr "{0}日間の無料トライアルを開始"+msgid "Start By"+msgstr "開始予定日"+msgid "Start counting"msgstr "カウントを開始"@@ -17386,6 +17656,9 @@ msgstr "ステップは独立して構築された後、1つのピースとしmsgid "Still dark out on the floor."msgstr "まだフロアは暗い。"+msgid "Stock Availability"+msgstr "在庫可用性"+msgid "Stock movement corrected"msgstr "在庫移動が訂正されました"@@ -17624,6 +17897,15 @@ msgstr "照合を提案"msgid "Suggest with AI"msgstr "AIで提案"+msgid "Suggested Jobs"+msgstr "提案製造指図"++msgid "Suggested Orders"+msgstr "提案注文"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "この品目の計画期間の後に必要な提案注文があります。それらを含めるために計画期間を延長してください。"+msgid "Suggested orders you haven't placed yet."msgstr "まだ発注していない推奨注文。"@@ -17874,7 +18156,7 @@ msgstr "同期"msgid "Sync Activity"msgstr "同期アクティビティ"-msgid "sync off"+msgid "Sync Off"msgstr "同期オフ"msgid "Sync operation"@@ -18642,6 +18924,9 @@ msgstr "現金割引の割合。割引がない場合は0を使用してくだmsgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "このタイプの新しい従業員が自動的に受け取る権限セット。ここで編集すると、将来の雇用のみがテンプレートを変更します。既存の従業員は、明示的に大量更新されない限り、持っているものを保持します。"+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "計画提案が割り当てられる個人:その拠点での品目の責任者。該当なければアイテムグループの責任者。該当なければ拠点の責任者。該当なければ会社のデフォルト。"+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "あなたの仕事と在庫が存在する工場、倉庫、およびサイト"@@ -18663,6 +18948,9 @@ msgstr "この作業区が実行できる工法。工程のスケジュール時msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "プロバイダーはディメンションターゲットを提供していません。最初にプロバイダーで機能を有効にしてください(例:追跡カテゴリ、クラス追跡、またはフィールド)。"+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "この明細が価格設定される数量ブレークポイント。各列は買い手と仕入先の交渉および下流文書への変換用に、独自の単価を持ちます。"@@ -18991,6 +19279,9 @@ msgstr "これらの仕訳はまだ下書きであるため、それらの借方msgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "これらの工程は複数の仕入先に対応可能な工法を使用しています。各工程について仕入先を選択してください。"+msgid "These orders could not be loaded. Close and reopen to try again."+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 "これらの部品はこの部品で置き換わっています。各ルールは旧部品に設定されています;ルールを変更するには旧部品を開いてください。"@@ -19469,6 +19760,9 @@ msgstr "許容差+"msgid "Tolerance (+/-)"msgstr "許容範囲 (+/-)"+msgid "Tolerance (days)"+msgstr "許容値(日)"+msgid "Tomorrow"msgstr "明日"@@ -19530,7 +19824,7 @@ msgid "Total Hours"msgstr "合計時間"msgid "Total Indirect Cost"-msgstr "総間接原価"+msgstr "間接原価合計"msgid "Total Material Cost"msgstr "材料原価合計"@@ -19847,7 +20141,7 @@ msgstr "元に戻す"msgid "Ungroup"msgstr "グループ解除"-msgid "unhealthy"+msgid "Unhealthy"msgstr "不正常"msgid "Uninstall"@@ -20936,6 +21230,9 @@ msgstr "{name}が変更されるとき"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "完成品の保存期間が「計算」に設定されている場合、計算に使用される消費材料を選択してください。"+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "受注または製造指図が残りの予測がない週に着地した場合、上に計算されるのではなく、近くの週から予測を消費します。両方を 0 に設定して、同じ週内のみで相殺します。"+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "シリアルまたはバッチが期限切れになるとき、およびその後使用された場合に何が起こるか — 会社のポリシーは警告、ブロック、またはブロック上書きできます。"@@ -21128,6 +21425,9 @@ msgstr "誰が何をどのような形式で訓練を受けるか。あなたのmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "見積、注文、購買の承認が必要な人と時期"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "MRP計画アクションの所有者。拠点は会社のデフォルトを継承し、品目グループはそれらの拠点を継承します。最も具体的な割り当てが優先され、各品目は計画タブで上書きできます。"+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "保全関連の保全指示の通知を受け取る必要があるのは誰ですか?"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 8bfaf58ba1..e4178d02fd 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# 행은 이 회사 외부의 데이터에 연결되어msgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# 행은 이 회사 외부의 데이터에 연결되어 있어서 백업할 수 없습니다. 이를 건너뛰면 다른 모든 것이 백업됩니다.} other {# 행은 이 회사 외부의 데이터에 연결되어 있어서 백업할 수 없습니다. 이를 건너뛰면 다른 모든 것이 백업됩니다.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, other {#주}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {플래너는 이 부품을 하나의 강체로 취급합니다 — 명령의 한 단계입니다. 적용하려면 계획을 다시 실행하세요.} other {플래너는 이 # 부품을 하나의 강체로 취급합니다 — 명령의 한 단계입니다. 적용하려면 계획을 다시 실행하세요.}}"@@ -107,6 +111,10 @@ msgstr "{0}은(는) {where}에서 아직 사용 중이므로 삭제할 수 없msgid "{0} cells with deltas"msgstr "{0}개 셀에 변경사항 있음"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} 소모됨"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0}개 값"msgid "{0} values missing"msgstr "{0}개 값 누락"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0}이 {name}으로 저장됩니다"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# 잔액이 있는 계정} other {# 잔액이 있msgid "{count, plural, one {# course} other {# courses}}"msgstr "교육과정 {count}개"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, other {{fenceLabel} 이후 # 개}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {배치 # 해제} other {배치 # 해제}}"@@ -340,6 +356,9 @@ msgstr "{days}일"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo}가(이) 이를 귀사의 원장에 게시하므로 Carbon은 이를 푸시하지 않습니다. 변경되는 경우에 대비하여 저장된 선택 사항이 유지됩니다."+msgid "{dismissed} dismissed"+msgstr "{dismissed} 무시됨"+msgid "{done} of {total} phases complete"msgstr "{done}개 중 {total}개 단계 완료"@@ -360,6 +379,9 @@ msgstr "{hiddenCount}개 추가: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted}개 추가, {updated}개 업데이트, {0}개 수정 필요, {1}개 건너뜀."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, other {#일}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# 줄} other {# 줄}}"@@ -415,6 +437,9 @@ msgstr "{remaining}단계 남음"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount}개 자원 · {reservationCount}개 예약 · {jobCount}개 작업 지시"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "권한 {scopeCount}개"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {먼저 # 남은 필수 계정을msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount}개는 일정을 짤 수 없습니다"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount}개의 작업 지시 업데이트됨"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} 업로드됨 — 문서에서 필드가 채워졌습니다."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0개 공정"+msgid "0 suggests a move for any date difference."+msgstr "0은 날짜 차이가 있으면 항상 주문을 이동할 것을 제안합니다."+msgid "0-4 weeks"msgstr "0-4주"@@ -518,9 +543,6 @@ msgstr "1개의 초안 분개"msgid "1 job created"msgstr "1개 작업이 생성됨"-msgid "1 job updated"-msgstr "1개 작업이 업데이트됨"-msgid "1 part skipped — it already has an open job"msgstr "1개 부품이 건너뜀 — 이미 활성 작업이 있음"@@ -530,6 +552,9 @@ msgstr "1개 부품이 건너뜀 — 만들 것이 없음"msgid "1 problem — not published"msgstr "1개 문제 — 게시됨 아님"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 구매 = {conversionFactor} 재고 관리"+msgid "1 suggested batch"msgstr "제안된 배치 1개"@@ -542,6 +567,9 @@ msgstr "12개월 기간"msgid "13+ weeks"msgstr "13주 이상"+msgid "1st Negative On Hand"+msgstr "첫 번째 음수 재고"+msgid "1Y"msgstr "1년"@@ -1082,6 +1110,9 @@ msgstr "단계에 이름이 필요합니다."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "작업장 또는 작업자의 한 공정의 배치 시간 범위에 대한 저장된 예약 — 일정 생성 실행의 구체화된 결과물이며, 예측이 표시하는 대상입니다."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "MRP가 각 실행 후 작성하는 제안입니다: 새로운 공급을 발주하거나 생산하거나, 미결 발주서 라인 또는 작업 지시를 가속화, 연기, 증가, 감소 또는 취소합니다. 계획 페이지에서 적용하거나, 무시하거나, 할당할 수 있습니다."+msgid "A supplier contact and location are optional"msgstr "공급업체 담당자 및 사업장은 선택사항입니다"@@ -2006,6 +2037,12 @@ msgstr "이 작업의 공정이 이 배치에서 실행됩니다"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "공정이 작업장의 대기열에서 차지하는 위치 — 현장이 작업을 처리하는 순서입니다. 엔진은 배치 순서(가장 빠른 예상 시작)에 따라 번호를 매깁니다. 작업장 보드에서 카드 순서를 변경하면 날짜를 변경하지 않고 이를 재정의합니다."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Onshape 연동 중 예상치 못한 오류가 발생했습니다. 연동 설정을 저장하여 다시 시도하세요."@@ -2167,6 +2204,9 @@ msgstr "가격 규칙 적용"msgid "Apply Rules On Top"msgstr "규칙을 우선 적용"+msgid "Apply Suggested Changes"+msgstr "제안된 변경 사항 적용"+msgid "Apply suggestions"msgstr "제안 적용"@@ -2824,6 +2864,9 @@ msgstr "할당"msgid "Assign to Groups"msgstr "그룹에 할당"+msgid "Assign to Me"+msgstr "나에게 할당"+msgid "Assigned"msgstr "배정됨"@@ -2836,6 +2879,9 @@ msgstr "나에게 배정됨"msgid "Assignee"msgstr "담당자"+msgid "Assignees"+msgstr "담당자"+msgid "Assignment"msgstr "배정"@@ -3491,12 +3537,18 @@ msgstr "변경 통지 취소"msgid "Cancel Job"msgstr "작업 취소"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "주문 취소"msgid "Cancel Purchase Order"msgstr "발주서 취소"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "반품 취소"@@ -3548,6 +3600,12 @@ msgstr "품목 ID 없이 부품 버킷으로 이동할 수 없습니다"msgid "Cannot place order - no supplier associated with this item"msgstr "주문할 수 없습니다 - 이 품목에 연결된 공급업체가 없습니다"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "주문할 수 없습니다 — {count}개 품목에 공급업체가 없습니다"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "주문할 수 없습니다 — 1개 품목에 공급업체가 없습니다"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "전기할 수 없습니다 — 출하에 만료됨 추적 항목이 포함되어 있습니다."@@ -3753,6 +3811,9 @@ msgstr "변경 유형"msgid "Changed By"msgstr "변경자"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "이 보기에서만 변경되었습니다. 품목의 계획 호라이즌은 변경되지 않습니다."+msgid "Changelog"msgstr "변경 로그"@@ -3853,6 +3914,9 @@ msgstr "이 반품에 라인을 추가하는 방법을 선택하세요."msgid "Choose what appears on the printed job traveler."msgstr "인쇄된 작업 이동표에 나타날 내용을 선택하십시오."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "MRP이 자동으로 다시 계산할 시간을 선택하세요. 계획 페이지에서 \"다시 계산\" 버튼으로 언제든지 직접 실행할 수 있습니다."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "품목, 견적서 및 작업 지시의 BoM 탐색기에서 각 라인을 설명으로 표시할지 품목 ID로 표시할지 선택하세요."@@ -4068,6 +4132,9 @@ msgstr "회사"msgid "Company"msgstr "회사"+msgid "Company default"+msgstr "회사 기본값"+msgid "Company group"msgstr "회사 그룹"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "문서를 읽을 수 없습니다: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "{0}을 릴리스할 수 없음: {1}"@@ -5093,6 +5162,9 @@ msgstr "부서 생성됨"msgid "Created failure mode"msgstr "고장 모드 생성됨"+msgid "Created from planning"+msgstr "계획에서 생성됨"+msgid "Created gauge type"msgstr "계측기 유형이 생성되었습니다."@@ -5671,6 +5743,15 @@ msgstr "소수 자릿수"msgid "Declining balance"msgstr "정률법"+msgid "Decrease"+msgstr "감소"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "{name}님, 한밤중이군요."@@ -5737,6 +5818,9 @@ msgstr "장비 및 설비 유지보수에 대한 기본 총계정원장 비용msgid "Default GL expense account for periodic depreciation runs."msgstr "정기 감가상각 처리에 대한 기본 총계정원장 비용 계정입니다."+msgid "Default horizon (days)"+msgstr "기본 호라이즌(일)"+msgid "Default Method"msgstr "기본 방법"@@ -5788,6 +5872,15 @@ msgstr "이 분류의 신규 자산에 미리 채워지는 기본 내용연수msgid "Defaults"msgstr "기본값"+msgid "Defer"+msgstr "연기"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "이연법인세비용"@@ -6368,6 +6461,9 @@ msgstr "발견"msgid "Dismiss"msgstr "닫기"+msgid "Dismissed"+msgstr "무시됨"+msgid "Dispatch"msgstr "유지보수 지시"@@ -6744,6 +6840,9 @@ msgstr "각 공급업체의 외주 공정은 모든 작업 지시에서 새로msgid "Each, lb, ft…"msgstr "개, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "이전 주가 먼저 소진됩니다."+msgid "Earliest operation start"msgstr "최초 작업 시작"@@ -7503,6 +7602,9 @@ msgstr "이벤트 유형"msgid "Events"msgstr "이벤트"+msgid "Every 3 hours"+msgstr "3시간마다"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "모든 회사 범위의 레코드. 자격증명, 연동 토큰 및 웹훅은 포함되지 않습니다."@@ -7635,6 +7737,15 @@ msgstr "예상 입고"msgid "Expected Receipt Date"msgstr "예상 입고일"+msgid "Expedite"+msgstr "앞당기기"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "매출채권 정산 시 회수 불가로 상각된 고객 잔액에 대한 비용 계정"@@ -8112,12 +8223,18 @@ msgstr "카운트를 업데이트하지 못했습니다"msgid "Failed to update item cost"msgstr "품목 원가를 업데이트하지 못했습니다"+msgid "Failed to update job"+msgstr "작업 지시 변경 실패"+msgid "Failed to update lead times"msgstr "리드타임 업데이트 실패"msgid "Failed to update opportunity with purchase order"msgstr "발주서로 영업 기회 업데이트 실패"+msgid "Failed to update purchase order line"+msgstr "발주서 라인 변경 실패"+msgid "Failed to update quote line"msgstr "견적 라인을 업데이트하지 못했습니다"@@ -8315,6 +8432,9 @@ msgstr "이름"msgid "First Operation"msgstr "첫 번째 공정작업"+msgid "First week the projected stock goes below zero"+msgstr "예상 재고가 0 이하로 내려가는 첫 주"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "정규 MACRS 스케줄이 시작되기 전에 적용되는 1차연도 추가 공제입니다."@@ -8381,6 +8501,12 @@ msgstr "무엇이든지요. 적임자를 연결해 드립니다."msgid "Forecast"msgstr "예측"+msgid "Forecast consumption"+msgstr "예측 소모"++msgid "Forecast Consumption"+msgstr "예측 소모"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "예측 방법: <0>{0}</0>. 이 행은 활성 작업 지시에서 파생되지 않았으므로 부모 소스를 사용할 수 없습니다."@@ -8829,7 +8955,7 @@ msgstr "일정을 짤 수 없는 공정이 있습니다"msgid "Headers"msgstr "헤더"-msgid "healthy"+msgid "Healthy"msgstr "정상"msgid "Help"@@ -8979,6 +9105,9 @@ msgstr "계산 날짜 이후 선급 할인을 사용할 수 있는 일 수입니msgid "How many days after the calculation date the full amount is due."msgstr "계산일로부터 전체 금액이 만기되는 일수입니다."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "미결 발주가 필요한 날짜로부터 이 일수의 범위 내에 도착하면 MRP가 일정 변경을 제안하지 않습니다. 설정 → 계획에서 설정하며, 기본값은 7일입니다."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "이 고객이 송장 날짜로부터 지불하는 데 주어진 일수입니다. 고객 송장의 기본 마감일을 결정합니다."@@ -9253,6 +9382,9 @@ msgstr "이 단계에서"msgid "In use"msgstr "사용 중"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "회사의 시간대({companyTimeZone})에 따릅니다."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "엔터프라이즈 설정의 개발자 아래에서 개인 OAuth 애플리케이션의 권한을 편집하여 \"애플리케이션이 문서에 쓸 수 있음\"을 포함하도록 한 후 연동 설정을 다시 저장하세요."@@ -9265,9 +9397,6 @@ msgstr "인앱 알림은 항상 전달됩니다. 이메일 또는 Slack으로도msgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "인앱 알림은 항상 전달됩니다. 이메일로도 전달받을 주제를 선택하세요."-msgid "inactive"-msgstr "비활성"-msgid "Inactive"msgstr "비활성"@@ -9325,6 +9454,15 @@ msgstr "인코텀즈"msgid "Incoterm Location"msgstr "인코텀즈 위치"+msgid "Increase"+msgstr "증가"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "간접"@@ -9364,6 +9502,9 @@ msgstr "그룹에서 상속됨: 이 계정이 이익잉여금(수익)으로 종msgid "Inherited from the parent group."msgstr "상위 그룹에서 상속됨."+msgid "inherits {inheritedName}"+msgstr "상속: {inheritedName}"+msgid "Input"msgstr "입력"@@ -9893,6 +10034,9 @@ msgstr "작업 우선순위"msgid "Job readable"msgstr "작업 가독성"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "작업 이동표"@@ -10108,9 +10252,15 @@ msgstr "마지막 사용"msgid "Late in the evening, {name}."msgstr "{name}님, 저녁이 늦어가는군요."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "이전 주가 모두 소진된 후 이후 주가 소진됩니다."+msgid "Latest operation end"msgstr "최신 작업 종료"+msgid "Latest Order Date"+msgstr "최종 주문 날짜"+msgid "Latitude"msgstr "위도"@@ -10153,6 +10303,9 @@ msgstr "다음 리비전을 자동으로 사용하려면 공백으로 두세요"msgid "Leave empty for exact match"msgstr "정확히 일치시키려면 비워두세요"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "MRP가 계획한 모든 것을 표시하려면 공란으로 두거나 0을 입력하세요."+msgid "Leave this page"msgstr "이 페이지 나가기"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "라인"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "발주서 입고가 전기된 후 라인이 여기에 표시되며, 다른 공급업체 반품에서 아직 승인되지 않은 수량에만 표시됩니다. 맹목적 반품의 경우 라인 품목 추가를 사용하세요."+msgstr "발주서 입고가 전기된 후 라인이 여기에 나타나며, 다른 공급업체 반품에서 아직 승인되지 않은 수량에만 적용됩니다. 맹목적 반품의 경우 라인 항목 추가를 사용하세요."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "수주 출하가 전기된 후 라인이 여기에 나타나며, 다른 RMA에서 이미 승인되지 않은 수량만 나타납니다. 맹목적 반품의 경우 「라인 항목 추가」를 사용하세요."@@ -10441,6 +10594,12 @@ msgstr "상세 설명"msgid "Longitude"msgstr "경도"+msgid "Look ahead (weeks)"+msgstr "향후 조회 (주)"++msgid "Look back (weeks)"+msgstr "이전 조회 (주)"+msgid "Looks empty here"msgstr "이곳은 비어 있는 것 같습니다"@@ -10570,6 +10729,12 @@ msgstr "유지보수 유형"msgid "Make"msgstr "제조"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "{quantity} 제조"+msgid "Make Active"msgstr "활성으로 설정"@@ -10847,6 +11012,9 @@ msgstr "자재 품목"msgid "Material Planning"msgstr "물질 계획"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "자재 계획은 오늘부터 이 많은 날짜 내에 필요한 조치 및 제안된 주문만 표시하므로, 먼 미래의 필요는 중요해질 때까지 방해가 되지 않습니다. 품목의 자체 계획 호라이즌이 이 기본값보다 우선합니다."+msgid "Material Properties"msgstr "자재 속성"@@ -11231,6 +11399,18 @@ msgstr "MRP(계획)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP는 3시간마다 자동으로 실행되지만, 여기서 수동으로 실행할 수도 있습니다."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP는 매일 {time}({timeZone})에 자동으로 실행되지만, 여기서 수동으로 실행할 수 있습니다."++msgid "MRP Schedule"+msgstr "MRP 일정"++msgid "MRP Suggestions"+msgstr "MRP 제안"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP는 주문의 날짜가 이 일수보다 더 차이날 때만 기존 주문을 이동할 것을 제안합니다. 작은 차이는 작업 목록을 조용하게 유지하기 위해 무시됩니다."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "여러 작업 지시가 이 공법에서 동시에 실행될 수 있습니다 — 예: 레이저 테이블, 용광로 또는 도금 조에"@@ -11498,9 +11678,6 @@ msgstr "신규 지불 조건"msgid "New Picking List"msgstr "새 피킹 리스트"-msgid "New PO"-msgstr "새 구매주문"-msgid "New Price Override"msgstr "새 가격 재정의"@@ -12140,7 +12317,7 @@ msgid "No results found"msgstr "결과가 없습니다"msgid "No returnable lines for this customer"-msgstr "이 고객에 대한 반품 가능 라인이 없습니다."+msgstr "이 고객을 위한 반품 가능한 라인이 없습니다."msgid "No returnable lines for this supplier"msgstr "이 공급업체에 대한 반품 가능 라인이 없습니다."@@ -12205,6 +12382,9 @@ msgstr "보관 단위가 없습니다."msgid "No storage units or tracking numbers match."msgstr "일치하는 보관 단위 또는 추적 번호가 없습니다."+msgid "No Supplier"+msgstr "공급업체 없음"+msgid "No suppliers yet"msgstr "아직 공급업체가 없습니다"@@ -12555,6 +12735,9 @@ msgstr "정시 납품"msgid "Onboard your agent to Carbon"msgstr "Carbon에 에이전트 등록"+msgid "Once a day"+msgstr "하루에 한 번"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "작업 지시 소요량 더하기 이 빈에서의 미결 이송"msgid "Open jobs"msgstr "미결 작업 지시"+msgid "Open Jobs"+msgstr "미결 작업 지시"+msgid "Open menu"msgstr "메뉴 열기"msgid "Open navigation"msgstr "탐색 열기"+msgid "Open Orders"+msgstr "미결 주문"+msgid "Open payables by supplier and age"msgstr "공급업체 및 기간별 미결 매입채무"@@ -12932,9 +13121,18 @@ msgstr "이 작업 지시를 위해 {0} × {substitute} 발주"msgid "Order {0} for this job"msgstr "이 작업의 주문 {0}"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "{quantity} 주문"+msgid "Order by"msgstr "정렬 기준"+msgid "Order By"+msgstr "정렬 기준"+msgid "Order date"msgstr "주문 날짜"@@ -13091,6 +13289,9 @@ msgstr "책임자"msgid "Owner (cost center)"msgstr "책임자 (원가 센터)"+msgid "Ownership"+msgstr "담당"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "소유: {0}"@@ -13569,9 +13770,36 @@ msgstr "계획된 시간"msgid "Planning"msgstr "계획"+msgid "Planning action"+msgstr "계획 조치"++msgid "Planning horizon"+msgstr "계획 호라이즌"++msgid "Planning Horizon"+msgstr "계획 호라이즌"++msgid "Planning Horizon (Days)"+msgstr "계획 호라이즌(일)"++msgid "Planning Horizon:"+msgstr "계획 호라이즌:"++msgid "Planning Ownership"+msgstr "계획 소유권"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "계획은 제안된 보충 수량을 이 숫자의 배수로 반올림합니다."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "계획은 이 많은 날짜 내에 필요한 조치 및 제안된 주문만 표시합니다. 회사 기본값을 사용하려면 공란으로 두거나, 이 품목의 모든 것을 표시하려면 0을 입력하세요."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "계획에서 제안하는 보충 수량의 하한선으로, 공급업체-부품 레코드에 있는 공급업체의 MOQ와는 별개입니다."@@ -13980,6 +14208,9 @@ msgstr "프로젝트 계획"msgid "Project start"msgstr "프로젝트 시작"+msgid "Projected"+msgstr "예상"+msgid "Projected completion"msgstr "예상 완료"@@ -14001,6 +14232,12 @@ msgstr "예상 보유 재고"msgid "Projected stock"msgstr "예상 재고"+msgid "Projected stock by week"+msgstr "주별 예상 재고"++msgid "Projected stock is already below zero this week"+msgstr "예상 재고가 이미 이번 주에 0 이하입니다."+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "{0} 주의 예상 재고 부족"@@ -14139,6 +14376,9 @@ msgstr "발주서"msgid "Purchase Order Amount"msgstr "발주서 금액"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "발주서 승인 규칙"@@ -14166,6 +14406,9 @@ msgstr "발주서"msgid "Purchase Orders and Planning"msgstr "발주서 및 계획"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "발주서가 필요합니다"@@ -14272,9 +14515,6 @@ msgstr "수량"msgid "Qty On Hand"msgstr "현재고"-msgid "Qty to Order"-msgstr "주문 수량"-msgid "Qty. Complete"msgstr "완료 수량"@@ -14568,6 +14808,9 @@ msgstr "견적 준비 완료"msgid "ready to keep or revert"msgstr "유지하거나 되돌릴 준비됨"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "실제 주문은 먼저 해당 주의 수요 예측을 소모한 후, 회사의 범위 내에서 이전 및 이후 주의 수요를 소모합니다. 따라서 예측 수요와 실제 수요가 동일한 단위에 대해 동시에 계획되지 않습니다."+msgid "Real-time inventory and shop-floor visibility"msgstr "실시간 재고 및 현장 가시성"@@ -14880,9 +15123,15 @@ msgstr "릴리스 제어"msgid "Release Job"msgstr "작업 지시 릴리스"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "작업 지시 릴리스"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "릴리즈됨"@@ -15034,6 +15283,9 @@ msgstr "라벨 미리보기 생성 중..."msgid "Reopen"msgstr "다시 열기"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "재주문"@@ -15116,7 +15368,7 @@ msgid "Reports"msgstr "보고서"msgid "Reprice with current rules"-msgstr "현재 규칙으로 가격 재책정"+msgstr "현재 규칙으로 다시 가격책정하기"#. placeholder {0}: format(repricedPrice)msgid "Repricing with today's rules and costs gives <0>{0}</0>."@@ -15221,6 +15473,12 @@ msgstr "수리 필요"msgid "Requires staffing"msgstr "인력 필수"+msgid "Reschedule tolerance"+msgstr "재일정 허용 범위"++msgid "Reschedule Tolerance"+msgstr "재일정 허용도"+msgid "Reserve floor"msgstr "예약 최저 수량"@@ -15279,6 +15537,12 @@ msgstr "자원"msgid "Resources"msgstr "자원"+msgid "Responsible employee"+msgstr "담당 직원"++msgid "Responsible Employee"+msgstr "담당 직원"+msgid "Restock"msgstr "재입고"@@ -15654,6 +15918,9 @@ msgstr "실행 ID"msgid "Run month-end close and standard reconciliations"msgstr "월마감 및 표준 조정 작업을 수행하세요"+msgid "Run MRP"+msgstr "MRP 실행"+msgid "Run payment batches and track aging"msgstr "지불 배치를 실행하고 에이징을 추적합니다."@@ -16087,7 +16354,7 @@ msgid "Search by linear issue title..."msgstr "linear 이슈 제목으로 검색..."msgid "Search by receipt, PO, or item"-msgstr "입고, 발주서 또는 품목으로 검색"+msgstr "입고, 발주 또는 품목으로 검색"msgid "Search by shipment, sales order, or item"msgstr "출하, 수주, 또는 품목으로 검색"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "공정 선택"msgid "Select posted receipt lines from this supplier to return."-msgstr "이 공급업체에서 전기된 입고 라인을 선택하여 반품하세요."+msgstr "이 공급업체의 전기된 입고 라인을 선택하여 반품하세요."msgid "Select posted shipment lines to this customer to return."msgstr "이 고객의 전기된 출하 라인을 선택하여 반품하세요."@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "세션 잠김"msgid "Set a customer on this return to add from a shipment."-msgstr "출하에서 추가하려면 이 반품에 고객을 설정하세요."+msgstr "출하에서 추가할 고객을 이 반품에 설정하세요."msgid "Set a supplier on this return to add from a receipt."msgstr "이 반품에 공급업체를 지정하여 입고에서 추가하세요."@@ -17243,6 +17510,9 @@ msgstr "시작"msgid "Start {0} Day Free Trial"msgstr "{0}일 무료 체험 시작"+msgid "Start By"+msgstr "시작 기준"+msgid "Start counting"msgstr "실사 시작"@@ -17386,6 +17656,9 @@ msgstr "단계들은 독립적으로 구축되며 하나의 부품으로 결합msgid "Still dark out on the floor."msgstr "작업장은 여전히 어둡습니다."+msgid "Stock Availability"+msgstr "재고 가용성"+msgid "Stock movement corrected"msgstr "재고 이동 수정됨"@@ -17624,6 +17897,15 @@ msgstr "일치 제안"msgid "Suggest with AI"msgstr "AI로 제안"+msgid "Suggested Jobs"+msgstr "제안된 작업 지시"++msgid "Suggested Orders"+msgstr "제안된 주문"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "이 품목의 계획 호라이즌 이후에 필요한 제안된 주문입니다. 호라이즌을 확장하여 포함하세요."+msgid "Suggested orders you haven't placed yet."msgstr "아직 발주하지 않은 제안 주문입니다."@@ -17874,7 +18156,7 @@ msgstr "동기화"msgid "Sync Activity"msgstr "동기화 활동"-msgid "sync off"+msgid "Sync Off"msgstr "동기화 해제"msgid "Sync operation"@@ -18642,6 +18924,9 @@ msgstr "현금 할인 비율입니다. 할인이 없으면 0을 사용하세요.msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "이 유형의 신규 직원이 자동으로 받는 권한 세트입니다. 여기서 수정하면 이후 신규 채용자에게만 템플릿이 적용되며, 기존 직원은 명시적으로 일괄 업데이트하지 않는 한 현재 권한을 유지합니다."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "계획 조치가 할당되는 사람입니다: 해당 사업장의 품목 책임자, 없으면 품목 그룹의 책임자, 없으면 사업장의 책임자, 없으면 회사 기본 책임자입니다."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "작업과 재고가 위치하는 공장, 창고, 사업장"@@ -18663,6 +18948,9 @@ msgstr "이 작업장이 실행할 수 있는 공법으로, 공정 일정 시msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "제공자가 차원 대상을 제공하지 않습니다. 먼저 제공자에서 기능을 활성화하세요(예: 추적 카테고리, 클래스 추적 또는 필드)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "이 라인의 가격 책정 수량 구간점; 각 열은 구매자-공급업체 협상 및 다운스트림 문서로 변환하기 위한 자체 단가를 포함합니다."@@ -18991,6 +19279,9 @@ msgstr "이 전표들은 아직 초안 상태이므로 이 기간에 차변 및msgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "이 공정들은 여러 공급업체에서 처리 가능합니다. 각 공정마다 공급업체를 선택하세요."+msgid "These orders could not be loaded. Close and reopen to try again."+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 "이 부품들이 이 부품으로 대체됩니다. 각 규칙은 기존 부품에 설정되어 있으니 규칙을 변경하려면 해당 부품을 열어주세요."@@ -19469,6 +19760,9 @@ msgstr "공차+"msgid "Tolerance (+/-)"msgstr "공차(+/-)"+msgid "Tolerance (days)"+msgstr "허용치 (일)"+msgid "Tomorrow"msgstr "내일"@@ -19847,7 +20141,7 @@ msgstr "실행 취소"msgid "Ungroup"msgstr "그룹 해제"-msgid "unhealthy"+msgid "Unhealthy"msgstr "문제 있음"msgid "Uninstall"@@ -20936,6 +21230,9 @@ msgstr "{name}이(가) 변경될 때"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "완성 제품의 보존 기간이 계산됨으로 설정된 경우, 계산에 영향을 주는 소모된 입력을 선택하세요."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "수주 또는 작업 지시가 남은 예측이 없는 주에 도착하면, 별도로 계산되지 않고 인근 주의 예측을 소모합니다. 둘 다 0으로 설정하면 같은 주 내에서만 계산됩니다."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "일련번호 또는 배치가 만료되는 시점과 만료 후 사용 시의 처리 방식입니다 — 회사 정책은 경고, 차단, 또는 승인 후 차단 중 하나로 설정할 수 있습니다."@@ -21128,6 +21425,9 @@ msgstr "누가 무엇을, 어떤 형식으로 교육받는지. 귀사가 할 일msgid "Who has to approve quotes, orders, and purchases — and when"msgstr "누가 견적, 주문, 구매를 승인해야 하는지 — 그리고 언제"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "MRP 계획 조치를 누가 소유하는가. 사업장은 회사 기본값을 상속하고, 품목 그룹은 해당 사업장을 상속합니다. 가장 구체적인 할당이 적용되며, 각 품목은 계획 탭에서 재정의할 수 있습니다."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "유지보수 관련 유지보수 지시에 대한 알림을 받아야 하는 사람은 누구입니까?"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex a8a959b59a..cc66ccd7fa 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# wiersz łączy się z danymi spoza tej firmy, dlategomsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# wiersz łączy się z danymi spoza tej firmy, dlatego nie można go zabezpieczyć. Pominięcie go pozwala na zabezpieczenie wszystkiego innego.} other {# wierszy łączy się z danymi spoza tej firmy, dlatego nie można ich zabezpieczyć. Pominięcie ich pozwala na zabezpieczenie wszystkiego innego.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# tydzień} few {# tygodnie} many {# tygodni} other {# tygodnia}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {Planista traktuje ten składnik jako jedno sztywne ciało — jeden krok w instrukcjach. Uruchom ponownie plan, aby zastosować.} other {Planista traktuje te # składniki jako jedno sztywne ciało — jeden krok w instrukcjach. Uruchom ponownie plan, aby zastosować.}}"@@ -107,6 +111,10 @@ msgstr "Nie można usunąć {0}, ponieważ jest nadal używana przez: {where}. Nmsgid "{0} cells with deltas"msgstr "{0} komórek z różnicami"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} zużyto"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} wartości"msgid "{0} values missing"msgstr "{0} brakujących wartości"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} będzie zapisany jako {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# konto z saldem} other {# konta z saldem}}"msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# kurs} other {# kursy}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# więcej po {fenceLabel}} few {# więcej po {fenceLabel}} many {# więcej po {fenceLabel}} other {# więcej po {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Rozpuść # partię produkcyjną} few {Rozpuść # partie produkcyjne} many {Rozpuść # partii produkcyjnych} other {Rozpuść # partii produkcyjnych}}"@@ -340,6 +356,9 @@ msgstr "{days}d"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "${delegatedTo} wysyła to do Twojej księgi, więc Carbon tego nie wysyła. Twój zapisany wybór jest zachowywany na wypadek zmian."+msgid "{dismissed} dismissed"+msgstr "{dismissed} odrzucone"+msgid "{done} of {total} phases complete"msgstr "{done} z {total} faz ukończonych"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} więcej: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} wstawiono, {updated} zaktualizowano, {0} wymagają naprawy, {1} pominięte."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# dzień} few {# dni} many {# dni} other {# dnia}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# linia} other {# linii}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# faza pozostała} other {# faz pozostało}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} zasobów · {reservationCount} rezerwacji · {jobCount} zleceń produkcyjnych"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} uprawnień"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Najpierw zmapuj # pozostałe wymagamsgid "{unschedulableCount} can't be scheduled"msgstr "Nie można zaplanować {unschedulableCount}"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} zleceń produkcyjnych zaktualizowanych"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "Przesłano {uploadedFileName} — pola wypełniono na podstawie dokumentu."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 operacji"+msgid "0 suggests a move for any date difference."+msgstr "0 sugeruje przesunięcie dla dowolnej różnicy dat."+msgid "0-4 weeks"msgstr "0-4 tygodnie"@@ -518,9 +543,6 @@ msgstr "1 wersja robocza zapisu księgowego"msgid "1 job created"msgstr "1 zadanie utworzone"-msgid "1 job updated"-msgstr "1 zadanie zaktualizowane"-msgid "1 part skipped — it already has an open job"msgstr "1 część pominięta — ma już otwarte zadanie"@@ -530,6 +552,9 @@ msgstr "1 część pominięta — nic do zrobienia"msgid "1 problem — not published"msgstr "1 problem — nie opublikowano"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Zakup = {conversionFactor} Zapasy"+msgid "1 suggested batch"msgstr "1 sugerowana partia"@@ -542,6 +567,9 @@ msgstr "12 miesięcznych okresów"msgid "13+ weeks"msgstr "13+ tygodni"+msgid "1st Negative On Hand"+msgstr "1. Ujemny Stan Magazynowy"+msgid "1Y"msgstr "1 rok"@@ -1082,6 +1110,9 @@ msgstr "Krok wymaga nazwy."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Zapisana rezerwacja stanowiska roboczego lub operatora dla przedziału czasowego umieszczenia jednej operacji — zmaterializowany wynik przebiegu harmonogramu i to, co rysuje Prognoza."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Propozycja, którą MRP generuje po każdym uruchomieniu: Zamów lub Produkuj nowe pokrycie, albo Przyspiesz, Odłóż, Zwiększ, Zmniejsz lub Anuluj otwartą pozycję zamówienia zakupu bądź zlecenie produkcyjne. Zastosuj ją na stronie planowania, odrzuć lub przypisz ją."+msgid "A supplier contact and location are optional"msgstr "Kontakt dostawcy i lokalizacja są opcjonalne"@@ -2006,6 +2037,12 @@ msgstr "Operacja tego zlecenia jest w tej partii"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "Pozycja operacji w kolejce stanowiska roboczego — kolejność, w jakiej brygada podejmuje prace. Silnik numeruje ją na podstawie kolejności umieszczenia (najwcześniejszy planowany start najpierw); zmiana kolejności kart na tablicy Stanowisk roboczych zmienia ją bez zmiany dat."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Podczas łączenia się z Onshape wystąpił nieoczekiwany błąd. Zapisz ustawienia integracji, aby spróbować ponownie."@@ -2167,6 +2204,9 @@ msgstr "Zastosuj reguły cenowe"msgid "Apply Rules On Top"msgstr "Zastosuj reguły na górze"+msgid "Apply Suggested Changes"+msgstr "Zastosuj sugerowane zmiany"+msgid "Apply suggestions"msgstr "Zastosuj propozycje"@@ -2824,6 +2864,9 @@ msgstr "Przypisz do"msgid "Assign to Groups"msgstr "Przypisz do grup"+msgid "Assign to Me"+msgstr "Przypisz mnie"+msgid "Assigned"msgstr "Przydzielone"@@ -2836,6 +2879,9 @@ msgstr "Przypisane do mnie"msgid "Assignee"msgstr "Osoba przypisana"+msgid "Assignees"+msgstr "Osoby przypisane"+msgid "Assignment"msgstr "Przypisanie"@@ -3491,12 +3537,18 @@ msgstr "Anuluj zawiadomienie o zmianie"msgid "Cancel Job"msgstr "Anuluj zadanie"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Anuluj zamówienie"msgid "Cancel Purchase Order"msgstr "Anuluj zamówienie zakupu"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Anuluj zwrot"@@ -3548,6 +3600,12 @@ msgstr "Nie można przenieść do zasobnika części bez identyfikatora elementumsgid "Cannot place order - no supplier associated with this item"msgstr "Nie można złożyć zamówienia - brak dostawcy powiązanego z tym artykułem"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Nie można złożyć zamówienia — {count} pozycji nie ma dostawcy"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Nie można złożyć zamówienia — 1 pozycja nie ma dostawcy"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Nie można zaksięgować — wysyłka zawiera wygasłe jednostki śledzone."@@ -3753,6 +3811,9 @@ msgstr "Zmień typ"msgid "Changed By"msgstr "Zmienione przez"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Zmienione tylko dla tego widoku. Horyzont planowania artykułu nie jest aktualizowany."+msgid "Changelog"msgstr "Historia zmian"@@ -3853,6 +3914,9 @@ msgstr "Wybierz sposób dodania pozycji do tego zwrotu."msgid "Choose what appears on the printed job traveler."msgstr "Wybierz, co pojawia się na drukowanym przewodniku zlecenia produkcyjnego."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Wybierz, kiedy MRP będzie się automatycznie przeliczać. Możesz go również uruchomić ręcznie w dowolnym momencie, korzystając z opcji Przelicz ponownie na stronach Planowania."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Wybierz, czy eksplorator listy materiałów w artykułach, ofertach i zleceniach produkcyjnych wyświetla dla każdej pozycji jej opis czy ID artykułu."@@ -4068,6 +4132,9 @@ msgstr "Firmy"msgid "Company"msgstr "Firma"+msgid "Company default"+msgstr "Domyślne dla firmy"+msgid "Company group"msgstr "Grupa firm"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Nie można odczytać dokumentu: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Nie można było zwolnić {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "Utworzono dział"msgid "Created failure mode"msgstr "Utworzony tryb awarii"+msgid "Created from planning"+msgstr "Utworzono z planowania"+msgid "Created gauge type"msgstr "Utworzono typ przyrządu"@@ -5671,6 +5743,15 @@ msgstr "Miejsca Dziesiętne"msgid "Declining balance"msgstr "Metoda degresywna"+msgid "Decrease"+msgstr "Zmniejsz"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Głębokie noce, {name}."@@ -5737,6 +5818,9 @@ msgstr "Domyślne Konto księgowe wydatków dla Urządzeń i Utrzymania ruchu famsgid "Default GL expense account for periodic depreciation runs."msgstr "Domyślne konto wydatków w księdze głównej dla okresowych rozliczeń amortyzacji."+msgid "Default horizon (days)"+msgstr "Domyślny horyzont (dni)"+msgid "Default Method"msgstr "Metoda domyślna"@@ -5788,6 +5872,15 @@ msgstr "Domyślny okres użytkowania, który jest automatycznie wypełniany dlamsgid "Defaults"msgstr "Ustawienia domyślne"+msgid "Defer"+msgstr "Przełóż"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Odroczone Wydatki Podatkowe"@@ -6368,6 +6461,9 @@ msgstr "Odkrywanie"msgid "Dismiss"msgstr "Odrzuć"+msgid "Dismissed"+msgstr "Odrzucone"+msgid "Dispatch"msgstr "Zlecenie utrzymania ruchu"@@ -6744,6 +6840,9 @@ msgstr "Operacje zewnętrzne każdego dostawcy z każdego zlecenia produkcyjnegomsgid "Each, lb, ft…"msgstr "Każdy, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "Wcześniejsze tygodnie są zużywane najpierw."+msgid "Earliest operation start"msgstr "Najwcześniejszy początek operacji"@@ -7503,6 +7602,9 @@ msgstr "Typ zdarzenia"msgid "Events"msgstr "Zdarzenia"+msgid "Every 3 hours"+msgstr "Co 3 godziny"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Wszystkie rekordy firmy. Dane uwierzytelniające, tokeny integracji i webhooki nigdy nie są dołączane."@@ -7635,6 +7737,15 @@ msgstr "Oczekiwane Potwierdzenie Odbioru"msgid "Expected Receipt Date"msgstr "Oczekiwana data przyjęcia"+msgid "Expedite"+msgstr "Przyspiesz"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Konto wydatków dla sald klientów odpisanych jako nieściągalne przy rozliczeniu należności"@@ -8112,12 +8223,18 @@ msgstr "Nie udało się zaktualizować liczenia"msgid "Failed to update item cost"msgstr "Nie udało się zaktualizować kosztu pozycji"+msgid "Failed to update job"+msgstr "Nie udało się zaktualizować zlecenia produkcyjnego"+msgid "Failed to update lead times"msgstr "Nie udało się zaktualizować czasów realizacji"msgid "Failed to update opportunity with purchase order"msgstr "Nie udało się zaktualizować szansy sprzedaży za pomocą zamówienia zakupu"+msgid "Failed to update purchase order line"+msgstr "Nie udało się zaktualizować pozycji zamówienia zakupu"+msgid "Failed to update quote line"msgstr "Nie udało się zaktualizować pozycji oferty"@@ -8315,6 +8432,9 @@ msgstr "Imię"msgid "First Operation"msgstr "Pierwsza operacja"+msgid "First week the projected stock goes below zero"+msgstr "Pierwszy tydzień, w którym prognozowany zapas przechodzi poniżej zera"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Środek Trwały"@@ -8381,6 +8501,12 @@ msgstr "w sprawie czegokolwiek. Zaangażują odpowiednią osobę."msgid "Forecast"msgstr "Prognoza"+msgid "Forecast consumption"+msgstr "Zużycie prognozy"++msgid "Forecast Consumption"+msgstr "Zużycie prognozy"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Metoda prognozy: <0>{0}</0>. Ten wiersz nie został wyprowadzony ze zleceń produkcyjnych, dlatego żadne źródła nadrzędne nie są dostępne."@@ -8829,8 +8955,8 @@ msgstr "Ma operacje, które nie można zaplanować"msgid "Headers"msgstr "Nagłówki"-msgid "healthy"-msgstr "zdrowy"+msgid "Healthy"+msgstr "Zdrowy"msgid "Help"msgstr "Pomoc"@@ -8979,6 +9105,9 @@ msgstr "Ile dni po dacie obliczenia rabat za wcześniejszą płatność jest jesmsgid "How many days after the calculation date the full amount is due."msgstr "Ile dni po dacie obliczenia pełna kwota jest należna."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Ile dni otwarte zamówienie może przybyć od daty, w której jest potrzebne, zanim MRP zasugeruje jego przesunięcie. Ustaw w Ustawienia → Planowanie; domyślnie 7 dni."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Ile dni od daty faktury ten klient ma na zapłatę; określa domyślny termin płatności na fakturach klientów."@@ -9253,6 +9382,9 @@ msgstr "W tym kroku"msgid "In use"msgstr "W użyciu"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "W strefie czasowej Twojej firmy ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "W ustawieniach Enterprise w sekcji Developer edytuj uprawnienia prywatnej aplikacji OAuth, aby uwzględnić „Aplikacja może zapisywać w Twoich dokumentach”, a następnie ponownie zapisz ustawienia integracji."@@ -9265,9 +9397,6 @@ msgstr "Powiadomienia w aplikacji są zawsze dostarczane. Wybierz, które tematymsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Powiadomienia w aplikacji są zawsze dostarczane. Wybierz, które tematy mają do Ciebie dotrzeć również pocztą e-mail."-msgid "inactive"-msgstr "nieaktywny"-msgid "Inactive"msgstr "Nieaktywny"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Lokalizacja Incoterm"+msgid "Increase"+msgstr "Zwiększ"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Pośredni"@@ -9364,6 +9502,9 @@ msgstr "Odziedziczone z grupy: czy to konto zamyka się do zysków zatrzymanychmsgid "Inherited from the parent group."msgstr "Odziedziczone z grupy nadrzędnej."+msgid "inherits {inheritedName}"+msgstr "dziedziczy {inheritedName}"+msgid "Input"msgstr "Dane wejściowe"@@ -9893,6 +10034,9 @@ msgstr "Priorytet zadania"msgid "Job readable"msgstr "Czytelne zadanie"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Przewodnik zlecenia"@@ -10108,9 +10252,15 @@ msgstr "Ostatnio używany"msgid "Late in the evening, {name}."msgstr "Późny wieczór, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Późniejsze tygodnie są zużywane, gdy wcześniejsze zostały wyczerpane."+msgid "Latest operation end"msgstr "Koniec ostatniej operacji"+msgid "Latest Order Date"+msgstr "Ostatnia data zamówienia"+msgid "Latitude"msgstr "Szerokość geograficzna"@@ -10153,6 +10303,9 @@ msgstr "Pozostaw puste, aby automatycznie użyć następnej rewizji"msgid "Leave empty for exact match"msgstr "Pozostaw puste dla dokładnego dopasowania"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Pozostaw puste lub wpisz 0, aby pokazać wszystko, co planuje MRP."+msgid "Leave this page"msgstr "Opuść tę stronę"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Linie"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Pozycje pojawiają się tutaj po zaksięgowaniu przyjęcia zamówienia zakupu, tylko dla ilości nie już uwzględnionych w innym zwrocie dostawcy. Użyj opcji Dodaj pozycję dla ślepego zwrotu."+msgstr "Pozycje pojawiają się tutaj po zaksięgowaniu przyjęcia zamówienia zakupu i tylko dla ilości, które nie zostały autoryzowane na inny zwrot. Aby dodać żądane zwroty, użyj Dodaj pozycję."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Pozycje pojawiają się tutaj po zaksięgowaniu wysyłki zamówienia sprzedaży i tylko dla ilości, które nie zostały już autoryzowane w innym RMA. Użyj opcji Dodaj pozycję dla zwrotu ślepego."@@ -10441,6 +10594,12 @@ msgstr "Długi opis"msgid "Longitude"msgstr "Długość geograficzna"+msgid "Look ahead (weeks)"+msgstr "Zajrzyj w przód (tygodnie)"++msgid "Look back (weeks)"+msgstr "Zajrzyj wstecz (tygodnie)"+msgid "Looks empty here"msgstr "Wygląda na to, że tu nic nie ma"@@ -10570,6 +10729,12 @@ msgstr "Typ utrzymania ruchu"msgid "Make"msgstr "Wytwórz"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "Wytwórz {quantity}"+msgid "Make Active"msgstr "Ustaw jako aktywny"@@ -10847,6 +11012,9 @@ msgstr "Artykuł Materiału"msgid "Material Planning"msgstr "Planowanie materiałów"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "Planowanie materiałów pokazuje tylko działania i sugerowane zamówienia należne w ciągu tylu dni od dziś, aby dalekozasięgne potrzeby nie stały w drodze, dopóki się nie będą ważne. Własny horyzont planowania artykułu zastępuje tę wartość domyślną."+msgid "Material Properties"msgstr "Właściwości materiału"@@ -11231,6 +11399,18 @@ msgstr "MRP (planowanie)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP uruchamia się automatycznie co 3 godziny, ale możesz uruchomić go ręcznie tutaj."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP uruchamia się automatycznie każdego dnia o {time} ({timeZone}), ale możesz uruchomić to ręcznie tutaj."++msgid "MRP Schedule"+msgstr "Harmonogram MRP"++msgid "MRP Suggestions"+msgstr "Propozycje MRP"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP sugeruje przesunięcie istniejącego zamówienia tylko gdy jego data różni się o więcej niż określona liczba dni. Mniejsze różnice są ignorowane, aby nie przeładowywać listy zadań."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Wiele zleceń produkcyjnych może działać na tym procesie jednocześnie — np. laser, piec lub łaźnia galwaniczna"@@ -11498,9 +11678,6 @@ msgstr "Nowe Warunki płatności"msgid "New Picking List"msgstr "Nowa Lista kompletacyjna"-msgid "New PO"-msgstr "Nowe ZO"-msgid "New Price Override"msgstr "Nowe Nadpisanie ceny"@@ -12143,7 +12320,7 @@ msgid "No returnable lines for this customer"msgstr "Brak zwracalnych pozycji dla tego klienta"msgid "No returnable lines for this supplier"-msgstr "Brak pozycji do zwrotu dla tego dostawcy"+msgstr "Brak zwracalnych pozycji dla tego dostawcy"msgid "No returnable lines match your search"msgstr "Żadne pozycje do zwrotu nie pasują do Twojego wyszukiwania"@@ -12205,6 +12382,9 @@ msgstr "Brak jednostki magazynowania"msgid "No storage units or tracking numbers match."msgstr "Brak zgodnych jednostek magazynowych ani numerów śledzenia."+msgid "No Supplier"+msgstr "Brak dostawcy"+msgid "No suppliers yet"msgstr "Brak dostawców"@@ -12555,6 +12735,9 @@ msgstr "Dostawa na czas"msgid "Onboard your agent to Carbon"msgstr "Dodaj swojego agenta do Carbon"+msgid "Once a day"+msgstr "Raz dziennie"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Otwarte zapotrzebowanie ze zleceń plus pozostające przesunięcia z tegmsgid "Open jobs"msgstr "Otwarte zlecenia produkcyjne"+msgid "Open Jobs"+msgstr "Otwarte Zlecenia produkcyjne"+msgid "Open menu"msgstr "Otwórz menu"msgid "Open navigation"msgstr "Otwórz nawigację"+msgid "Open Orders"+msgstr "Otwarte Zamówienia"+msgid "Open payables by supplier and age"msgstr "Otwarte zobowiązania wg dostawcy i wieku"@@ -12932,9 +13121,18 @@ msgstr "Zamów {0} × {substitute} dla tego zlecenia produkcyjnego"msgid "Order {0} for this job"msgstr "Zamów {0} dla tego zadania"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "Zamów {quantity}"+msgid "Order by"msgstr "Zamów do"+msgid "Order By"+msgstr "Sortuj Wg"+msgid "Order date"msgstr "Data zamówienia"@@ -13091,6 +13289,9 @@ msgstr "Właściciel"msgid "Owner (cost center)"msgstr "Właściciel (miejsce powstawania kosztów)"+msgid "Ownership"+msgstr "Przypisanie"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Odpowiada za: {0}"@@ -13569,9 +13770,36 @@ msgstr "Zaplanowany czas"msgid "Planning"msgstr "Planowanie"+msgid "Planning action"+msgstr "Akcja planowania"++msgid "Planning horizon"+msgstr "Horyzont planowania"++msgid "Planning Horizon"+msgstr "Horyzont Planowania"++msgid "Planning Horizon (Days)"+msgstr "Horyzont Planowania (dni)"++msgid "Planning Horizon:"+msgstr "Horyzont Planowania:"++msgid "Planning Ownership"+msgstr "Właściciel planowania"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Rundy planowania zasugerowały uzupełnienie do całkowitej wielokrotności tej liczby."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "Planowanie pokazuje tylko działania i sugerowane zamówienia należne w ciągu tylu dni. Pozostaw puste, aby użyć ustawienia domyślnego firmy, lub wpisz 0, aby pokazać wszystko dla tego artykułu."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Dolna granica planowania dla sugerowanej ilości uzupełnienia; różni się od MOQ dostawcy, która znajduje się w rekordie części dostawcy."@@ -13980,6 +14208,9 @@ msgstr "Plan Projektu"msgid "Project start"msgstr "Początek projektu"+msgid "Projected"+msgstr "Prognozowane"+msgid "Projected completion"msgstr "Przewidywane zakończenie"@@ -14001,6 +14232,12 @@ msgstr "Prognozowana niedostępność zapasów w tygodniu {0}"msgid "Projected stock"msgstr "Prognozowany zapas"+msgid "Projected stock by week"+msgstr "Prognozowany Zapas wg Tygodnia"++msgid "Projected stock is already below zero this week"+msgstr "Prognozowany zapas jest już poniżej zera w tym tygodniu"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Projekcja braku zapasu na tydzień {0}"@@ -14139,6 +14376,9 @@ msgstr "Zamówienie Zakupu"msgid "Purchase Order Amount"msgstr "Kwota Zamówienia Zakupu"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Reguła zatwierdzania zamówienia zakupu"@@ -14166,6 +14406,9 @@ msgstr "Zamówienia Zakupu"msgid "Purchase Orders and Planning"msgstr "Zamówienia zakupu i planowanie"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Wymagane zamówienia zakupu"@@ -14272,9 +14515,6 @@ msgstr "Ilość"msgid "Qty On Hand"msgstr "Ilość na magazynie"-msgid "Qty to Order"-msgstr "Ilość do zamówienia"-msgid "Qty. Complete"msgstr "Ilość ukończona"@@ -14568,6 +14808,9 @@ msgstr "Gotowe do oferty"msgid "ready to keep or revert"msgstr "gotowe do zachowania lub przywrócenia"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Rzeczywiste zamówienia najpierw zużywają prognozę zapotrzebowania na ich własny tydzień, następnie wcześniejsze i późniejsze tygodnie w ramach okna firmy, dzięki czemu prognoza i rzeczywiste zapotrzebowanie nigdy nie są jednocześnie planowane dla tych samych jednostek."+msgid "Real-time inventory and shop-floor visibility"msgstr "Widoczność zapasów i hali produkcyjnej w czasie rzeczywistym"@@ -14880,9 +15123,15 @@ msgstr "Kontrola Zwolnienia"msgid "Release Job"msgstr "Zwolnij zadanie"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Zwolnij zlecenia produkcyjne"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Wydane"@@ -15034,6 +15283,9 @@ msgstr "Renderowanie podglądu etykiety..."msgid "Reopen"msgstr "Ponownie otwórz"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Zmień kolejność"@@ -15221,6 +15473,12 @@ msgstr "Wymaga naprawy"msgid "Requires staffing"msgstr "Wymaga obsady"+msgid "Reschedule tolerance"+msgstr "Tolerancja przesunięcia"++msgid "Reschedule Tolerance"+msgstr "Tolerancja przesunięcia"+msgid "Reserve floor"msgstr "Poziom rezerwy"@@ -15279,6 +15537,12 @@ msgstr "zasoby"msgid "Resources"msgstr "Zasoby"+msgid "Responsible employee"+msgstr "Odpowiedzialny pracownik"++msgid "Responsible Employee"+msgstr "Pracownik odpowiedzialny"+msgid "Restock"msgstr "Uzupełnianie"@@ -15654,6 +15918,9 @@ msgstr "ID uruchomienia"msgid "Run month-end close and standard reconciliations"msgstr "Przeprowadź zamknięcie miesiąca i standardowe uzgodnienia"+msgid "Run MRP"+msgstr "Uruchom MRP"+msgid "Run payment batches and track aging"msgstr "Uruchamiaj partie płatności i śledź wiek należności"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "Wybierz operacje"msgid "Select posted receipt lines from this supplier to return."-msgstr "Wybierz pozycje przyjęcia zaksięgowane od tego dostawcy do zwrotu."+msgstr "Wybierz zaksięgowane pozycje przyjęcia od tego dostawcy do zwrotu."msgid "Select posted shipment lines to this customer to return."msgstr "Wybierz zaksięgowane pozycje wysyłki do tego klienta do zwrotu."@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "Sesja zablokowana"msgid "Set a customer on this return to add from a shipment."-msgstr "Ustaw klienta dla tego zwrotu, aby dodać z wysyłki."+msgstr "Ustaw klienta na tym zwrocie, aby dodać z wysyłki."msgid "Set a supplier on this return to add from a receipt."msgstr "Ustaw dostawcę w tym zwrocie, aby dodać z przyjęcia."@@ -17243,6 +17510,9 @@ msgstr "Rozpocznij"msgid "Start {0} Day Free Trial"msgstr "Rozpocznij {0}-dniowy bezpłatny okres próbny"+msgid "Start By"+msgstr "Zacznij Od"+msgid "Start counting"msgstr "Rozpocznij liczenie"@@ -17386,6 +17656,9 @@ msgstr "Kroki zbudowane niezależnie, a następnie zmontowane jako jeden elementmsgid "Still dark out on the floor."msgstr "Jeszcze ciemno na hali."+msgid "Stock Availability"+msgstr "Dostępność zapasu"+msgid "Stock movement corrected"msgstr "Ruch zapasów poprawiony"@@ -17624,6 +17897,15 @@ msgstr "Sugeruj dopasowanie"msgid "Suggest with AI"msgstr "Zasugeruj przy pomocy AI"+msgid "Suggested Jobs"+msgstr "Sugerowane Zlecenia produkcyjne"++msgid "Suggested Orders"+msgstr "Sugerowane Zamówienia"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Sugerowane zamówienia wymagane po horyzoncie planowania tego artykułu. Rozszerz horyzont, aby je uwzględnić."+msgid "Suggested orders you haven't placed yet."msgstr "Sugerowane zamówienia, które jeszcze nie złożyłeś."@@ -17874,8 +18156,8 @@ msgstr "Synchronizuj"msgid "Sync Activity"msgstr "Działalność synchronizacji"-msgid "sync off"-msgstr "synchronizacja wyłączona"+msgid "Sync Off"+msgstr "Synchronizacja wyłączona"msgid "Sync operation"msgstr "Operacja synchronizacji"@@ -18642,6 +18924,9 @@ msgstr "Procent rabatu gotówkowego. Użyj 0, aby nie udzielać rabatu."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "Zestaw uprawnień, które automatycznie otrzymują nowi pracownicy tego typu; edycja tutaj zmienia szablon tylko dla przyszłych wynajęć - pracownicy istniejący zachowują to, co mają, chyba że zostaną jawnie zaktualizowani zbiorczo."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "Osoba, do której przypisana jest akcja planowania: właściciel artykułu w tej lokalizacji, ewentualnie właściciel grupy artykułów, ewentualnie właściciel lokalizacji, ewentualnie domyślna osoba firmy."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Fabryki, magazyny i obiekty, w których znajduje się Twoja praca i zapasy"@@ -18663,6 +18948,9 @@ msgstr "Procesy, które może wykonać to stanowisko robocze; pojawia się w selmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "Dostawca nie oferuje celów wymiarów. Najpierw włącz funkcję u dostawcy (np. kategorie śledzenia, śledzenie klasy lub pola)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Punkty graniczne ilości, przy których ta pozycja jest wyceniona; każda kolumna nosi własną cenę za sztukę do negocjacji kupiec–dostawca i do konwersji na dokumenty następujące."@@ -18991,6 +19279,9 @@ msgstr "Te dowody księgowe są wciąż w wersji roboczej, dlatego ich wpisy Winmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Te operacje korzystają z procesu z wieloma dostawcami. Wybierz dostawcę dla każdej."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Nie można było załadować tych zamówień. Zamknij i otwórz ponownie, aby spróbować ponownie."+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łę."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Tolerancja (+/-)"+msgid "Tolerance (days)"+msgstr "Tolerancja (dni)"+msgid "Tomorrow"msgstr "Jutro"@@ -19847,8 +20141,8 @@ msgstr "Cofnij"msgid "Ungroup"msgstr "Rozdziel"-msgid "unhealthy"-msgstr "w złym stanie"+msgid "Unhealthy"+msgstr "W złym stanie"msgid "Uninstall"msgstr "Odinstaluj"@@ -20936,6 +21230,9 @@ msgstr "Gdy zmieni się {name}"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Gdy okres przydatności gotowego produktu jest ustawiony na Obliczony, wybierz, które zużyte materiały wejściowe zasilają obliczenie."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Gdy zamówienie sprzedaży lub zlecenie produkcyjne pojawi się w tygodniu bez pozostałej prognozy, zużywa prognozę z pobliskich tygodni zamiast być dodane do niej. Ustaw oba parametry na 0, aby wyegzekwować tylko w tym samym tygodniu."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Kiedy serial lub partia wygasa i co się dzieje, jeśli jest używany potem — polityka firmy może Ostrzec, Zablokować lub ZablokujZPrzesłonięciem."@@ -21128,6 +21425,9 @@ msgstr "Kto otrzymuje szkolenie na temat czego, w jakim formacie. Twoja rola: zamsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Kto musi zatwierdzić oferty, zamówienia i zakupy — i kiedy"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Kto jest właścicielem działań planowania MRP. Lokalizacje dziedziczą domyślne ustawienia firmy; grupy artykułów dziedziczą swoją lokalizację. Przypisanie najbardziej specyficzne wygrywa, a każdy artykuł może nadpisać to na karcie Planowanie."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Kto powinien otrzymywać powiadomienia dla zleceń utrzymania ruchu?"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 5880f4504b..18f6b10dde 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# linha vincula dados fora desta empresa, portanto umamsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# linha vincula dados fora desta empresa, portanto não pode ser feita backup dela. Ignorá-la faz backup de tudo mais.} other {# linhas vinculam dados fora desta empresa, portanto não podem ser feitas backup delas. Ignorá-las fazem backup de tudo mais.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# semana} other {# semanas}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {O planejador trata este componente como um corpo rígido — uma etapa nas instruções. Execute o planejamento novamente para aplicar.} other {O planejador trata estes # componentes como um corpo rígido — uma etapa nas instruções. Execute o planejamento novamente para aplicar.}}"@@ -107,6 +111,10 @@ msgstr "{0} não pode ser excluído porque ainda está em uso por {where}. Altermsgid "{0} cells with deltas"msgstr "{0} células com deltas"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} consumido"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} valores"msgid "{0} values missing"msgstr "{0} valores ausentes"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} será salvo como {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# conta com saldo} other {# contas com saldo}}"msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# curso} other {# cursos}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# mais após {fenceLabel}} other {# mais após {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Dissolver # lote de produção} other {Dissolver # lotes de produção}}"@@ -340,6 +356,9 @@ msgstr "{days}d"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "${delegatedTo} publica isto no seu razão, portanto o Carbon não o envia. Sua escolha salva é mantida caso isso mude."+msgid "{dismissed} dismissed"+msgstr "{dismissed} dispensados"+msgid "{done} of {total} phases complete"msgstr "{done} de {total} fases concluídas"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} mais: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} inseridos, {updated} atualizados, {0} precisam de correção, {1} ignorados."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# dia} other {# dias}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# linha} other {# linhas}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# fase restante} other {# fases restantes}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} recursos · {reservationCount} reservas · {jobCount} ordens de produção"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} permissões"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Mapeie primeiro a # conta obrigatómsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} não podem ser programadas"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} ordens de produção atualizadas"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} enviado — campos preenchidos a partir do documento."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 operações"+msgid "0 suggests a move for any date difference."+msgstr "0 sugere uma movimentação para qualquer diferença de data."+msgid "0-4 weeks"msgstr "0-4 semanas"@@ -518,9 +543,6 @@ msgstr "1 lançamento de diário em rascunho"msgid "1 job created"msgstr "1 trabalho criado"-msgid "1 job updated"-msgstr "1 trabalho atualizado"-msgid "1 part skipped — it already has an open job"msgstr "1 peça ignorada — ela já tem um trabalho aberto"@@ -530,6 +552,9 @@ msgstr "1 peça ignorada — nada para fabricar"msgid "1 problem — not published"msgstr "1 problema — não publicado"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Compra = {conversionFactor} Inventário"+msgid "1 suggested batch"msgstr "1 lote sugerido"@@ -542,6 +567,9 @@ msgstr "12 períodos mensais"msgid "13+ weeks"msgstr "13+ semanas"+msgid "1st Negative On Hand"+msgstr "1º Estoque Negativo"+msgid "1Y"msgstr "1 ano"@@ -1082,6 +1110,9 @@ msgstr "Uma etapa precisa de um nome."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Uma reserva armazenada de um centro de trabalho ou operador para o intervalo de tempo alocado de uma operação — a saída materializada de uma execução de programação e o que a Previsão mostra."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Uma sugestão que MRP escreve após cada execução: Ordenar ou Fabricar novo suprimento, ou Agilizar, Adiar, Aumentar, Diminuir ou Cancelar uma linha de pedido de compra aberta ou ordem de produção. Aplique-a na página de Planejamento, dispense-a ou atribua-a."+msgid "A supplier contact and location are optional"msgstr "Um contato do fornecedor e um local são opcionais"@@ -2006,6 +2037,12 @@ msgstr "Uma operação deste trabalho é executada neste lote"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "A posição de uma operação na fila de seu centro de trabalho — a ordem em que o chão pega o trabalho. O mecanismo a numera de acordo com a ordem de colocação (início projetado mais cedo primeiro); reorganizar cartões no painel de Centros de Trabalho sobrescreve sem alterar as datas."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Um erro inesperado ocorreu ao conectar ao Onshape. Salve as configurações de integração para tentar novamente."@@ -2167,6 +2204,9 @@ msgstr "Aplicar regras de precificação"msgid "Apply Rules On Top"msgstr "Aplicar regras na parte superior"+msgid "Apply Suggested Changes"+msgstr "Aplicar Alterações Sugeridas"+msgid "Apply suggestions"msgstr "Aplicar sugestões"@@ -2824,6 +2864,9 @@ msgstr "Atribuir a"msgid "Assign to Groups"msgstr "Atribuir a Grupos"+msgid "Assign to Me"+msgstr "Atribuir para Mim"+msgid "Assigned"msgstr "Atribuído"@@ -2836,6 +2879,9 @@ msgstr "Atribuído a Mim"msgid "Assignee"msgstr "Designado"+msgid "Assignees"+msgstr "Designados"+msgid "Assignment"msgstr "Atribuição"@@ -3491,12 +3537,18 @@ msgstr "Cancelar Aviso de Alteração"msgid "Cancel Job"msgstr "Cancelar Trabalho"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Cancelar pedido"msgid "Cancel Purchase Order"msgstr "Cancelar Pedido de compra"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Cancelar Devolução"@@ -3548,6 +3600,12 @@ msgstr "Não é possível mover para o bucket de peças sem ID do item"msgid "Cannot place order - no supplier associated with this item"msgstr "Não é possível fazer o pedido - nenhum fornecedor associado a este item"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Não é possível fazer o pedido — {count} itens não têm fornecedor"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Não é possível fazer o pedido — 1 item não tem fornecedor"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Não é possível contabilizar — a remessa contém entidades rastreadas vencidas."@@ -3753,6 +3811,9 @@ msgstr "Alterar Tipo"msgid "Changed By"msgstr "Alterado por"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Alterado apenas para esta visualização. O horizonte de planejamento do item não é atualizado."+msgid "Changelog"msgstr "Histórico de Mudanças"@@ -3853,6 +3914,9 @@ msgstr "Escolha como adicionar linhas a esta devolução."msgid "Choose what appears on the printed job traveler."msgstr "Escolha o que aparece na ficha de acompanhamento impressa."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Escolha quando o MRP recalcula automaticamente. Você ainda pode executá-lo manualmente a qualquer momento com Recalcular nas páginas de Planejamento."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Escolha se o explorador da lista de materiais em itens, orçamentos e ordens de produção rotula cada linha com sua descrição ou sua ID do item."@@ -4068,6 +4132,9 @@ msgstr "Empresas"msgid "Company"msgstr "Empresa"+msgid "Company default"+msgstr "Padrão da empresa"+msgid "Company group"msgstr "Grupo de empresas"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Não foi possível ler o documento: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Não foi possível liberar {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "Departamento criado"msgid "Created failure mode"msgstr "Modo de falha criado"+msgid "Created from planning"+msgstr "Criado a partir do planejamento"+msgid "Created gauge type"msgstr "Tipo de instrumento criado"@@ -5671,6 +5743,15 @@ msgstr "Casas Decimais"msgid "Declining balance"msgstr "Saldo Decrescente"+msgid "Decrease"+msgstr "Diminuir"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Bem na madrugada, {name}."@@ -5737,6 +5818,9 @@ msgstr "Conta de despesa contábil padrão para manutenção de equipamento e inmsgid "Default GL expense account for periodic depreciation runs."msgstr "Conta de despesa contábil padrão para processamentos periódicos de depreciação."+msgid "Default horizon (days)"+msgstr "Horizonte padrão (dias)"+msgid "Default Method"msgstr "Método Padrão"@@ -5788,6 +5872,15 @@ msgstr "Vida útil padrão que é pré-preenchida em novos ativos nesta classe."msgid "Defaults"msgstr "Padrões"+msgid "Defer"+msgstr "Adiar"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Despesa de Imposto Diferido"@@ -6368,6 +6461,9 @@ msgstr "Descoberta"msgid "Dismiss"msgstr "Descartar"+msgid "Dismissed"+msgstr "Dispensado"+msgid "Dispatch"msgstr "Ordem de manutenção"@@ -6744,6 +6840,9 @@ msgstr "As operações terceirizadas de cada fornecedor de todas as ordens de prmsgid "Each, lb, ft…"msgstr "Cada, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "O estoque das semanas anteriores é usado em primeiro lugar."+msgid "Earliest operation start"msgstr "Início mais cedo da operação"@@ -7503,6 +7602,9 @@ msgstr "Tipo de Evento"msgid "Events"msgstr "Eventos"+msgid "Every 3 hours"+msgstr "A cada 3 horas"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Todos os registros da empresa. Credenciais, tokens de integração e webhooks nunca são incluídos."@@ -7635,6 +7737,15 @@ msgstr "Recebimento Esperado"msgid "Expected Receipt Date"msgstr "Data de Recebimento Esperada"+msgid "Expedite"+msgstr "Antecipar"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Conta de despesa para saldos de clientes cancelados como incobrável na liquidação de contas a receber"@@ -8112,12 +8223,18 @@ msgstr "Falha ao atualizar contagem"msgid "Failed to update item cost"msgstr "Falha ao atualizar custo do item"+msgid "Failed to update job"+msgstr "Falha ao atualizar ordem de produção"+msgid "Failed to update lead times"msgstr "Falha ao atualizar Lead times"msgid "Failed to update opportunity with purchase order"msgstr "Falha ao atualizar oportunidade com pedido de compra"+msgid "Failed to update purchase order line"+msgstr "Falha ao atualizar linha do pedido de compra"+msgid "Failed to update quote line"msgstr "Falha ao atualizar linha do orçamento"@@ -8315,6 +8432,9 @@ msgstr "Primeiro Nome"msgid "First Operation"msgstr "Primeira Operação"+msgid "First week the projected stock goes below zero"+msgstr "Primeira semana em que o estoque projetado fica negativo"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Ativo Fixo"@@ -8381,6 +8501,12 @@ msgstr "para qualquer coisa. Eles vão trazer a pessoa certa."msgid "Forecast"msgstr "Previsão"+msgid "Forecast consumption"+msgstr "Consumo de previsão"++msgid "Forecast Consumption"+msgstr "Consumo de previsão"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Método de previsão: <0>{0}</0>. Esta linha não foi derivada de ordens de produção ativas, portanto nenhuma fonte pai está disponível."@@ -8829,8 +8955,8 @@ msgstr "Tem operações que não podem ser programadas"msgid "Headers"msgstr "Cabeçalhos"-msgid "healthy"-msgstr "íntegro"+msgid "Healthy"+msgstr "Íntegro"msgid "Help"msgstr "Ajuda"@@ -8979,6 +9105,9 @@ msgstr "Quantos dias após a data de cálculo o desconto por pagamento antecipadmsgid "How many days after the calculation date the full amount is due."msgstr "Quantos dias após a data de cálculo o valor total é devido."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Quantos dias um pedido aberto pode chegar a partir da data em que é necessário antes que MRP sugira movê-lo. Defina em Configurações → Planejamento; o padrão é 7 dias."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Quantos dias a partir da data da fatura este cliente tem para pagar; determina a data de vencimento padrão nas faturas de clientes."@@ -9253,6 +9382,9 @@ msgstr "Nesta etapa"msgid "In use"msgstr "Em uso"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "No fuso horário da sua Empresa ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "Nas configurações da Empresa em Desenvolvedor, edite as permissões do aplicativo OAuth privado para incluir «O aplicativo pode escrever em seus documentos», então salve as configurações de integração novamente."@@ -9265,9 +9397,6 @@ msgstr "As notificações no aplicativo são sempre entregues. Escolha quais tómsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "As notificações no aplicativo são sempre entregues. Escolha quais tópicos também chegarão a você por email."-msgid "inactive"-msgstr "inativo"-msgid "Inactive"msgstr "Inativo"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Local de Incoterm"+msgid "Increase"+msgstr "Aumentar"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Indireto"@@ -9364,6 +9502,9 @@ msgstr "Herdado do grupo: se esta conta se encerra em lucros acumulados (receitamsgid "Inherited from the parent group."msgstr "Herdado do grupo pai."+msgid "inherits {inheritedName}"+msgstr "herda {inheritedName}"+msgid "Input"msgstr "Entrada"@@ -9893,6 +10034,9 @@ msgstr "Prioridade da ordem"msgid "Job readable"msgstr "Ordem legível"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Ficha de acompanhamento"@@ -10108,9 +10252,15 @@ msgstr "Última utilização"msgid "Late in the evening, {name}."msgstr "Tarde da noite, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "O estoque das semanas posteriores é usado assim que o das semanas anteriores for usado."+msgid "Latest operation end"msgstr "Término da operação mais recente"+msgid "Latest Order Date"+msgstr "Data Mais Recente do Pedido"+msgid "Latitude"msgstr "Latitude"@@ -10153,6 +10303,9 @@ msgstr "Deixe em branco para usar a próxima revisão automaticamente"msgid "Leave empty for exact match"msgstr "Deixe vazio para correspondência exata"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Deixe vazio ou digite 0 para mostrar tudo que o MRP planeja."+msgid "Leave this page"msgstr "Sair desta página"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Linhas"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "As linhas aparecem aqui após um recebimento de pedido de compra ter sido contabilizado, e apenas para quantidades não já autorizadas em outra devolução de fornecedor. Use Adicionar Item de Linha para uma devolução às cegas."+msgstr "As linhas aparecem aqui quando um recebimento de pedido de compra é contabilizado, e apenas para quantidades ainda não autorizadas em outra devolução de fornecedor. Use Adicionar item de linha para uma devolução cega."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "As linhas aparecem aqui uma vez que uma remessa de pedido de venda tenha sido contabilizada, e apenas para quantidades não já autorizadas em outro RMA. Use Adicionar Item de Linha para uma devolução cega."@@ -10441,6 +10594,12 @@ msgstr "Descrição Longa"msgid "Longitude"msgstr "Longitude"+msgid "Look ahead (weeks)"+msgstr "Próximas Semanas"++msgid "Look back (weeks)"+msgstr "Semanas Anteriores"+msgid "Looks empty here"msgstr "Parece vazio aqui"@@ -10570,6 +10729,12 @@ msgstr "Tipo de Manutenção"msgid "Make"msgstr "Fabricar"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "Fabricar {quantity}"+msgid "Make Active"msgstr "Tornar Ativo"@@ -10847,6 +11012,9 @@ msgstr "Item de Material"msgid "Material Planning"msgstr "Planejamento de Materiais"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "O planejamento de material mostra apenas as ações e pedidos sugeridos com prazo dentro deste número de dias a partir de hoje, para que as necessidades distantes não atrapalhem até que importem. O horizonte de planejamento próprio do item substitui este padrão."+msgid "Material Properties"msgstr "Propriedades do Material"@@ -11231,6 +11399,18 @@ msgstr "MRP (planejamento)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP é executado automaticamente a cada 3 horas, mas você pode executá-lo manualmente aqui."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP é executado automaticamente todos os dias às {time} ({timeZone}), mas você pode executá-lo manualmente aqui."++msgid "MRP Schedule"+msgstr "Programação MRP"++msgid "MRP Suggestions"+msgstr "Sugestões MRP"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP sugere mover um pedido existente apenas quando sua data está fora de prazo por mais de vários dias. Diferenças menores são ignoradas para manter a lista de trabalho tranquila."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Múltiplas ordens de produção podem ser executadas neste processo ao mesmo tempo — por exemplo, uma mesa a laser, forno ou banho de galvanização"@@ -11498,9 +11678,6 @@ msgstr "Nova condição de pagamento"msgid "New Picking List"msgstr "Nova lista de separação"-msgid "New PO"-msgstr "Novo PO"-msgid "New Price Override"msgstr "Nova sobrescrita de preço"@@ -12143,7 +12320,7 @@ msgid "No returnable lines for this customer"msgstr "Nenhuma linha retornável para este cliente"msgid "No returnable lines for this supplier"-msgstr "Nenhuma linha devolvível para este fornecedor"+msgstr "Nenhuma linha retornável para este fornecedor"msgid "No returnable lines match your search"msgstr "Nenhuma linha devolvível corresponde à sua pesquisa"@@ -12205,6 +12382,9 @@ msgstr "Sem unidade de armazenamento"msgid "No storage units or tracking numbers match."msgstr "Nenhuma unidade de armazenamento ou número de rastreamento corresponde."+msgid "No Supplier"+msgstr "Sem fornecedor"+msgid "No suppliers yet"msgstr "Nenhum fornecedor ainda"@@ -12555,6 +12735,9 @@ msgstr "Entrega no prazo"msgid "Onboard your agent to Carbon"msgstr "Integre seu agente ao Carbon"+msgid "Once a day"+msgstr "Uma vez por dia"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Demanda aberta de ordem de produção mais transferências pendentes desmsgid "Open jobs"msgstr "Ordens de produção abertas"+msgid "Open Jobs"+msgstr "Ordens de Produção Abertas"+msgid "Open menu"msgstr "Abrir menu"msgid "Open navigation"msgstr "Abrir navegação"+msgid "Open Orders"+msgstr "Pedidos Abertos"+msgid "Open payables by supplier and age"msgstr "Contas a pagar em aberto por fornecedor e idade"@@ -12932,9 +13121,18 @@ msgstr "Solicitar {0} × {substitute} para esta ordem de produção"msgid "Order {0} for this job"msgstr "Pedir {0} para este trabalho"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "Pedir {quantity}"+msgid "Order by"msgstr "Encomendar até"+msgid "Order By"+msgstr "Ordenar Por"+msgid "Order date"msgstr "Data do pedido"@@ -13091,6 +13289,9 @@ msgstr "Responsável"msgid "Owner (cost center)"msgstr "Responsável (centro de custo)"+msgid "Ownership"+msgstr "Propriedade"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Responsável por: {0}"@@ -13569,9 +13770,36 @@ msgstr "Tempo planejado"msgid "Planning"msgstr "Planejamento"+msgid "Planning action"+msgstr "Ação de planejamento"++msgid "Planning horizon"+msgstr "Horizonte de planejamento"++msgid "Planning Horizon"+msgstr "Horizonte de Planejamento"++msgid "Planning Horizon (Days)"+msgstr "Horizonte de Planejamento (Dias)"++msgid "Planning Horizon:"+msgstr "Horizonte de Planejamento:"++msgid "Planning Ownership"+msgstr "Propriedade de planejamento"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Os ciclos de planejamento sugeriram reabastecimento até um múltiplo inteiro deste número."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "O planejamento mostra apenas as ações e pedidos sugeridos com prazo dentro deste número de dias. Deixe vazio para usar o padrão da empresa ou digite 0 para mostrar tudo para este item."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Limite inferior de planejamento em uma quantidade de reabastecimento sugerida; distinto do MOQ de um fornecedor, que vive no registro de parte do fornecedor."@@ -13980,6 +14208,9 @@ msgstr "Plano do Projeto"msgid "Project start"msgstr "Início do projeto"+msgid "Projected"+msgstr "Projetado"+msgid "Projected completion"msgstr "Conclusão projetada"@@ -14001,6 +14232,12 @@ msgstr "Falta de estoque projetada na semana de {0}"msgid "Projected stock"msgstr "Stock projetado"+msgid "Projected stock by week"+msgstr "Estoque projetado por semana"++msgid "Projected stock is already below zero this week"+msgstr "O estoque projetado já está negativo esta semana"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Ruptura de estoque projetada na semana de {0}"@@ -14139,6 +14376,9 @@ msgstr "Pedido de compra"msgid "Purchase Order Amount"msgstr "Valor do Pedido de Compra"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Regra de aprovação de pedido de compra"@@ -14166,6 +14406,9 @@ msgstr "Pedidos de Compra"msgid "Purchase Orders and Planning"msgstr "Pedidos de compra e planejamento"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Pedidos de compra necessários"@@ -14272,9 +14515,6 @@ msgstr "Qtd"msgid "Qty On Hand"msgstr "Qtd. em Mãos"-msgid "Qty to Order"-msgstr "Qtd a Encomendar"-msgid "Qty. Complete"msgstr "Qtd. Concluída"@@ -14568,6 +14808,9 @@ msgstr "Pronto para orçamento"msgid "ready to keep or revert"msgstr "pronto para manter ou reverter"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Pedidos reais usam a previsão de demanda para sua própria semana primeiro, depois para semanas anteriores e posteriores dentro da janela da empresa, para que a previsão e a demanda real nunca sejam planejadas para as mesmas unidades."+msgid "Real-time inventory and shop-floor visibility"msgstr "Visibilidade em tempo real do inventário e do chão de fábrica"@@ -14880,9 +15123,15 @@ msgstr "Liberar Controle"msgid "Release Job"msgstr "Liberar Trabalho"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Liberar Ordens de produção"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Liberado"@@ -15034,6 +15283,9 @@ msgstr "Renderizando visualização de etiqueta..."msgid "Reopen"msgstr "Reabrir"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Reordenar"@@ -15221,6 +15473,12 @@ msgstr "Requer Reparo"msgid "Requires staffing"msgstr "Exige pessoal"+msgid "Reschedule tolerance"+msgstr "Tolerância de reagendamento"++msgid "Reschedule Tolerance"+msgstr "Tolerância de reagendamento"+msgid "Reserve floor"msgstr "Piso de reserva"@@ -15279,6 +15537,12 @@ msgstr "recursos"msgid "Resources"msgstr "Recursos"+msgid "Responsible employee"+msgstr "Funcionário responsável"++msgid "Responsible Employee"+msgstr "Funcionário responsável"+msgid "Restock"msgstr "Reabastecimento"@@ -15654,6 +15918,9 @@ msgstr "ID de Execução"msgid "Run month-end close and standard reconciliations"msgstr "Executar encerramento de mês e reconciliações padrão"+msgid "Run MRP"+msgstr "Executar MRP"+msgid "Run payment batches and track aging"msgstr "Executar lotes de pagamento e rastrear vencimento"@@ -17243,6 +17510,9 @@ msgstr "Iniciar"msgid "Start {0} Day Free Trial"msgstr "Iniciar Teste Gratuito de {0} Dias"+msgid "Start By"+msgstr "Iniciar Por"+msgid "Start counting"msgstr "Iniciar contagem"@@ -17386,6 +17656,9 @@ msgstr "Etapas construídas por conta própria, depois encaixadas em uma únicamsgid "Still dark out on the floor."msgstr "Ainda está escuro no chão."+msgid "Stock Availability"+msgstr "Disponibilidade de Estoque"+msgid "Stock movement corrected"msgstr "Movimento de estoque corrigido"@@ -17624,6 +17897,15 @@ msgstr "Sugerir Correspondência"msgid "Suggest with AI"msgstr "Sugerir com IA"+msgid "Suggested Jobs"+msgstr "Ordens de Produção Sugeridas"++msgid "Suggested Orders"+msgstr "Pedidos Sugeridos"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Pedidos sugeridos necessários após o horizonte de planejamento deste item. Estenda o horizonte para incluí-los."+msgid "Suggested orders you haven't placed yet."msgstr "Pedidos sugeridos que você ainda não realizou."@@ -17874,8 +18156,8 @@ msgstr "Sincronizar"msgid "Sync Activity"msgstr "Atividade de sincronização"-msgid "sync off"-msgstr "sincronização desativada"+msgid "Sync Off"+msgstr "Sincronização desativada"msgid "Sync operation"msgstr "Operação de sincronização"@@ -18642,6 +18924,9 @@ msgstr "O percentual do desconto à vista. Use 0 para nenhum desconto."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "O conjunto de permissões que novos funcionários deste tipo recebem automaticamente; editar aqui muda apenas o modelo para futuras contratações - os funcionários existentes mantêm o que têm a menos que sejam explicitamente atualizados em massa."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "A pessoa a quem uma ação de planejamento está atribuída: o responsável do item naquele local, senão o do grupo do item, senão o do local, senão o padrão da empresa."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "As plantas, armazéns e locais onde seu trabalho e estoque residem"@@ -18663,6 +18948,9 @@ msgstr "Os processos que este centro de trabalho pode executar; aparecem em selemsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "O provedor não oferece alvos de dimensão. Habilite o recurso no provedor primeiro (por exemplo, categorias de rastreamento, rastreamento de classe ou campos)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Os pontos de ruptura de quantidade em que essa linha é precificada; cada coluna possui seu próprio preço por unidade para negociação comprador-fornecedor e conversão para documentos posteriores."@@ -18991,6 +19279,9 @@ msgstr "Estes lançamentos de diário ainda estão em Rascunho, portanto seus dmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Essas operações usam um processo com múltiplos fornecedores. Selecione um fornecedor para cada uma."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Estes pedidos não puderam ser carregados. Feche e reabra para tentar novamente."+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."@@ -19469,6 +19760,9 @@ msgstr "Tol+"msgid "Tolerance (+/-)"msgstr "Tolerância (+/-)"+msgid "Tolerance (days)"+msgstr "Tolerância (dias)"+msgid "Tomorrow"msgstr "Amanhã"@@ -19847,8 +20141,8 @@ msgstr "Desfazer"msgid "Ungroup"msgstr "Desagrupar"-msgid "unhealthy"-msgstr "malsaudável"+msgid "Unhealthy"+msgstr "Malsaudável"msgid "Uninstall"msgstr "Desinstalar"@@ -20936,6 +21230,9 @@ msgstr "Quando {name} muda"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Quando a vida de prateleira de um produto acabado é definida como Calculada, escolha quais entradas consumidas alimentam o cálculo."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Quando um Pedido de Venda ou Ordem de Produção chega a uma semana sem previsão remanescente, ela utiliza a previsão de semanas próximas em vez de ser contabilizada adicionalmente. Defina ambas como 0 para compensar apenas na mesma semana."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Quando um número de série ou lote expira e o que acontece se usado depois — uma política da empresa pode Avisar, Bloquear ou BloquearComSubstituição."@@ -21128,6 +21425,9 @@ msgstr "Quem recebe treinamento sobre o quê, em qual formato. Sua parte: protejmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Quem tem que aprovar cotações, pedidos e compras — e quando"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Quem é o proprietário das ações de Planejamento de MRP. Locais herdam o padrão da Empresa; grupos de Item herdam seu Local. A atribuição mais específica prevalece, e cada Item pode sobrescrever na sua aba de Planejamento."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Quem deve receber notificações para ordens de manutenção?"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex fa4e189931..b912ce4a66 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# строка связана с данными внеmsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# строка связана с данными вне этой организации, поэтому она не может быть зарезервирована. Пропуск позволит зарезервировать все остальное.} other {# строк связаны с данными вне этой организации, поэтому они не могут быть зарезервированы. Пропуск позволит зарезервировать все остальное.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# неделя} few {# недели} many {# недель} other {# недели}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {Планировщик рассматривает этот компонент как одно жесткое тело — один шаг в инструкциях. Повторно запустите план, чтобы применить.} other {Планировщик рассматривает эти # компонентов как одно жесткое тело — один шаг в инструкциях. Повторно запустите план, чтобы применить.}}"@@ -107,6 +111,10 @@ msgstr "{0} нельзя удалить, так как она всё ещё исmsgid "{0} cells with deltas"msgstr "{0} ячеек с разницами"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} израсходовано"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} значений"msgid "{0} values missing"msgstr "{0} значений отсутствует"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} будет сохранено как {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# счет с остатком} other {# счетоmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# курс} other {# курсов}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# еще после {fenceLabel}} few {# еще после {fenceLabel}} many {# еще после {fenceLabel}} other {# еще после {fenceLabel}}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Расформировать # серию} few {Расформировать # серии} many {Расформировать # серий} other {Расформировать # серий}}"@@ -340,6 +356,9 @@ msgstr "{days}д"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "${delegatedTo} отправляет это в вашу бухгалтерскую книгу, поэтому Carbon не отправляет это. Ваш сохраненный выбор сохраняется на случай, если это изменится."+msgid "{dismissed} dismissed"+msgstr "{dismissed} отклонено"+msgid "{done} of {total} phases complete"msgstr "{done} из {total} этапов завершено"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} еще: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} вставлено, {updated} обновлено, {0} требуют исправления, {1} пропущено."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# день} few {# дня} many {# дней} other {# дня}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# строка} other {# строк}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# этап остался} other {# этапоmsgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} ресурсов · {reservationCount} резервирований · {jobCount} производственных заказов"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} прав доступа"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Сначала сопоставьтmsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} не может быть спланировано"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} производственных заказов обновлено"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "Файл {uploadedFileName} загружен — поля заполнены из документа."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 операций"+msgid "0 suggests a move for any date difference."+msgstr "0 предлагает перемещение для любой разницы в датах."+msgid "0-4 weeks"msgstr "0-4 недели"@@ -518,9 +543,6 @@ msgstr "1 черновая проводка"msgid "1 job created"msgstr "1 задание создано"-msgid "1 job updated"-msgstr "1 задание обновлено"-msgid "1 part skipped — it already has an open job"msgstr "1 деталь пропущена — у неё уже есть открытое задание"@@ -530,6 +552,9 @@ msgstr "1 деталь пропущена — нечего делать"msgid "1 problem — not published"msgstr "1 проблема — не опубликовано"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Покупка = {conversionFactor} Запасы"+msgid "1 suggested batch"msgstr "1 предложенная серия"@@ -542,6 +567,9 @@ msgstr "12 ежемесячных периодов"msgid "13+ weeks"msgstr "13+ недель"+msgid "1st Negative On Hand"+msgstr "Первое отрицательное значение запаса"+msgid "1Y"msgstr "1 год"@@ -1082,6 +1110,9 @@ msgstr "Шаг должен иметь имя."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Сохраненное бронирование рабочего центра или оператора на время размещения одной операции — материализованный результат запуска планирования и то, что отображает Прогноз."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "Предложение, которое MRP создает после каждого запуска: заказать или начать производство нового обеспечения, или ускорить, отсрочить, увеличить, уменьшить или отменить строку открытого заказа поставщику или производственный заказ. Примените его со страницы планирования, отклоните его или назначьте его."+msgid "A supplier contact and location are optional"msgstr "Контактное лицо и площадка поставщика опциональны"@@ -2006,6 +2037,12 @@ msgstr "Операция этого задания входит в эту парmsgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "Позиция операции в очереди ее рабочего центра — порядок, в котором цех берет работу. Двигатель нумерует ее по порядку размещения (самое раннее предполагаемое начало в первую очередь); переупорядочение карт на доске Рабочих центров переопределяет его без изменения дат."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Во время подключения к Onshape произошла неожиданная ошибка. Сохраните настройки интеграции и попробуйте еще раз."@@ -2167,6 +2204,9 @@ msgstr "Применять правила ценообразования"msgid "Apply Rules On Top"msgstr "Применить правила выше"+msgid "Apply Suggested Changes"+msgstr "Применить предложенные изменения"+msgid "Apply suggestions"msgstr "Применить предложения"@@ -2824,6 +2864,9 @@ msgstr "Назначить"msgid "Assign to Groups"msgstr "Назначить группам"+msgid "Assign to Me"+msgstr "Назначить мне"+msgid "Assigned"msgstr "Назначено"@@ -2836,6 +2879,9 @@ msgstr "Назначено мне"msgid "Assignee"msgstr "Исполнитель"+msgid "Assignees"+msgstr "Исполнители"+msgid "Assignment"msgstr "Назначение"@@ -3491,12 +3537,18 @@ msgstr "Отмена Извещения об изменении"msgid "Cancel Job"msgstr "Отменить задание"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Отменить заказ"msgid "Cancel Purchase Order"msgstr "Отмена Заказа поставщику"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "Отменить возврат"@@ -3548,6 +3600,12 @@ msgstr "Невозможно переместить в корзину деталmsgid "Cannot place order - no supplier associated with this item"msgstr "Невозможно разместить заказ - с этим товаром не связан поставщик"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Невозможно оформить заказ — у {count} позиций нет поставщика"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Невозможно оформить заказ — у 1 позиции нет поставщика"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Невозможно провести — отгрузка содержит сущности, срок действия которых истек."@@ -3753,6 +3811,9 @@ msgstr "Изменить тип"msgid "Changed By"msgstr "Изменено"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Изменено только для этого представления. Горизонт планирования номенклатуры не обновлен."+msgid "Changelog"msgstr "Журнал изменений"@@ -3853,6 +3914,9 @@ msgstr "Выберите, как добавить строки в этот воmsgid "Choose what appears on the printed job traveler."msgstr "Выбрать, что отображается на распечатанном маршрутном листе работы."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "Выберите, когда MRP будет пересчитываться автоматически. Вы в любой момент можете запустить его вручную, нажав кнопку Пересчет на страницах планирования."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Выберите, будут ли подписаны каждая строка спецификации на номенклатуре, коммерческих предложениях и производственных заказах с описанием или кодом номенклатуры."@@ -4068,6 +4132,9 @@ msgstr "Компании"msgid "Company"msgstr "Организация"+msgid "Company default"+msgstr "По умолчанию организации"+msgid "Company group"msgstr "Группа организаций"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Не удалось прочитать документ: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "Не удалось запустить в работу {0}: {1}"@@ -5093,6 +5162,9 @@ msgstr "Отдел создан"msgid "Created failure mode"msgstr "Режим отказа создан"+msgid "Created from planning"+msgstr "Создано из планирования"+msgid "Created gauge type"msgstr "Создан тип средства измерения"@@ -5671,6 +5743,15 @@ msgstr "Десятичные разряды"msgid "Declining balance"msgstr "Уменьшаемый остаток"+msgid "Decrease"+msgstr "Уменьшить"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Глубокая ночь, {name}."@@ -5737,6 +5818,9 @@ msgstr "Счет расходов главной книги по умолчанmsgid "Default GL expense account for periodic depreciation runs."msgstr "Счет расходов главной книги по умолчанию для периодических начислений амортизации."+msgid "Default horizon (days)"+msgstr "Горизонт планирования по умолчанию (дней)"+msgid "Default Method"msgstr "Метод по умолчанию"@@ -5788,6 +5872,15 @@ msgstr "Стандартный срок полезного использоваmsgid "Defaults"msgstr "Значения по умолчанию"+msgid "Defer"+msgstr "Отложить"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Отложенные налоговые расходы"@@ -6368,6 +6461,9 @@ msgstr "Обнаружение"msgid "Dismiss"msgstr "Отклонить"+msgid "Dismissed"+msgstr "Отклонено"+msgid "Dispatch"msgstr "Заявка на техобслуживание"@@ -6744,6 +6840,9 @@ msgstr "Внешние операции каждого поставщика изmsgid "Each, lb, ft…"msgstr "Каждый, фунт, фут…"+msgid "Earlier weeks are consumed first."+msgstr "Запас из ранних недель расходуется в первую очередь."+msgid "Earliest operation start"msgstr "Самое раннее начало операции"@@ -7503,6 +7602,9 @@ msgstr "Тип события"msgid "Events"msgstr "События"+msgid "Every 3 hours"+msgstr "Каждые 3 часа"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Все записи компании. Учётные данные, токены интеграций и вебхуки никогда не включаются."@@ -7635,6 +7737,15 @@ msgstr "Ожидаемое получение"msgid "Expected Receipt Date"msgstr "Ожидаемая дата получения"+msgid "Expedite"+msgstr "Ускорить"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Счет расходов для остатков покупателей, списанных как безнадежные при урегулировании дебиторской задолженности"@@ -8112,12 +8223,18 @@ msgstr "Ошибка обновления подсчета"msgid "Failed to update item cost"msgstr "Не удалось обновить себестоимость номенклатуры"+msgid "Failed to update job"+msgstr "Не удалось обновить производственный заказ"+msgid "Failed to update lead times"msgstr "Не удалось обновить сроки поставки"msgid "Failed to update opportunity with purchase order"msgstr "Не удалось обновить сделку заказом поставщику"+msgid "Failed to update purchase order line"+msgstr "Не удалось обновить строку заказа поставщику"+msgid "Failed to update quote line"msgstr "Не удалось обновить строку предложения"@@ -8315,6 +8432,9 @@ msgstr "Имя"msgid "First Operation"msgstr "Первая операция"+msgid "First week the projected stock goes below zero"+msgstr "Первая неделя, когда прогнозируемый запас упадет ниже нуля"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Основной Актив"@@ -8381,6 +8501,12 @@ msgstr "для чего угодно. Они привлекут нужногоmsgid "Forecast"msgstr "Прогноз"+msgid "Forecast consumption"+msgstr "Потребление прогноза"++msgid "Forecast Consumption"+msgstr "Потребление прогноза"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Метод прогноза: <0>{0}</0>. Эта строка не была получена из активных производственных заказов, поэтому нет доступных источников."@@ -8829,8 +8955,8 @@ msgstr "Имеет операции, которые не могут быть сmsgid "Headers"msgstr "Заголовки"-msgid "healthy"-msgstr "здоровый"+msgid "Healthy"+msgstr "Здоровый"msgid "Help"msgstr "Справка"@@ -8979,6 +9105,9 @@ msgstr "Сколько дней после даты расчета скидкаmsgid "How many days after the calculation date the full amount is due."msgstr "Сколько дней после даты расчета полная сумма становится подлежащей уплате."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Количество дней, на которое открытый заказ может отклониться от требуемой даты до того, как MRP предложит его перенести. Установить в Настройки → Планирование; по умолчанию 7 дней."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Количество дней от даты счета-фактуры, отведенных покупателю на оплату; определяет срок выполнения по умолчанию на счетах-фактурах покупателя."@@ -9253,6 +9382,9 @@ msgstr "На этом шаге"msgid "In use"msgstr "В использовании"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "В часовом поясе вашей организации ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "В настройках Enterprise под разделом Developer отредактируйте разрешения приватного OAuth приложения, чтобы включить «Приложение может записывать в ваши документы», затем сохраните настройки интеграции снова."@@ -9265,9 +9397,6 @@ msgstr "Уведомления в приложении всегда доставmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Уведомления в приложении всегда доставляются. Выберите, какие темы также будут доходить до вас по электронной почте."-msgid "inactive"-msgstr "неактивный"-msgid "Inactive"msgstr "Неактивно"@@ -9325,6 +9454,15 @@ msgstr "Инкотермс"msgid "Incoterm Location"msgstr "Место поставки по Инкотермс"+msgid "Increase"+msgstr "Увеличить"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Косвенный"@@ -9364,6 +9502,9 @@ msgstr "Унаследовано из группы: закрывается лиmsgid "Inherited from the parent group."msgstr "Унаследовано от родительской группы."+msgid "inherits {inheritedName}"+msgstr "от {inheritedName}"+msgid "Input"msgstr "Ввод"@@ -9893,6 +10034,9 @@ msgstr "Приоритет работы"msgid "Job readable"msgstr "Читаемая работа"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "Маршрутный лист работы"@@ -10108,9 +10252,15 @@ msgstr "Последний раз использован"msgid "Late in the evening, {name}."msgstr "Поздно вечером, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Запас из поздних недель расходуется после того, как запас из ранних недель исчерпан."+msgid "Latest operation end"msgstr "Конец последней операции"+msgid "Latest Order Date"+msgstr "Последняя дата заказа"+msgid "Latitude"msgstr "Широта"@@ -10153,6 +10303,9 @@ msgstr "Оставить пусто, чтобы использовать слеmsgid "Leave empty for exact match"msgstr "Оставьте пустым для точного совпадения"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Оставьте пусто или введите 0, чтобы показать все, что планирует MRP."+msgid "Leave this page"msgstr "Покинуть эту страницу"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Строки"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Строки появляются здесь, когда поступление проведено, и только для количеств, не авторизованных на другом возврате поставщику. Используйте добавление строки для слепого возврата."+msgstr "Строки появятся здесь после проведения поступления заказа поставщику и только для количеств, не авторизованных в другом возврате поставщику. Используйте Добавить строку для слепого возврата."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Строки появляются здесь после проведения отгрузки, и только для количеств, не авторизованных на другой RMA. Используйте функцию «Добавить строку» для слепого возврата."@@ -10441,6 +10594,12 @@ msgstr "Подробное описание"msgid "Longitude"msgstr "Долгота"+msgid "Look ahead (weeks)"+msgstr "Смотреть вперед (недели)"++msgid "Look back (weeks)"+msgstr "Смотреть назад (недели)"+msgid "Looks empty here"msgstr "Здесь пусто"@@ -10570,6 +10729,12 @@ msgstr "Тип техобслуживания"msgid "Make"msgstr "Производить"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "Произвести {quantity}"+msgid "Make Active"msgstr "Сделать активным"@@ -10847,6 +11012,9 @@ msgstr "Номенклатура материала"msgid "Material Planning"msgstr "Планирование материалов"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "Планирование материалов показывает только действия и рекомендуемые заказы, выполняемые в течение этого количества дней с сегодня, чтобы удаленные потребности оставались в стороне, пока они не станут важны. Собственный горизонт планирования номенклатуры переопределяет это значение по умолчанию."+msgid "Material Properties"msgstr "Свойства материалов"@@ -11231,6 +11399,18 @@ msgstr "MRP (планирование)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP запускается автоматически каждые 3 часа, но вы можете запустить его вручную здесь."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP запускается автоматически каждый день в {time} ({timeZone}), но вы можете запустить его вручную здесь."++msgid "MRP Schedule"+msgstr "MRP График"++msgid "MRP Suggestions"+msgstr "Предложения MRP"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP предлагает переместить существующий заказ только если его дата отличается более чем на это количество дней. Меньшие разницы остаются без изменений, чтобы список работ оставался управляемым."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Несколько производственных заказов могут выполняться на этом процессе одновременно — например, лазерный станок, печь или ванна для гальваники"@@ -11498,9 +11678,6 @@ msgstr "Новые условия оплаты"msgid "New Picking List"msgstr "Новый лист отбора"-msgid "New PO"-msgstr "Новый ПО"-msgid "New Price Override"msgstr "Новое переопределение цены"@@ -12205,6 +12382,9 @@ msgstr "Нет единицы хранения"msgid "No storage units or tracking numbers match."msgstr "Единицы хранения или номера отслеживания не совпадают."+msgid "No Supplier"+msgstr "Нет поставщика"+msgid "No suppliers yet"msgstr "Поставщиков еще нет"@@ -12555,6 +12735,9 @@ msgstr "Своевременная доставка"msgid "Onboard your agent to Carbon"msgstr "Подключите вашего агента к Carbon"+msgid "Once a day"+msgstr "Один раз в день"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Открытая потребность производственногmsgid "Open jobs"msgstr "Открытые производственные заказы"+msgid "Open Jobs"+msgstr "Открытые производственные заказы"+msgid "Open menu"msgstr "Открыть меню"msgid "Open navigation"msgstr "Открыть навигацию"+msgid "Open Orders"+msgstr "Открытые заказы"+msgid "Open payables by supplier and age"msgstr "Открытая кредиторская задолженность по поставщикам и срокам"@@ -12932,9 +13121,18 @@ msgstr "Заказать {0} × {substitute} для этого производmsgid "Order {0} for this job"msgstr "Заказать {0} для этого задания"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "Заказать {quantity}"+msgid "Order by"msgstr "Заказать до"+msgid "Order By"+msgstr "Сортировать по"+msgid "Order date"msgstr "Дата заказа"@@ -13091,6 +13289,9 @@ msgstr "Ответственный"msgid "Owner (cost center)"msgstr "Ответственный (Центр затрат)"+msgid "Ownership"+msgstr "Владение"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Владеет: {0}"@@ -13569,9 +13770,36 @@ msgstr "Плановое время"msgid "Planning"msgstr "Планирование"+msgid "Planning action"+msgstr "Действие планирования"++msgid "Planning horizon"+msgstr "Горизонт планирования"++msgid "Planning Horizon"+msgstr "Горизонт планирования"++msgid "Planning Horizon (Days)"+msgstr "Горизонт планирования (дней)"++msgid "Planning Horizon:"+msgstr "Горизонт планирования:"++msgid "Planning Ownership"+msgstr "Ответственность планирования"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Циклы планирования предложили пополнение до целого кратного этому числу."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "Планирование показывает только действия и рекомендуемые заказы, выполняемые в течение этого количества дней. Оставьте пусто, чтобы использовать значение по умолчанию организации, или введите 0, чтобы показать все для этой номенклатуры."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Нижняя граница планирования предлагаемого количества пополнения; отличается от минимального количества заказа поставщика, которое находится в карточке поставщик-номенклатура."@@ -13980,6 +14208,9 @@ msgstr "План проекта"msgid "Project start"msgstr "Начало проекта"+msgid "Projected"+msgstr "Спрогнозировано"+msgid "Projected completion"msgstr "Прогнозное завершение"@@ -14001,6 +14232,12 @@ msgstr "Прогнозируемое исчерпание запасов на нmsgid "Projected stock"msgstr "Прогнозируемый запас"+msgid "Projected stock by week"+msgstr "Прогнозируемый запас по неделям"++msgid "Projected stock is already below zero this week"+msgstr "Прогнозируемый запас уже ниже нуля на этой неделе"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "Прогнозируемый дефицит на неделе {0}"@@ -14139,6 +14376,9 @@ msgstr "Заказ поставщику"msgid "Purchase Order Amount"msgstr "Сумма заказа поставщику"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Правило утверждения заказа поставщику"@@ -14166,6 +14406,9 @@ msgstr "Заказы поставщику"msgid "Purchase Orders and Planning"msgstr "Заказы поставщику и Планирование"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Требуются заказы поставщику"@@ -14272,9 +14515,6 @@ msgstr "Кол-во"msgid "Qty On Hand"msgstr "Кол-во в наличии"-msgid "Qty to Order"-msgstr "Кол-во для заказа"-msgid "Qty. Complete"msgstr "Кол-во завершено"@@ -14568,6 +14808,9 @@ msgstr "Готово к предложению"msgid "ready to keep or revert"msgstr "готово к сохранению или восстановлению"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Реальные заказы сначала потребляют прогноз потребности на их собственную неделю, затем на более ранние и более поздние недели в пределах окна компании, поэтому прогноз и фактическая потребность никогда не планируются для одних и тех же единиц одновременно."+msgid "Real-time inventory and shop-floor visibility"msgstr "Видимость запасов и производства в реальном времени"@@ -14880,9 +15123,15 @@ msgstr "Управление запуском в работу"msgid "Release Job"msgstr "Запустить производственный заказ в работу"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "Запустить в работу производственные заказы"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Выпущено"@@ -15034,6 +15283,9 @@ msgstr "Отрисовка предпросмотра этикетки..."msgid "Reopen"msgstr "Открыть заново"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Переупорядочить"@@ -15116,7 +15368,7 @@ msgid "Reports"msgstr "Отчеты"msgid "Reprice with current rules"-msgstr "Переоценить с текущими правилами"+msgstr "Пересчитать с применением текущих правил"#. placeholder {0}: format(repricedPrice)msgid "Repricing with today's rules and costs gives <0>{0}</0>."@@ -15221,6 +15473,12 @@ msgstr "Требует ремонта"msgid "Requires staffing"msgstr "Требует персонала"+msgid "Reschedule tolerance"+msgstr "Допуск переноса"++msgid "Reschedule Tolerance"+msgstr "Допуск переноса"+msgid "Reserve floor"msgstr "Минимальный уровень запаса"@@ -15279,6 +15537,12 @@ msgstr "ресурсы"msgid "Resources"msgstr "Ресурсы"+msgid "Responsible employee"+msgstr "Ответственный сотрудник"++msgid "Responsible Employee"+msgstr "Ответственный сотрудник"+msgid "Restock"msgstr "Пополнение"@@ -15654,6 +15918,9 @@ msgstr "Идентификатор запуска"msgid "Run month-end close and standard reconciliations"msgstr "Выполнить закрытие конца месяца и стандартные сверки"+msgid "Run MRP"+msgstr "Запустить MRP"+msgid "Run payment batches and track aging"msgstr "Запускать пакеты платежей и отслеживать просрочку"@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "Сеанс заблокирован"msgid "Set a customer on this return to add from a shipment."-msgstr "Укажите покупателя в этом возврате для добавления из отгрузки."+msgstr "Укажите покупателя для этого возврата, чтобы добавить из отгрузки."msgid "Set a supplier on this return to add from a receipt."msgstr "Установите поставщика для этого возврата, чтобы добавить из поступления."@@ -17243,6 +17510,9 @@ msgstr "Начать"msgid "Start {0} Day Free Trial"msgstr "Начать {0}-дневный бесплатный пробный период"+msgid "Start By"+msgstr "Начать с"+msgid "Start counting"msgstr "Начать подсчёт"@@ -17386,6 +17656,9 @@ msgstr "Шаги, построенные отдельно, затем собраmsgid "Still dark out on the floor."msgstr "На производстве всё ещё темно."+msgid "Stock Availability"+msgstr "Наличие запаса"+msgid "Stock movement corrected"msgstr "Движение запаса исправлено"@@ -17624,6 +17897,15 @@ msgstr "Предложить совпадение"msgid "Suggest with AI"msgstr "Предложить с помощью ИИ"+msgid "Suggested Jobs"+msgstr "Рекомендуемые производственные заказы"++msgid "Suggested Orders"+msgstr "Рекомендуемые заказы"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Рекомендуемые заказы требуются после горизонта планирования этой номенклатуры. Расширьте горизонт, чтобы включить их."+msgid "Suggested orders you haven't placed yet."msgstr "Предложенные заказы, которые вы еще не разместили."@@ -17874,8 +18156,8 @@ msgstr "Синхронизация"msgid "Sync Activity"msgstr "Активность синхронизации"-msgid "sync off"-msgstr "синхронизация отключена"+msgid "Sync Off"+msgstr "Синхронизация отключена"msgid "Sync operation"msgstr "Операция синхронизации"@@ -18642,6 +18924,9 @@ msgstr "Процент скидки при оплате наличными. Исmsgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "Набор прав доступа, который автоматически получают новые сотрудники этого типа; редактирование здесь изменяет шаблон только для будущих сотрудников — существующие сотрудники сохраняют свои права, пока их явно не обновить массово."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "Лицо, которому назначено действие планирования: ответственный номенклатуры на этой площадке, иначе ответственный группы номенклатуры, иначе ответственный площадки, иначе ответственный организации по умолчанию."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Заводы, склады и объекты, где находятся ваша работа и запасы"@@ -18663,6 +18948,9 @@ msgstr "Процессы, которые может выполнять этотmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "Поставщик не предлагает целевые показатели по измерениям. Сначала включите функцию у поставщика (например, категории отслеживания, отслеживание класса или поля)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Точки разрыва по количеству, при которых рассчитывается цена этой строки; каждый столбец содержит свою цену за единицу для переговоров между закупщиком и поставщиком и для преобразования в последующие документы."@@ -18991,6 +19279,9 @@ msgstr "Эти операции по-прежнему находятся в реmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Эти операции выполняются по процессу с несколькими поставщиками. Выберите поставщика для каждой операции."+msgid "These orders could not be loaded. Close and reopen to try again."+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 "Эти детали заменяются на эту. Каждое правило установлено на старой детали; откройте ее, чтобы изменить правило."@@ -19469,6 +19760,9 @@ msgstr "Допуск+"msgid "Tolerance (+/-)"msgstr "Допуск (+/-)"+msgid "Tolerance (days)"+msgstr "Допуск (дней)"+msgid "Tomorrow"msgstr "Завтра"@@ -19847,8 +20141,8 @@ msgstr "Отменить"msgid "Ungroup"msgstr "Разгруппировать"-msgid "unhealthy"-msgstr "некорректно"+msgid "Unhealthy"+msgstr "Некорректно"msgid "Uninstall"msgstr "Удалить"@@ -20936,6 +21230,9 @@ msgstr "Когда {name} изменяется"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Когда срок хранения готового продукта установлен на Рассчитанный, выберите, какие потребленные входные данные питают расчет."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Когда заказ покупателя или производственный заказ попадает на неделю без оставшегося прогноза, он использует прогноз из соседних недель вместо добавления к существующему. Установите оба на 0, чтобы рассчитать только в пределах той же недели."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Когда истекает срок годности серии или производственной серии и что происходит при использовании после — политика организации может предупредить, заблокировать или заблокировать с переопределением."@@ -21128,6 +21425,9 @@ msgstr "Кто получает обучение, по каким темам иmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Кто должен утвердить коммерческие предложения, заказы и закупки — и когда"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "Кто владеет действиями планирования MRP. Площадки наследуют значение по умолчанию организации; группы номенклатуры наследуют свою площадку. Наиболее специфичное назначение применяется, и каждая номенклатура может переопределить на вкладке «Планирование»."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Кто должен получать уведомления о заявках на техобслуживание?"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex c736cb9e02..149a4e3143 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# satır bu şirketin dışındaki verilere bağlantımsgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# satır bu şirketin dışındaki verilere bağlantı kuruyor, bu nedenle yedeklenemez. Bunu atlayarak diğer her şeyi yedekleyebilirsiniz.} other {# satır bu şirketin dışındaki verilere bağlantı kuruyor, bu nedenle yedeklenemez. Bunları atlayarak diğer her şeyi yedekleyebilirsiniz.}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, one {# hafta} other {# hafta}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {Planlama motoru bu bileşeni tek bir rijit gövde olarak görür — talimatların bir adımı. Uygulamak için planı yeniden çalıştırın.} other {Planlama motoru bu # bileşeni tek bir rijit gövde olarak görür — talimatların bir adımı. Uygulamak için planı yeniden çalıştırın.}}"@@ -107,6 +111,10 @@ msgstr "{0} hâlâ {where} tarafından kullanıldığı için silinemez. Önce bmsgid "{0} cells with deltas"msgstr "{0} deltaları olan hücreler"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} tüketildi"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} değer"msgid "{0} values missing"msgstr "{0} değeri eksik"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0}, {name} olarak kaydedilecek"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# bakiyesi olan hesap} other {# bakiyesi olan hesapmsgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# kurs} other {# kurs}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, one {# daha {fenceLabel} sonra} other {# daha {fenceLabel} sonra}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# partiyi çöz} other {# partileri çöz}}"@@ -340,6 +356,9 @@ msgstr "{days}g"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo} bunu muhasebe defterinize gönderir, bu nedenle Carbon onu göndermez. Kaydedilen seçiminiz değişmesi durumunda korunur."+msgid "{dismissed} dismissed"+msgstr "{dismissed} reddedildi"+msgid "{done} of {total} phases complete"msgstr "{done} / {total} aşama tamamlandı"@@ -360,6 +379,9 @@ msgstr "{hiddenCount} daha: {hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "{inserted} eklendi, {updated} güncellendi, {0} düzeltme gerekli, {1} atlandı."+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, one {# gün} other {# gün}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# satır} other {# satırlar}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# aşama kaldı} other {# aşama kaldı}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} Kaynaklar · {reservationCount} rezervasyonlar · {jobCount} İş emirleri"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} izinleri"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {Önce kalan # gerekli hesabı eşlemsgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount} planlanmıyor"-msgid "{updatedJobCount} jobs updated"-msgstr "{updatedJobCount} İş emirleri güncellendi"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "{uploadedFileName} yüklendi — alanlar belgeden dolduruldu."@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0 operasyon"+msgid "0 suggests a move for any date difference."+msgstr "0, herhangi bir tarih farkı için bir taşıma önerir."+msgid "0-4 weeks"msgstr "0-4 hafta"@@ -518,9 +543,6 @@ msgstr "1 taslak yevmiye kaydı"msgid "1 job created"msgstr "1 iş oluşturuldu"-msgid "1 job updated"-msgstr "1 iş güncellendi"-msgid "1 part skipped — it already has an open job"msgstr "1 parça atlandı — zaten açık bir işi var"@@ -530,6 +552,9 @@ msgstr "1 parça atlandı — yapılacak bir şey yok"msgid "1 problem — not published"msgstr "1 sorun — yayınlanmadı"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 Satın Alma = {conversionFactor} Envanter"+msgid "1 suggested batch"msgstr "1 önerilen parti"@@ -542,6 +567,9 @@ msgstr "12 aylık dönem"msgid "13+ weeks"msgstr "13+ hafta"+msgid "1st Negative On Hand"+msgstr "1. Negatif Eldeki"+msgid "1Y"msgstr "1Y"@@ -1082,6 +1110,9 @@ msgstr "Bir adım bir ada ihtiyaç duyuyor."msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "Bir operasyon'un yerleştirilmiş zaman aralığı için iş merkezi veya operatör'ün saklı bir rezervasyonu — bir planlama çalışmasının gerçekleştirilmiş çıktısı ve Tahmin'in çizdiği şey."+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "MRP'nin her çalışmasından sonra yazdığı bir öneri: Yeni arz sipariş ver veya üret, ya da açık bir satın alma siparişi satırını veya iş emrini hızlandır, ertele, artır, azalt veya iptal et. Planlama sayfasından uygula, kapat veya bir kişiye ata."+msgid "A supplier contact and location are optional"msgstr "Bir tedarikçi ilgili kişisi ve lokasyonu isteğe bağlıdır"@@ -2006,6 +2037,12 @@ msgstr "Bu işin bir operasyonu bu partide çalışıyor"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "Bir operasyon'un iş merkezi'nin kuyruğundaki konumu — atölyenin işleri aldığı sıra. Motor, yerleştirme sırasından numaralandırır (en erken öngörülen başlangıç ilk); İş merkezleri panosundaki kartları yeniden sıralamak, tarihleri değiştirmeden bunu geçersiz kılar."+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "Onshape'e bağlanırken beklenmedik bir hata oluştu. Tekrar denemek için entegrasyon ayarlarını kaydedin."@@ -2167,6 +2204,9 @@ msgstr "Fiyatlandırma kurallarını uygula"msgid "Apply Rules On Top"msgstr "Kuralları üste uygula"+msgid "Apply Suggested Changes"+msgstr "Önerilen Değişiklikleri Uygula"+msgid "Apply suggestions"msgstr "Önerileri Uygula"@@ -2824,6 +2864,9 @@ msgstr "Ata"msgid "Assign to Groups"msgstr "Gruplara Ata"+msgid "Assign to Me"+msgstr "Bana Ata"+msgid "Assigned"msgstr "Atanmış"@@ -2836,6 +2879,9 @@ msgstr "Bana Atananlar"msgid "Assignee"msgstr "Atan"+msgid "Assignees"+msgstr "Atananlar"+msgid "Assignment"msgstr "Görevlendirme"@@ -3491,12 +3537,18 @@ msgstr "Değişiklik Bildirisini İptal Et"msgid "Cancel Job"msgstr "İşi İptal Et"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "Siparişi İptal Et"msgid "Cancel Purchase Order"msgstr "Satın Alma Siparişini İptal Et"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "İadeyi İptal Et"@@ -3548,6 +3600,12 @@ msgstr "Öğe kimliği olmadan parçalar klasörüne taşınamaz"msgid "Cannot place order - no supplier associated with this item"msgstr "Sipariş verilemiyor - bu ürünle ilişkili tedarikçi yok"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "Sipariş verilemiyor — {count} kalemin tedarikçisi yok"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "Sipariş verilemiyor — 1 kalemin tedarikçisi yok"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "Muhasebeleştirilemiyor — Sevkiyat süresi dolmuş takip edilen varlıklar içeriyor."@@ -3753,6 +3811,9 @@ msgstr "Tipi Değiştir"msgid "Changed By"msgstr "Değiştiren"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "Bu görünüm için değişti. Stok kartının planlama ufku güncellenmedi."+msgid "Changelog"msgstr "Değişiklik Günlüğü"@@ -3853,6 +3914,9 @@ msgstr "Bu iade için satırları nasıl ekleyeceğinizi seçin."msgid "Choose what appears on the printed job traveler."msgstr "Yazdırılan İş takip kartında neyin görüneceğini seçin."+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "MRP'nin otomatik olarak ne zaman yeniden hesaplandığını seçin. Planlama sayfalarındaki Yeniden Hesapla seçeneğiyle istediğiniz zaman elle çalıştırabilirsiniz."+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "Stok kartları, teklifler ve iş emirlerindeki malzeme ağacı gezgininin her satırı açıklama veya stok kartı kimliğiyle etiketleyip etiketlemeyeceğini seçin."@@ -4068,6 +4132,9 @@ msgstr "Şirketler"msgid "Company"msgstr "Şirket"+msgid "Company default"+msgstr "Şirket varsayılanı"+msgid "Company group"msgstr "Şirket grubu"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "Belge okunamadı: {0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "{0} serbest bırakılamadı: {1}"@@ -5093,6 +5162,9 @@ msgstr "Departman oluşturuldu"msgid "Created failure mode"msgstr "Başarısız mod oluşturuldu"+msgid "Created from planning"+msgstr "Planlamadan oluşturuldu"+msgid "Created gauge type"msgstr "Ölçüm aleti türü oluşturuldu"@@ -5671,6 +5743,15 @@ msgstr "Ondalık Basamaklar"msgid "Declining balance"msgstr "Azalan Bakiye"+msgid "Decrease"+msgstr "Azalt"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "Gece derin saatlerinde, {name}."@@ -5737,6 +5818,9 @@ msgstr "Ekipman ve tesis bakımı için varsayılan muhasebe gideri hesabı"msgid "Default GL expense account for periodic depreciation runs."msgstr "Periyodik amortisman çalışmaları için varsayılan muhasebe gideri hesabı"+msgid "Default horizon (days)"+msgstr "Varsayılan ufuk (gün)"+msgid "Default Method"msgstr "Varsayılan Yöntem"@@ -5788,6 +5872,15 @@ msgstr "Bu sınıftaki yeni varlıklara önceden doldurulan varsayılan faydalımsgid "Defaults"msgstr "Varsayılanlar"+msgid "Defer"+msgstr "Ertele"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "Ertelenen Vergi Gideri"@@ -6368,6 +6461,9 @@ msgstr "Keşif"msgid "Dismiss"msgstr "Kapat"+msgid "Dismissed"+msgstr "Reddedildi"+msgid "Dispatch"msgstr "Bakım emri"@@ -6744,6 +6840,9 @@ msgstr "Her tedarikçinin her iş emrinden dış operasyonları yeni bir satınmsgid "Each, lb, ft…"msgstr "Her, lb, ft…"+msgid "Earlier weeks are consumed first."+msgstr "Daha önceki haftalar önce tüketilir."+msgid "Earliest operation start"msgstr "En erken operasyon başlangıcı"@@ -7503,6 +7602,9 @@ msgstr "Olay Türü"msgid "Events"msgstr "Etkinlikler"+msgid "Every 3 hours"+msgstr "Her 3 saatte bir"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "Şirket kapsamındaki tüm kayıtlar. Kimlik bilgileri, entegrasyon belirteçleri ve webhook'lar asla dahil edilmez."@@ -7635,6 +7737,15 @@ msgstr "Beklenen Teslim Alma"msgid "Expected Receipt Date"msgstr "Beklenen Teslim Alma Tarihi"+msgid "Expedite"+msgstr "Hızlandır"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "Alacak hesapları uzlaşması sırasında tahsil edilemez olarak silinen müşteri bakiyeleri için gider hesabı"@@ -8112,12 +8223,18 @@ msgstr "Sayı güncelleme başarısız"msgid "Failed to update item cost"msgstr "Ürün maliyeti güncellenemedi"+msgid "Failed to update job"+msgstr "İş emri güncellenemedi"+msgid "Failed to update lead times"msgstr "Tedarik sürelerini güncelleme başarısız oldu"msgid "Failed to update opportunity with purchase order"msgstr "Satın alma siparişi ile fırsat güncellenemedi"+msgid "Failed to update purchase order line"+msgstr "Satın alma siparişi satırı güncellenemedi"+msgid "Failed to update quote line"msgstr "Teklif satırını güncelleme başarısız oldu"@@ -8315,6 +8432,9 @@ msgstr "Adı Soyad"msgid "First Operation"msgstr "İlk İşlem"+msgid "First week the projected stock goes below zero"+msgstr "Projekte edilen stoğun sıfırın altına düştüğü ilk hafta"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "Sabit Kıymet"@@ -8381,6 +8501,12 @@ msgstr "herhangi bir şey için. Doğru kişiyi çekerler."msgid "Forecast"msgstr "Tahmin"+msgid "Forecast consumption"+msgstr "Tahmin tüketimi"++msgid "Forecast Consumption"+msgstr "Tahmin Tüketimi"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "Tahmin yöntemi: <0>{0}</0>. Bu satır aktif İş emirlerinden türetilmedi, bu nedenle kaynak yoktur."@@ -8829,8 +8955,8 @@ msgstr "Planlanmayan operasyonları var"msgid "Headers"msgstr "Başlıklar"-msgid "healthy"-msgstr "sağlıklı"+msgid "Healthy"+msgstr "Sağlıklı"msgid "Help"msgstr "Yardım"@@ -8979,6 +9105,9 @@ msgstr "Hesaplama tarihinden sonra erken ödeme iskontosunun kaç gün daha kullmsgid "How many days after the calculation date the full amount is due."msgstr "Hesaplama tarihinden sonra kaç gün tam tutar ödenmesi gerekir."+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "Açık bir siparişin ihtiyaç duyulan tarihten ne kadar gün sonra gelebileceği, MRP bunu hareket ettirmeyi önerilmeden önce. Ayarlar → Planlama'da ayarlanır; varsayılan değer 7 gündür."+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "Bu müşteri fatura tarihinden itibaren kaç gün ödeme yapmak için sahip; müşteri faturalarında varsayılan son tarihi belirler."@@ -9253,6 +9382,9 @@ msgstr "Bu adımda"msgid "In use"msgstr "Kullanımda"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "Şirketinizin saat diliminde ({companyTimeZone})."+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "Enterprise ayarlarınızın Geliştirici bölümünde, özel OAuth uygulamasının izinlerini «Uygulama belgelerinize yazabilir» izni dahil etmek için düzenleyin ve ardından entegrasyon ayarlarını yeniden kaydedin."@@ -9265,9 +9397,6 @@ msgstr "Uygulama içi bildirimler her zaman iletilir. Hangi konuların e-posta vmsgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "Uygulama içi bildirimler her zaman iletilir. Hangi konuların e-posta aracılığıyla sizi ulaştıracağını seçin."-msgid "inactive"-msgstr "pasif"-msgid "Inactive"msgstr "Pasif"@@ -9325,6 +9454,15 @@ msgstr "Incoterm"msgid "Incoterm Location"msgstr "Incoterm Lokasyonu"+msgid "Increase"+msgstr "Artır"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "Dolaylı"@@ -9364,6 +9502,9 @@ msgstr "Gruptan miras alınır: bu hesabın dağıtılmamış kârlara kapanıpmsgid "Inherited from the parent group."msgstr "Ana gruptan devralınan."+msgid "inherits {inheritedName}"+msgstr "devralınan {inheritedName}"+msgid "Input"msgstr "Giriş"@@ -9893,6 +10034,9 @@ msgstr "İş Önceliği"msgid "Job readable"msgstr "İş okunabilir"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "İş takip kartı"@@ -10108,9 +10252,15 @@ msgstr "Son Kullanılan"msgid "Late in the evening, {name}."msgstr "Akşamın geç saatlerinde, {name}."+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "Daha sonraki haftalar, daha önceki olanlar bittiğinde tüketilir."+msgid "Latest operation end"msgstr "En son işlem sonu"+msgid "Latest Order Date"+msgstr "Son Sipariş Tarihi"+msgid "Latitude"msgstr "Enlem"@@ -10153,6 +10303,9 @@ msgstr "Sonraki revizyonu otomatik olarak kullanmak için boş bırakın"msgid "Leave empty for exact match"msgstr "Tam eşleşme için boş bırakın"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "Tüm MRP planlarını görmek için boş bırakın veya 0 girin."+msgid "Leave this page"msgstr "Bu sayfadan ayrıl"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "Satırlar"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "Satın alma siparişi mal kabulu muhasebeleştirildiğinde satırlar burada görüntülenir ve yalnızca başka bir tedarikçi iadesi üzerinde henüz yetkilendirilmemiş miktarlar için. Kör iade için Satır Ekle'yi kullanın."+msgstr "Satınalma siparişi mal kabulü muhasebeleştirildiğinde satırlar burada görünür ve yalnızca başka bir tedarikçi iadesinde henüz yetkilendirilmemiş miktarlar için. Kör iade için Satır Ürün Ekle kullanın."msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "Satırlar, bir satış siparişi sevkiyatı muhasebeleştirildiğinde burada görünür ve yalnızca başka bir RMA üzerinde zaten yetkilendirilmemiş miktarlar için. Kör iade için satırı ekle kullanın."@@ -10441,6 +10594,12 @@ msgstr "Uzun Açıklama"msgid "Longitude"msgstr "Boylam"+msgid "Look ahead (weeks)"+msgstr "İleri Görüş (haftalar)"++msgid "Look back (weeks)"+msgstr "Geriye Görüş (haftalar)"+msgid "Looks empty here"msgstr "Burada boş görünüyor"@@ -10570,6 +10729,12 @@ msgstr "Bakım Türü"msgid "Make"msgstr "Üret"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "{quantity} üret"+msgid "Make Active"msgstr "Aktif Yap"@@ -10847,6 +11012,9 @@ msgstr "Malzeme Stok Kartı"msgid "Material Planning"msgstr "Malzeme Planlama"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "Malzeme planlama yalnızca bu kadar gün içinde gerçekleşmesi gereken eylemleri ve önerilen siparişleri gösterir; böylece uzak gelecekteki gereksinimler önemli olana kadar yol dışında kalır. Bir stok kartının kendi planlama ufku bu varsayılanı geçersiz kılar."+msgid "Material Properties"msgstr "Malzeme Özellikleri"@@ -11231,6 +11399,18 @@ msgstr "MRP (planlama)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP otomatik olarak her 3 saatte bir çalışır, ancak buradan manuel olarak çalıştırabilirsiniz."+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP her gün {time} ({timeZone}) saatinde otomatik olarak çalışır, ancak buradan manuel olarak çalıştırabilirsiniz."++msgid "MRP Schedule"+msgstr "MRP Çizelgesi"++msgid "MRP Suggestions"+msgstr "MRP Önerileri"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP, mevcut bir siparişi ancak tarihinden bu sayıda günden fazla fark olduğunda taşımayı önerir. Daha küçük farklar, iş listesinin sessiz kalması için yalnız bırakılır."+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "Bu Proses üzerinde aynı anda birden fazla İş emri çalışabilir — örneğin bir lazer masası, fırın veya kaplama havuzu"@@ -11498,9 +11678,6 @@ msgstr "Yeni ödeme koşulu"msgid "New Picking List"msgstr "Yeni Toplama Listesi"-msgid "New PO"-msgstr "Yeni Sipariş"-msgid "New Price Override"msgstr "Yeni Fiyat Geçersiz Kılma"@@ -12205,6 +12382,9 @@ msgstr "Depolama birimi yok"msgid "No storage units or tracking numbers match."msgstr "Depolama birimleri veya takip numaraları eşleşmiyor."+msgid "No Supplier"+msgstr "Tedarikçi yok"+msgid "No suppliers yet"msgstr "Henüz tedarikçi yok"@@ -12555,6 +12735,9 @@ msgstr "Zamanında teslimat"msgid "Onboard your agent to Carbon"msgstr "Aracınızı Carbon'a dahil edin"+msgid "Once a day"+msgstr "Günde bir kez"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "Bu gözden çıkan açık iş emri talebi ve beklemede transferler"msgid "Open jobs"msgstr "Açık İş emirleri"+msgid "Open Jobs"+msgstr "Açık İş Emirleri"+msgid "Open menu"msgstr "Menüyü aç"msgid "Open navigation"msgstr "Gezinmeyi aç"+msgid "Open Orders"+msgstr "Açık Siparişler"+msgid "Open payables by supplier and age"msgstr "Tedarikçi ve yaşa göre açık borçlar"@@ -12932,9 +13121,18 @@ msgstr "Bu iş emri için {0} × {substitute} sipariş et"msgid "Order {0} for this job"msgstr "Bu iş için {0} sipariş et"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "{quantity} sipariş et"+msgid "Order by"msgstr "Sipariş tarihi"+msgid "Order By"+msgstr "Sırala"+msgid "Order date"msgstr "Sipariş tarihi"@@ -13091,6 +13289,9 @@ msgstr "Sahip"msgid "Owner (cost center)"msgstr "Sahip (Maliyet merkezi)"+msgid "Ownership"+msgstr "Sahiplik"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "Sahibi: {0}"@@ -13569,9 +13770,36 @@ msgstr "Planlanan Zaman"msgid "Planning"msgstr "Planlama"+msgid "Planning action"+msgstr "Planlama aksiyonu"++msgid "Planning horizon"+msgstr "Planlama ufku"++msgid "Planning Horizon"+msgstr "Planlama Ufku"++msgid "Planning Horizon (Days)"+msgstr "Planlama Ufku (Gün)"++msgid "Planning Horizon:"+msgstr "Planlama Ufku:"++msgid "Planning Ownership"+msgstr "Planlama Sahipliği"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "Planlama turları, bu sayının tam katı kadar yenileme önermiştir."+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "Planlama yalnızca bu kadar gün içinde gerçekleşmesi gereken eylemleri ve önerilen siparişleri gösterir. Şirket varsayılanını kullanmak için boş bırakın, veya bu stok kartının tümünü görmek için 0 girin."+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "Önerilen yenileme miktarı üzerinde planlamanın alt sınırı; bir tedarikçinin MOQ'sından farklı olan, tedarikçi parçası kaydında bulunan."@@ -13980,6 +14208,9 @@ msgstr "Proje Planı"msgid "Project start"msgstr "Proje başlangıcı"+msgid "Projected"+msgstr "Öngörülen"+msgid "Projected completion"msgstr "Öngörülen tamamlanma"@@ -14001,6 +14232,12 @@ msgstr "{0} haftası için öngörülen stok tükenmesi"msgid "Projected stock"msgstr "Tahmini stok"+msgid "Projected stock by week"+msgstr "Haftalara göre projekte edilen stok"++msgid "Projected stock is already below zero this week"+msgstr "Projekte edilen stok bu hafta zaten sıfırın altında"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "{0} haftasında öngörülen stoksuzluk"@@ -14139,6 +14376,9 @@ msgstr "Satın Alma Siparişi"msgid "Purchase Order Amount"msgstr "Satın Alma Siparişi Tutarı"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "Satın Alma Siparişi onay kuralı"@@ -14166,6 +14406,9 @@ msgstr "Satın Alma Siparişleri"msgid "Purchase Orders and Planning"msgstr "Satın Alma Siparişleri ve Planlama"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "Satın alma siparişleri gerekli"@@ -14272,9 +14515,6 @@ msgstr "Miktar"msgid "Qty On Hand"msgstr "Elde Bulunan Miktar"-msgid "Qty to Order"-msgstr "Sipariş Edilecek Miktar"-msgid "Qty. Complete"msgstr "Tamamlanan Miktar"@@ -14568,6 +14808,9 @@ msgstr "Teklif İçin Hazır"msgid "ready to keep or revert"msgstr "tutmak veya geri almak için hazır"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "Gerçek siparişler önce kendi haftalı talep tahminlerini tüketir, ardından şirketin penceresindeki daha önceki ve daha sonraki haftaları, böylece tahmin ve gerçek talep hiçbir zaman aynı adetler için planlanmaz."+msgid "Real-time inventory and shop-floor visibility"msgstr "Gerçek zamanlı envanter ve atölye tabanı görünürlüğü"@@ -14880,9 +15123,15 @@ msgstr "Serbest Bırakma Kontrolü"msgid "Release Job"msgstr "İş emrini serbest bırak"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "İş emirlerini Serbest Bırak"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "Yayınlandı"@@ -15034,6 +15283,9 @@ msgstr "Etiket önizlemesi oluşturuluyor..."msgid "Reopen"msgstr "Yeniden Aç"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "Yeniden Sırala"@@ -15221,6 +15473,12 @@ msgstr "Onarım Gerektirir"msgid "Requires staffing"msgstr "Personel gerektirir"+msgid "Reschedule tolerance"+msgstr "Yeniden planlama toleransı"++msgid "Reschedule Tolerance"+msgstr "Yeniden Planlama Toleransı"+msgid "Reserve floor"msgstr "Rezerv tabanı"@@ -15279,6 +15537,12 @@ msgstr "kaynaklar"msgid "Resources"msgstr "Kaynaklar"+msgid "Responsible employee"+msgstr "Sorumlu Çalışan"++msgid "Responsible Employee"+msgstr "Sorumlu Çalışan"+msgid "Restock"msgstr "Yeniden Stoklama"@@ -15654,6 +15918,9 @@ msgstr "Çalıştırma ID'si"msgid "Run month-end close and standard reconciliations"msgstr "Ay sonu kapanışını ve standart mutabakatları çalıştırın"+msgid "Run MRP"+msgstr "MRP Çalıştır"+msgid "Run payment batches and track aging"msgstr "Ödeme partilerini çalıştırın ve yaşlandırmayı izleyin"@@ -16087,7 +16354,7 @@ msgid "Search by linear issue title..."msgstr "Linear sorunu başlığı ile ara..."msgid "Search by receipt, PO, or item"-msgstr "Mal kabul, Satın alma siparişi veya Stok kartı ile ara"+msgstr "Mal kabul, PO veya stok kartına göre ara"msgid "Search by shipment, sales order, or item"msgstr "Sevkiyat, satış siparişi veya stok kartı ile ara"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "Operasyon seç"msgid "Select posted receipt lines from this supplier to return."-msgstr "Bu tedarikçiden muhasebeleştirilmiş mal kabul satırlarını iade etmek üzere seçin."+msgstr "Bu tedarikçiden iade etmek üzere muhasebeleştirilmiş mal kabul satırlarını seçin."msgid "Select posted shipment lines to this customer to return."msgstr "Bu müşteriye muhasebeleştirilmiş sevkiyat satırlarını iade etmek için seçin."@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "Oturum Kilitli"msgid "Set a customer on this return to add from a shipment."-msgstr "Sevkiyat'dan eklemek için bu iade'de bir müşteri ayarlayın."+msgstr "Sevkiyattan eklemek için bu iade işlemine bir müşteri belirleyin."msgid "Set a supplier on this return to add from a receipt."msgstr "Mal kabulünden eklemek için bu iade kaydında bir tedarikçi belirleyin."@@ -17243,6 +17510,9 @@ msgstr "Başlat"msgid "Start {0} Day Free Trial"msgstr "{0} Gün Ücretsiz Deneme Başlat"+msgid "Start By"+msgstr "Şundan Başla"+msgid "Start counting"msgstr "Saymaya başla"@@ -17386,6 +17656,9 @@ msgstr "Adımlar kendi başlarına oluşturulur, ardından bir parça olarak takmsgid "Still dark out on the floor."msgstr "Fabrikada hala karanlık."+msgid "Stock Availability"+msgstr "Stok Mevcudiyeti"+msgid "Stock movement corrected"msgstr "Stok hareketi düzeltildi"@@ -17624,6 +17897,15 @@ msgstr "Eşleştirme Öner"msgid "Suggest with AI"msgstr "Yapay Zeka ile Öner"+msgid "Suggested Jobs"+msgstr "Önerilen İş Emirleri"++msgid "Suggested Orders"+msgstr "Önerilen Siparişler"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "Önerilen siparişler bu stok kartının planlama ufkundan sonra gereklidir. Ufku genişleterek bunları dahil edin."+msgid "Suggested orders you haven't placed yet."msgstr "Henüz yerleştirmediğiniz önerilen siparişler."@@ -17874,8 +18156,8 @@ msgstr "Senkronize Et"msgid "Sync Activity"msgstr "Senkronizasyon Etkinliği"-msgid "sync off"-msgstr "senkronizasyon kapalı"+msgid "Sync Off"+msgstr "Senkronizasyon kapalı"msgid "Sync operation"msgstr "Senkronizasyon işlemi"@@ -18642,6 +18924,9 @@ msgstr "Peşin ödeme iskontosunun yüzdesi. İskonto yoksa 0 kullanın."msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "Bu tür yeni çalışanların otomatik olarak aldığı izin kümesi; burada düzenleme, yalnızca gelecekteki işe almalar için şablonu değiştirir - mevcut çalışanlar, açıkça toplu güncellenmediği sürece sahip olduklarını tutarlar."+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "Planlama aksiyonunun atandığı kişi: o lokasyondaki stok kartının sahibi, değilse stok kartı grubunun, değilse lokasyonun, değilse şirketin varsayılanı."+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "Çalışmanızın ve stokunuzun bulunduğu fabrikalar, depolar ve tesisler"@@ -18663,6 +18948,9 @@ msgstr "Bu iş merkezinin çalıştırabileceği prosesler; operasyonları zamanmsgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "Sağlayıcı boyut hedefleri sunmaz. Önce sağlayıcıda özelliği etkinleştirin (örneğin, izleme kategorileri, sınıf izleme veya alanlar)."+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Bu Satırın fiyatlandırıldığı Miktar kırılım noktaları; her sütun Satın almacı–Tedarikçi müzakereleri ve aşağı yönlü belgelere dönüştürme için kendi birim başına Fiyatını taşır."@@ -18991,6 +19279,9 @@ msgstr "Bu Muhasebe fişi girişleri hala Taslak durumundadır, bu nedenle Borçmsgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "Bu operasyonlar birden fazla tedarikçili bir proses kullanır. Her biri için bir tedarikçi seçin."+msgid "These orders could not be loaded. Close and reopen to try again."+msgstr "Bu siparişler yüklenemedi. Kapatıp yeniden açarak tekrar deneyin."+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."@@ -19469,6 +19760,9 @@ msgstr "Tolerans+"msgid "Tolerance (+/-)"msgstr "Tolerans (+/-)"+msgid "Tolerance (days)"+msgstr "Tolerans (gün)"+msgid "Tomorrow"msgstr "Yarın"@@ -19847,8 +20141,8 @@ msgstr "Geri Al"msgid "Ungroup"msgstr "Grubu Çöz"-msgid "unhealthy"-msgstr "sağlıksız"+msgid "Unhealthy"+msgstr "Sağlıksız"msgid "Uninstall"msgstr "Kaldır"@@ -20936,6 +21230,9 @@ msgstr "Ne zaman {name} değişir"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "Bir bitmiş ürünün raf ömrü Hesaplanan olarak ayarlandığında, hesaplamaya hangi tüketilen girdilerin dahil edileceğini seçin."+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "Bir satış siparişi veya iş emri kalan tahmini olmayan bir haftaya düştüğünde, yakındaki haftalardan tahmin tüketir, üzerine eklenmek yerine. Her ikisini de 0 olarak ayarlayın, yalnızca aynı hafta içinde netleştirmek için."+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "Bir seri veya parti ne zaman süresinin dolduğu ve kullanıldığında ne olduğu — bir şirket politikası Uyar, Engelle veya EngellePrekesiyle yer alabilir."@@ -21128,6 +21425,9 @@ msgstr "Kimin ne konuda eğitim aldığı, hangi formatta eğitim alacağı. Sizmsgid "Who has to approve quotes, orders, and purchases — and when"msgstr "Teklifleri, siparişleri ve satın almaları kimin onaylaması gerektiği — ve ne zaman"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "MRP planlama eylemlerinin sahibi kimdir. Lokasyonlar şirket varsayılanını devralır; stok kartı grupları bulundukları lokasyonu devralır. En spesifik atama kazanır ve her stok kartı, Planlama sekmesinde değiştirebilir."+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "Bakım ile ilgili bakım emirleri için kimler bildirim almalıdır?"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 4c005f58d0..75869e0ffe 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -75,6 +75,10 @@ msgstr "{0, plural, one {# 行链接到该公司外的数据,无法制作当msgid "{0, plural, one {# row links to data outside this company, so it can't be backed up. Skipping it backs up everything else.} other {# rows link to data outside this company, so they can't be backed up. Skipping them backs up everything else.}}"msgstr "{0, plural, one {# 行链接到该公司外的数据,无法备份。跳过它可以备份其他所有内容。} other {# 行链接到该公司外的数据,无法备份。跳过它们可以备份其他所有内容。}}"+#. placeholder {0}: item.demandAccumulationPeriod+msgid "{0, plural, one {# week} other {# weeks}}"+msgstr "{0, plural, other {#周}}"+#. placeholder {0}: componentNodeIds.lengthmsgid "{0, plural, one {The planner treats this component as one rigid body — one step in the instructions. Re-run the plan to apply.} other {The planner treats these # components as one rigid body — one step in the instructions. Re-run the plan to apply.}}"msgstr "{0, plural, one {计划员将此组件视为一个刚体 — 说明中的一个步骤。重新运行计划以应用。} other {计划员将这 # 个组件视为一个刚体 — 说明中的一个步骤。重新运行计划以应用。}}"@@ -107,6 +111,10 @@ msgstr "{0} 仍被 {where} 使用,无法删除。请先将这些记录更改msgid "{0} cells with deltas"msgstr "{0} 个单元格有差异"+#. placeholder {0}: formatQuantity(consumed)+msgid "{0} consumed"+msgstr "{0} 已消耗"+#. placeholder {0}: line.creditableQuantity#. placeholder {1}: line.quantityCredited#. placeholder {2}: line.quantityShipped@@ -261,6 +269,11 @@ msgstr "{0} 个值"msgid "{0} values missing"msgstr "{0} 个值缺失"+#. placeholder {0}: warning.readableId+#. placeholder {1}: warning.message+msgid "{0} was released with a problem: {1}"+msgstr ""+#. placeholder {0}: file.namemsgid "{0} will be saved as {name}"msgstr "{0} 将被保存为 {name}"@@ -319,6 +332,9 @@ msgstr "{count, plural, one {# 个有余额的账户} other {# 个有余额的msgid "{count, plural, one {# course} other {# courses}}"msgstr "{count, plural, one {# 门课程} other {# 门课程}}"+msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgstr "{count, plural, other {{fenceLabel}之后还有 # 个}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {关闭 # 生产批次} other {关闭 # 生产批次}}"@@ -340,6 +356,9 @@ msgstr "{days}天"msgid "{delegatedTo} posts this to your ledger, so Carbon doesn't push it. Your saved choice is kept in case that changes."msgstr "{delegatedTo}将其发布到您的分类账,因此Carbon不会推送它。您保存的选择将被保留,以防情况发生变化。"+msgid "{dismissed} dismissed"+msgstr "{dismissed} 已忽略"+msgid "{done} of {total} phases complete"msgstr "{done}个/{total}个阶段已完成"@@ -360,6 +379,9 @@ msgstr "还有{hiddenCount}个:{hiddenNames}"msgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."msgstr "已插入{inserted}条,已更新{updated}条,需修复{0}条,已跳过{1}条。"+msgid "{leadTime, plural, one {# day} other {# days}}"+msgstr "{leadTime, plural, other {#天}}"+msgid "{linesCount, plural, one {# line} other {# lines}}"msgstr "{linesCount, plural, one {# 行} other {# 行}}"@@ -415,6 +437,9 @@ msgstr "{remaining, plural, one {# 个阶段剩余} other {# 个阶段剩余}}"msgid "{resourceCount} resources · {reservationCount} reservations · {jobCount} jobs"msgstr "{resourceCount} 个资源 · {reservationCount} 个预留 · {jobCount} 个任务"+msgid "{revisionLabel} will be reopened for planning as its next revision. The document already sent to the supplier is unchanged until you finalize and resend the order."+msgstr ""+msgid "{scopeCount} permissions"msgstr "{scopeCount} 个权限"@@ -454,9 +479,6 @@ msgstr "{unmappedRequiredCount, plural, one {先映射剩余的 # 个必需账msgid "{unschedulableCount} can't be scheduled"msgstr "{unschedulableCount}无法排程"-msgid "{updatedJobCount} jobs updated"-msgstr "已更新{updatedJobCount}个工单"-msgid "{uploadedFileName} uploaded — fields filled from the document."msgstr "已上传{uploadedFileName}——字段从文件填充。"@@ -497,6 +519,9 @@ msgstr "≈ {0}"msgid "0 operations"msgstr "0个工序"+msgid "0 suggests a move for any date difference."+msgstr "0 代表为任何日期差异建议移动。"+msgid "0-4 weeks"msgstr "0-4 周"@@ -518,9 +543,6 @@ msgstr "1个草稿分录"msgid "1 job created"msgstr "1 个作业已创建"-msgid "1 job updated"-msgstr "1 个作业已更新"-msgid "1 part skipped — it already has an open job"msgstr "1个零件已跳过——它已有未结的工单"@@ -530,6 +552,9 @@ msgstr "1 个零件已跳过 — 没有需要生产的"msgid "1 problem — not published"msgstr "1个问题——未发布"+msgid "1 Purchase = {conversionFactor} Inventory"+msgstr "1 采购 = {conversionFactor} 库存管理"+msgid "1 suggested batch"msgstr "1 个建议生产批次"@@ -542,6 +567,9 @@ msgstr "12个月度期间"msgid "13+ weeks"msgstr "13周以上"+msgid "1st Negative On Hand"+msgstr "首次出现负库存"+msgid "1Y"msgstr "1年"@@ -1082,6 +1110,9 @@ msgstr "步骤需要一个名称。"msgid "A stored booking of a work center or operator for one operation's placed time span — the materialized output of a scheduling run, and what the Forecast draws."msgstr "工作中心或操作员在某个工序预定时间段内的预约记录——排程运行的物化输出,也是预测显示的内容。"+msgid "A suggestion MRP writes after each run: Order or Make new supply, or Expedite, Defer, Increase, Decrease or Cancel an open purchase order line or job. Apply it from the planning page, dismiss it, or assign it."+msgstr "MRP在每次运行后写入的建议:订购或自制新供应,或加急、延期、增加、减少或取消未结的采购订单行或工单。从计划页面应用它、关闭它或分配它。"+msgid "A supplier contact and location are optional"msgstr "供应商联系人和地点是可选的"@@ -2006,6 +2037,12 @@ msgstr "此工作的一道工序在此批次中运行"msgid "An operation's position in its work center's queue — the order the floor picks work up. The engine numbers it from placement order (earliest projected start first); reordering cards on the Work Centers board overrides it without changing dates."msgstr "工序在所在工作中心队列中的位置——车间人员拿工作的顺序。引擎按安排顺序编号(最早预计开始时间优先);在工作中心看板上重新排列卡片会覆盖它,不会改变日期。"+msgid "An order raised from Material Planning follows the same approval rule as any other purchase order."+msgstr ""++msgid "An order raised from Material Planning is released as soon as it is finalized, without an approval request."+msgstr ""+msgid "An unexpected error occurred while connecting to Onshape. Save the integration settings to try again."msgstr "连接到 Onshape 时出现意外错误。保存集成设置以重试。"@@ -2167,6 +2204,9 @@ msgstr "应用定价规则"msgid "Apply Rules On Top"msgstr "在顶部应用规则"+msgid "Apply Suggested Changes"+msgstr "应用建议的更改"+msgid "Apply suggestions"msgstr "应用建议"@@ -2824,6 +2864,9 @@ msgstr "分配给"msgid "Assign to Groups"msgstr "分配给组"+msgid "Assign to Me"+msgstr "分配给我"+msgid "Assigned"msgstr "已分配"@@ -2836,6 +2879,9 @@ msgstr "已分配给我"msgid "Assignee"msgstr "经办人"+msgid "Assignees"+msgstr "经办人"+msgid "Assignment"msgstr "分配"@@ -3491,12 +3537,18 @@ msgstr "取消变更通知"msgid "Cancel Job"msgstr "取消工作"+msgid "Cancel job {target}"+msgstr ""+msgid "Cancel Order"msgstr "取消订单"msgid "Cancel Purchase Order"msgstr "取消采购订单"+msgid "Cancel purchase order {target}"+msgstr ""+msgid "Cancel Return"msgstr "取消退货"@@ -3548,6 +3600,12 @@ msgstr "无法在没有项目ID的情况下移动到零件桶"msgid "Cannot place order - no supplier associated with this item"msgstr "无法下单 - 此项目没有关联的供应商"+msgid "Cannot place the order — {count} items have no supplier"+msgstr "无法下单 — {count} 个物料没有供应商"++msgid "Cannot place the order — 1 item has no supplier"+msgstr "无法下单 — 1 个物料没有供应商"+msgid "Cannot post — shipment contains expired tracked entities."msgstr "无法过账 — 发货包含已过期的追踪实体。"@@ -3753,6 +3811,9 @@ msgstr "更改类型"msgid "Changed By"msgstr "更改者"+msgid "Changed for this view only. The item's planning horizon is not updated."+msgstr "仅对此视图进行了更改。该物料的计划周期未更新。"+msgid "Changelog"msgstr "更新日志"@@ -3853,6 +3914,9 @@ msgstr "选择如何向此退货添加行。"msgid "Choose what appears on the printed job traveler."msgstr "选择打印工单流转卡上显示的内容。"+msgid "Choose when MRP recalculates on its own. You can still run it yourself at any time with Recalculate on the planning pages."+msgstr "选择MRP何时自动重新计算。您可以随时在计划页面上使用「重新计算」功能手动运行。"+msgid "Choose whether the bill of material explorer on items, quotes, and jobs labels each line with its description or its item ID."msgstr "选择物料清单浏览器是否在物料、报价单和工单上用描述或物料 ID 标记每行。"@@ -4068,6 +4132,9 @@ msgstr "公司"msgid "Company"msgstr "公司"+msgid "Company default"+msgstr "公司默认值"+msgid "Company group"msgstr "公司集团"@@ -4840,8 +4907,10 @@ msgid "Could not read the document: {0}"msgstr "无法读取文件:{0}"#. placeholder {0}: d.failed.length+#. placeholder {0}: failure.readableId#. placeholder {0}: result.failed.length#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")+#. placeholder {1}: failure.message#. placeholder {1}: result.failed .map((f) => `${f.readableId} (${f.message})`) .join(", ")msgid "Could not release {0}: {1}"msgstr "无法下达{0}:{1}"@@ -5093,6 +5162,9 @@ msgstr "已创建部门"msgid "Created failure mode"msgstr "已创建故障模式"+msgid "Created from planning"+msgstr "从计划创建"+msgid "Created gauge type"msgstr "已创建量具类型"@@ -5671,6 +5743,15 @@ msgstr "小数位数"msgid "Declining balance"msgstr "余额递减法"+msgid "Decrease"+msgstr "减少"++msgid "Decrease job {target} to {amount}"+msgstr ""++msgid "Decrease purchase order {target} to {amount}"+msgstr ""+msgid "Deep in the small hours, {name}."msgstr "深夜时分,{name}。"@@ -5737,6 +5818,9 @@ msgstr "设备和设施维护的默认总账费用科目"msgid "Default GL expense account for periodic depreciation runs."msgstr "定期折旧处理的默认总账费用科目"+msgid "Default horizon (days)"+msgstr "默认计划周期(天数)"+msgid "Default Method"msgstr "默认方法"@@ -5788,6 +5872,15 @@ msgstr "新增此类资产时预填充的默认使用年限"msgid "Defaults"msgstr "默认值"+msgid "Defer"+msgstr "延后"++msgid "Defer job {target} to {date}"+msgstr ""++msgid "Defer purchase order {target} to {date}"+msgstr ""+msgid "Deferred Tax Expense"msgstr "递延所得税费用"@@ -6368,6 +6461,9 @@ msgstr "发现"msgid "Dismiss"msgstr "关闭"+msgid "Dismissed"+msgstr "已忽略"+msgid "Dispatch"msgstr "维护工单"@@ -6744,6 +6840,9 @@ msgstr "每个供应商的外协工序从每个工单转至一份新采购订单msgid "Each, lb, ft…"msgstr "每个、磅、英尺…"+msgid "Earlier weeks are consumed first."+msgstr "较早的周次先被消耗。"+msgid "Earliest operation start"msgstr "最早操作开始"@@ -7503,6 +7602,9 @@ msgstr "事件类型"msgid "Events"msgstr "事件"+msgid "Every 3 hours"+msgstr "每3小时"+msgid "Every company-scoped record. Credentials, integration tokens and webhooks are never included."msgstr "公司范围内的所有记录。凭据、集成令牌和 Webhook 永不包含在内。"@@ -7635,6 +7737,15 @@ msgstr "预期收货"msgid "Expected Receipt Date"msgstr "预期收货日期"+msgid "Expedite"+msgstr "加急"++msgid "Expedite job {target} to {date}"+msgstr ""++msgid "Expedite purchase order {target} to {date}"+msgstr ""+msgid "Expense account for customer balances written off as uncollectable on AR settlement"msgstr "应收账款结算时作为无法收回的客户余额的费用账户"@@ -8112,12 +8223,18 @@ msgstr "更新计数失败"msgid "Failed to update item cost"msgstr "更新项目成本失败"+msgid "Failed to update job"+msgstr "无法更新工单"+msgid "Failed to update lead times"msgstr "无法更新提前期"msgid "Failed to update opportunity with purchase order"msgstr "未能使用采购订单更新商机"+msgid "Failed to update purchase order line"+msgstr "无法更新采购订单行"+msgid "Failed to update quote line"msgstr "未能更新报价行"@@ -8315,6 +8432,9 @@ msgstr "名字"msgid "First Operation"msgstr "首次操作"+msgid "First week the projected stock goes below zero"+msgstr "投影库存首次低于零的周"+msgid "First-year additional deduction taken before the regular MACRS schedule begins."msgstr "在常规MACRS折旧计划开始之前的第一年额外扣除。"@@ -8381,6 +8501,12 @@ msgstr "用于任何事项。他们会调配合适的人员。"msgid "Forecast"msgstr "预测"+msgid "Forecast consumption"+msgstr "预测消耗"++msgid "Forecast Consumption"+msgstr "预测消耗"+#. placeholder {0}: forecastMethod ?? "unknown"msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."msgstr "预测方法: <0>{0}</0>。此行不是从活跃工单派生的,因此没有可用的父源。"@@ -8829,7 +8955,7 @@ msgstr "有无法排程的工序"msgid "Headers"msgstr "标头"-msgid "healthy"+msgid "Healthy"msgstr "健康"msgid "Help"@@ -8979,6 +9105,9 @@ msgstr "计算日期后多少天提前付款折扣仍然可用。"msgid "How many days after the calculation date the full amount is due."msgstr "计算日期后多少天全额应付。"+msgid "How many days an open order may land from the date it is needed before MRP suggests moving it. Set in Settings → Planning; the default is 7 days."+msgstr "未结订单可以晚于需要日期多少天到达,MRP才建议移动它。在设置 → 计划中设置;默认为7天。"+msgid "How many days from invoice date this customer is given to pay; drives the default due date on customer invoices."msgstr "此客户从发票日期起支付的天数; 确定客户发票上的默认到期日期。"@@ -9253,6 +9382,9 @@ msgstr "在此步骤中"msgid "In use"msgstr "使用中"+msgid "In your company's time zone ({companyTimeZone})."+msgstr "在您公司的时区({companyTimeZone})。"+msgid "In your Enterprise settings under Developer, edit the private OAuth application's permissions to include \"Application can write to your documents\", then save the integration settings again."msgstr "在您的企业设置的开发者下,编辑私有 OAuth 应用程序的权限以包括\"应用程序可以写入您的文档\",然后再次保存集成设置。"@@ -9265,9 +9397,6 @@ msgstr "应用内通知始终会被传递。选择哪些主题也通过电子邮msgid "In-app notifications are always delivered. Choose which topics also reach you by email."msgstr "应用内通知始终会被传递。选择哪些主题也通过电子邮件发送给您。"-msgid "inactive"-msgstr "已停用"-msgid "Inactive"msgstr "已停用"@@ -9325,6 +9454,15 @@ msgstr "贸易术语"msgid "Incoterm Location"msgstr "贸易术语地点"+msgid "Increase"+msgstr "增加"++msgid "Increase job {target} to {amount}"+msgstr ""++msgid "Increase purchase order {target} to {amount}"+msgstr ""+msgid "Indirect"msgstr "间接"@@ -9364,6 +9502,9 @@ msgstr "从公司继承:此账户是结转至未分配利润(收益)还是msgid "Inherited from the parent group."msgstr "从父组继承。"+msgid "inherits {inheritedName}"+msgstr "继承自 {inheritedName}"+msgid "Input"msgstr "输入"@@ -9893,6 +10034,9 @@ msgstr "工作优先级"msgid "Job readable"msgstr "工作可读性"+msgid "Job released"+msgstr ""+msgid "Job Traveler"msgstr "工单流转卡"@@ -10108,9 +10252,15 @@ msgstr "最后使用"msgid "Late in the evening, {name}."msgstr "傍晚晚些时候,{name}。"+msgid "Later weeks are consumed once earlier ones are used up."+msgstr "一旦较早的周次用完,较晚的周次将被消耗。"+msgid "Latest operation end"msgstr "最新操作结束"+msgid "Latest Order Date"+msgstr "最晚订单日期"+msgid "Latitude"msgstr "纬度"@@ -10153,6 +10303,9 @@ msgstr "留空以自动使用下一个修订版"msgid "Leave empty for exact match"msgstr "留空以精确匹配"+msgid "Leave empty, or enter 0, to show everything MRP plans."+msgstr "留空或输入 0 以显示 MRP 计划的所有内容。"+msgid "Leave this page"msgstr "离开此页面"@@ -10257,7 +10410,7 @@ msgid "Lines"msgstr "行"msgid "Lines appear here once a purchase order receipt has been posted, and only for quantities not already authorized on another supplier return. Use Add Line Item for a blind return."-msgstr "采购订单收货已过账后,行将显示在此处,并且仅限于尚未在另一个供应商退货中授权的数量。使用添加行项目进行盲退货。"+msgstr "采购订单收货过账后,行才会在此显示,且仅针对尚未在其他供应商退货上授权的数量。盲目退货请使用添加行项目。"msgid "Lines appear here once a sales order shipment has been posted, and only for quantities not already authorized on another RMA. Use Add Line Item for a blind return."msgstr "销售订单发货已过账后,行将显示在此处,仅适用于尚未在另一个RMA中授权的数量。对于盲目退货,请使用添加行项目。"@@ -10441,6 +10594,12 @@ msgstr "长描述"msgid "Longitude"msgstr "经度"+msgid "Look ahead (weeks)"+msgstr "前瞻(周)"++msgid "Look back (weeks)"+msgstr "回顾(周)"+msgid "Looks empty here"msgstr "看起来这里是空的"@@ -10570,6 +10729,12 @@ msgstr "维护类型"msgid "Make"msgstr "制造"+msgid "Make {amount} for {date}"+msgstr ""++msgid "Make {quantity}"+msgstr "制造 {quantity}"+msgid "Make Active"msgstr "启用"@@ -10847,6 +11012,9 @@ msgstr "原材料物料"msgid "Material Planning"msgstr "物料规划"+msgid "Material planning shows only the actions and suggested orders due within this many days from today, so far-out needs stay out of the way until they matter. An item's own planning horizon overrides this default."+msgstr "物料规划仅显示今天起 X 天内到期的操作和建议订单,以便远期需求不会造成干扰,直到需要时才显示。该物料自己的计划周期会覆盖此默认值。"+msgid "Material Properties"msgstr "原材料属性"@@ -11231,6 +11399,18 @@ msgstr "MRP (计划)"msgid "MRP runs automatically every 3 hours, but you can run it manually here."msgstr "MRP 每 3 小时自动运行一次,但您也可以在此手动运行。"+msgid "MRP runs automatically every day at {time} ({timeZone}), but you can run it manually here."+msgstr "MRP 将在每天 {time} ({timeZone}) 自动运行,但您也可以在此手动运行。"++msgid "MRP Schedule"+msgstr "MRP 时间表"++msgid "MRP Suggestions"+msgstr "MRP 建议"++msgid "MRP suggests moving an existing order only when its date is off by more than this many days. Smaller gaps are left alone so the worklist stays quiet."+msgstr "MRP 仅在现有订单的日期偏差超过此天数时才建议移动订单。较小的偏差将被忽略,以保持工作列表的清晰。"+msgid "Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath"msgstr "多个作业可以同时在此工序上运行 — 例如激光切割机、炉子或电镀槽"@@ -11498,9 +11678,6 @@ msgstr "新建付款条件"msgid "New Picking List"msgstr "新拣货单"-msgid "New PO"-msgstr "新采购订单"-msgid "New Price Override"msgstr "新价格覆盖"@@ -12140,7 +12317,7 @@ msgid "No results found"msgstr "未找到结果"msgid "No returnable lines for this customer"-msgstr "此客户没有可退货行。"+msgstr "此客户无可退货行"msgid "No returnable lines for this supplier"msgstr "此供应商没有可退货的行"@@ -12205,6 +12382,9 @@ msgstr "无存储单元"msgid "No storage units or tracking numbers match."msgstr "没有存储单元或追踪号与之匹配。"+msgid "No Supplier"+msgstr "无供应商"+msgid "No suppliers yet"msgstr "还没有供应商"@@ -12555,6 +12735,9 @@ msgstr "准时交付"msgid "Onboard your agent to Carbon"msgstr "将您的代理接入Carbon"+msgid "Once a day"+msgstr "每天一次"+#. placeholder {0}: company?.baseCurrencyCode#. placeholder {1}: initialValues.codemsgid "One {0} is equal to how many {1}?"@@ -12707,12 +12890,18 @@ msgstr "未结工单需求加上从此料箱转出的未清调拨"msgid "Open jobs"msgstr "未结工单"+msgid "Open Jobs"+msgstr "未结工单"+msgid "Open menu"msgstr "打开菜单"msgid "Open navigation"msgstr "打开导航"+msgid "Open Orders"+msgstr "未结订单"+msgid "Open payables by supplier and age"msgstr "按供应商和期限打开应付款项"@@ -12932,9 +13121,18 @@ msgstr "为此工单订购{0} × {substitute}"msgid "Order {0} for this job"msgstr "为此作业订购 {0}"+msgid "Order {amount} for {date}"+msgstr ""++msgid "Order {quantity}"+msgstr "订购 {quantity}"+msgid "Order by"msgstr "订购截止日期"+msgid "Order By"+msgstr "排序方式"+msgid "Order date"msgstr "订单日期"@@ -13091,6 +13289,9 @@ msgstr "负责人"msgid "Owner (cost center)"msgstr "负责人(成本中心)"+msgid "Ownership"+msgstr "所有权"+#. placeholder {0}: i18n._(member.owns)msgid "Owns: {0}"msgstr "拥有:{0}"@@ -13569,9 +13770,36 @@ msgstr "已计划时间"msgid "Planning"msgstr "计划"+msgid "Planning action"+msgstr "计划行动"++msgid "Planning horizon"+msgstr "计划周期"++msgid "Planning Horizon"+msgstr "计划周期"++msgid "Planning Horizon (Days)"+msgstr "计划周期(天)"++msgid "Planning Horizon:"+msgstr "计划周期:"++msgid "Planning Ownership"+msgstr "计划所有权"++msgid "Planning purchase orders need approval"+msgstr ""++msgid "Planning purchase orders skip approval"+msgstr ""+msgid "Planning rounds suggested replenishment up to a whole multiple of this number."msgstr "计划将建议的补货数量舍入至该数字的整数倍。"+msgid "Planning shows only the actions and suggested orders due within this many days. Leave empty to use the company default, or enter 0 to show everything for this item."+msgstr "计划仅显示 X 天内到期的操作和建议订单。留空以使用公司默认值,或输入 0 以显示此物料的所有内容。"+msgid "Planning's lower bound on a suggested replenishment quantity; distinct from a supplier's MOQ, which lives on the supplier-part record."msgstr "计划对建议补货数量的下限;不同于供应商的最小订购量 (MOQ),该值位于供应商-物料记录上。"@@ -13980,6 +14208,9 @@ msgstr "项目计划"msgid "Project start"msgstr "项目开始"+msgid "Projected"+msgstr "预测"+msgid "Projected completion"msgstr "预计完成"@@ -14001,6 +14232,12 @@ msgstr "{0}周的预计缺货"msgid "Projected stock"msgstr "预计库存"+msgid "Projected stock by week"+msgstr "按周投影库存"++msgid "Projected stock is already below zero this week"+msgstr "投影库存本周已经低于零"+#. placeholder {0}: formatWeek(stockoutDate)msgid "Projected stockout the week of {0}"msgstr "第 {0} 周预计缺货"@@ -14139,6 +14376,9 @@ msgstr "采购订单"msgid "Purchase Order Amount"msgstr "采购订单金额"+msgid "Purchase Order Approval"+msgstr ""+msgid "Purchase Order approval rule"msgstr "采购订单审批规则"@@ -14166,6 +14406,9 @@ msgstr "采购订单"msgid "Purchase Orders and Planning"msgstr "采购订单和计划"+msgid "Purchase orders created from Material Planning can be finalized without going through the approval rule. Adding, changing or deleting a line on one by hand sends it back through approval."+msgstr ""+msgid "Purchase orders required"msgstr "采购订单必需"@@ -14272,9 +14515,6 @@ msgstr "数量"msgid "Qty On Hand"msgstr "现有数量"-msgid "Qty to Order"-msgstr "订购数量"-msgid "Qty. Complete"msgstr "数量. 完成"@@ -14568,6 +14808,9 @@ msgstr "可报价"msgid "ready to keep or revert"msgstr "就绪保存或恢复"+msgid "Real orders use up the demand forecast for their own week first, then earlier and later weeks within the company's window, so forecast and actual demand are never both planned for the same units."+msgstr "实际订单首先消耗其本周的需求预测,然后消耗公司时间窗口内较早和较晚周次的需求预测,因此预测和实际需求永远不会同时为相同的物料单位进行计划。"+msgid "Real-time inventory and shop-floor visibility"msgstr "实时库存管理和车间可见性"@@ -14880,9 +15123,15 @@ msgstr "下达控制"msgid "Release Job"msgstr "下达工单"+msgid "Release job {target} by {date}"+msgstr ""+msgid "Release Jobs"msgstr "下达工单"+msgid "Release purchase order {target} by {date}"+msgstr ""+msgid "Released"msgstr "已下达"@@ -15034,6 +15283,9 @@ msgstr "正在渲染标签预览..."msgid "Reopen"msgstr "重新打开"+msgid "Reopen as Revision"+msgstr ""+msgid "Reorder"msgstr "重新排序"@@ -15116,7 +15368,7 @@ msgid "Reports"msgstr "报告"msgid "Reprice with current rules"-msgstr "使用当前规则重新定价"+msgstr "按当前规则重新定价"#. placeholder {0}: format(repricedPrice)msgid "Repricing with today's rules and costs gives <0>{0}</0>."@@ -15221,6 +15473,12 @@ msgstr "需要维修"msgid "Requires staffing"msgstr "需要人工配置"+msgid "Reschedule tolerance"+msgstr "改期容差"++msgid "Reschedule Tolerance"+msgstr "重新安排容差"+msgid "Reserve floor"msgstr "储备下限"@@ -15279,6 +15537,12 @@ msgstr "资源"msgid "Resources"msgstr "资源"+msgid "Responsible employee"+msgstr "负责员工"++msgid "Responsible Employee"+msgstr "负责员工"+msgid "Restock"msgstr "补货"@@ -15654,6 +15918,9 @@ msgstr "运行ID"msgid "Run month-end close and standard reconciliations"msgstr "运行月末结账和标准对账"+msgid "Run MRP"+msgstr "运行MRP"+msgid "Run payment batches and track aging"msgstr "运行付款批次并跟踪账龄"@@ -16358,7 +16625,7 @@ msgid "Select operations"msgstr "选择工序"msgid "Select posted receipt lines from this supplier to return."-msgstr "选择从此供应商的已过账收货行以退货。"+msgstr "从该供应商选择已过账的收货行以退货。"msgid "Select posted shipment lines to this customer to return."msgstr "从该客户的已过账发货行中选择要退货的"@@ -16560,7 +16827,7 @@ msgid "Session locked"msgstr "会话已锁定"msgid "Set a customer on this return to add from a shipment."-msgstr "在此退货中设置客户以从发货添加。"+msgstr "在此退货上设置客户以从发货中添加。"msgid "Set a supplier on this return to add from a receipt."msgstr "为此退货指定供应商以从其收货中添加"@@ -16895,7 +17162,7 @@ msgid "Show all hidden on this step"msgstr "显示此步骤上隐藏的全部内容"msgid "Show available batch numbers"-msgstr "显示可用的生产批次号"+msgstr "显示可用批次号"msgid "Show available tracking numbers"msgstr "显示可用的跟踪号码"@@ -17243,6 +17510,9 @@ msgstr "开始"msgid "Start {0} Day Free Trial"msgstr "开始 {0} 天免费试用"+msgid "Start By"+msgstr "开始于"+msgid "Start counting"msgstr "开始盘点"@@ -17386,6 +17656,9 @@ msgstr "步骤独自构建,然后作为一个整体拼接:在使用它的步msgid "Still dark out on the floor."msgstr "车间仍在黑暗中。"+msgid "Stock Availability"+msgstr "库存可用性"+msgid "Stock movement corrected"msgstr "库存移动已修正"@@ -17624,6 +17897,15 @@ msgstr "建议匹配"msgid "Suggest with AI"msgstr "使用 AI 建议"+msgid "Suggested Jobs"+msgstr "建议工单"++msgid "Suggested Orders"+msgstr "建议订单"++msgid "Suggested orders required after this item's planning horizon. Extend the horizon to include them."+msgstr "此物料的计划周期之后需要的建议订单。延长计划周期以包含它们。"+msgid "Suggested orders you haven't placed yet."msgstr "您尚未下达的建议订单。"@@ -17874,7 +18156,7 @@ msgstr "同步"msgid "Sync Activity"msgstr "同步活动"-msgid "sync off"+msgid "Sync Off"msgstr "同步已关闭"msgid "Sync operation"@@ -18642,6 +18924,9 @@ msgstr "现金折扣的百分比。使用 0 表示无折扣。"msgid "The permission set new employees of this type receive automatically; editing here changes the template for future hires only — existing employees keep what they have unless explicitly bulk-updated."msgstr "该类型的新员工自动接收的权限集;在此处编辑仅更改模板以供将来雇用 - 现有员工保留他们拥有的内容,除非明确进行批量更新。"+msgid "The person a planning action is assigned to: the item's owner at that location, else the item group's, else the location's, else the company default."+msgstr "计划行动被分配给的个人:该地点的物料负责人,否则为物料组的负责人,否则为地点的负责人,否则为公司默认值。"+msgid "The plants, warehouses, and sites where your work and stock live"msgstr "您的工作和库存所在的工厂、仓库和场所"@@ -18663,6 +18948,9 @@ msgstr "此工作中心可以运行的工艺;在排程工序时显示在工艺msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."msgstr "提供商不提供维度目标。首先在提供商中启用该功能(例如跟踪类别、类跟踪或字段)。"+msgid "The purchase order"+msgstr ""+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "此行定价的数量断点;每一列都有自己的单位价格,用于采购方–供应商谈判和转换为下游文件。"@@ -18991,6 +19279,9 @@ msgstr "这些凭证仍是草稿,所以其借方和贷方不在此期间的账msgid "These operations use a process with multiple suppliers. Choose a supplier for each."msgstr "这些工序使用的工艺支持多个供应商。请为每个工序选择一个供应商。"+msgid "These orders could not be loaded. Close and reopen to try again."+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 "这些零件被此零件替代。每个规则都在旧零件上设置;打开它来更改规则。"@@ -19469,6 +19760,9 @@ msgstr "公差+"msgid "Tolerance (+/-)"msgstr "容差 (+/-)"+msgid "Tolerance (days)"+msgstr "容差(天)"+msgid "Tomorrow"msgstr "明天"@@ -19847,7 +20141,7 @@ msgstr "撤销"msgid "Ungroup"msgstr "取消分组"-msgid "unhealthy"+msgid "Unhealthy"msgstr "异常"msgid "Uninstall"@@ -20936,6 +21230,9 @@ msgstr "当 {name} 更改时"msgid "When a finished product's shelf life is set to Calculated, pick which consumed inputs feed the calculation."msgstr "当成品的保质期设置为计算时,选择哪些已消耗的输入项用于计算。"+msgid "When a sales order or job lands in a week with no remaining forecast, it consumes forecast from nearby weeks instead of being counted on top of it. Set both to 0 to net within the same week only."+msgstr "当销售订单或工单落在没有剩余预测的周次时,该订单或工单将从附近周次的预测中抵消,而不是累加计算。将两者都设置为 0 以仅在同一周内抵消。"+msgid "When a serial or batch expires, and what happens if used after — a company policy can Warn, Block, or BlockWithOverride."msgstr "当序列号或批次过期时,以及之后使用时会发生什么 — 公司政策可以警告、阻止或使用覆盖阻止。"@@ -21128,6 +21425,9 @@ msgstr "谁接受什么培训,采用什么形式。你的职责:尽早在你msgid "Who has to approve quotes, orders, and purchases — and when"msgstr "谁必须审批报价单、订单和采购——以及何时"+msgid "Who owns MRP planning actions. Locations inherit the company default; item groups inherit their location. The most specific assignment wins, and each item can override on its Planning tab."+msgstr "MRP计划行动的所有者。地点继承公司默认值;物料组继承其地点。最具体的分配优先,每个物料可以在其计划选项卡上覆盖。"+msgid "Who should receive notifications for maintenance-related dispatches?"msgstr "谁应该接收与维护相关的维护工单的通知?"diff --git a/packages/planning/AGENTS.md b/packages/planning/AGENTS.mdindex 0a751d9013..578718227d 100644--- a/packages/planning/AGENTS.md+++ b/packages/planning/AGENTS.md@@ -47,6 +47,20 @@ Single subpath `@carbon/planning` (`./src/index.ts`):| `resolveLocationWindows` / `resolveWorkCenterWindows` / `subtractIntervals` | Machine/work-center availability window resolvers (`src/scheduling/`) || types (`LadderShiftRow`, `MrpPayload`, `MrpResult`, `LocationScheduleResult`, `ExpediteWhatIfResult`, `NewlyLateJob`, …) | Engine type surface |+Internal to the engine, not exported: `generatePlanningActions(client, db, { companyId, userId })`+(`src/mrp/planning-actions.ts` — the planning action messages, Order / Make / Expedite / Defer /+Increase / Decrease / Cancel, diff-written to `planningAction` in one transaction that holds a+per-company `pg_advisory_xact_lock` across the read and the write; `runMrp` calls it after its+Phase-7 commit), `loadResponsibleEmployeeResolver(db, companyId)` / `resolveResponsibleEmployee(rungs)`+(`src/mrp/responsible-employee.ts` — who owns an item + location's actions: item → location item+group → location → company default, first non-null wins), `consumeForecast` (`src/mrp/forecast-consumption.ts` —+actual demand consumes the demand projection in its own week, then backward, then forward,+per the company's consumption window; the consumed amount is persisted on+`demandProjection.consumedQuantity`), and `purchaseOrderLineArrivalDate` / `jobCompletionDate`+(`src/mrp/supply-date.ts` — when an open PO line arrives: promised date, else required+date, else order date (today when unset) + lead time; when a job completes: due date, else+today + 30 for No Deadline, else today — shared by the projection and the action generator).+## Consumers- `@carbon/jobs` — `scheduled/mrp.ts` (`runMrp`), `tasks/recalculate.ts` &diff --git a/packages/planning/src/mrp/forecast-consumption.test.ts b/packages/planning/src/mrp/forecast-consumption.test.tsnew file mode 100644index 0000000000..efac338b18--- /dev/null+++ b/packages/planning/src/mrp/forecast-consumption.test.ts@@ -0,0 +1,176 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { parseDate } from "@internationalized/date";+import { describe, expect, it } from "vitest";+import {+ actualConsumesForecast,+ consumeForecast+} from "./forecast-consumption";++const WINDOW = { backwardPeriods: 4, forwardPeriods: 1 };++describe("consumeForecast", () => {+ it("nets same-bucket forecast 10 / actual 10 to remainder 0", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([[2, 10]]),+ actuals: new Map([[2, 10]]),+ window: WINDOW+ });+ expect(consumedByPeriod.get(2)).toBe(10);+ expect(remainderByPeriod.get(2)).toBe(0);+ });++ it("nets same-bucket forecast 10 / actual 5 to remainder 5 (total demand 10)", () => {+ const { remainderByPeriod } = consumeForecast({+ forecast: new Map([[2, 10]]),+ actuals: new Map([[2, 5]]),+ window: WINDOW+ });+ expect(remainderByPeriod.get(2)).toBe(5);+ });++ it("floors remainder at 0 when actuals exceed forecast (total demand 12)", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([[2, 10]]),+ actuals: new Map([[2, 12]]),+ window: WINDOW+ });+ expect(consumedByPeriod.get(2)).toBe(10);+ expect(remainderByPeriod.get(2)).toBe(0);+ });++ it("heals the gap case: forecast in weeks 2 and 4, actual in week 3 consumes week 2", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([+ [2, 10],+ [4, 10]+ ]),+ actuals: new Map([[3, 10]]),+ window: { backwardPeriods: 1, forwardPeriods: 1 }+ });+ expect(consumedByPeriod.get(2)).toBe(10);+ expect(remainderByPeriod.get(2)).toBe(0);+ expect(remainderByPeriod.get(4)).toBe(10);+ });++ it("prefers backward over forward when both are reachable", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([+ [1, 10],+ [3, 10]+ ]),+ actuals: new Map([[2, 6]]),+ window: { backwardPeriods: 1, forwardPeriods: 1 }+ });+ expect(consumedByPeriod.get(1)).toBe(6);+ expect(remainderByPeriod.get(1)).toBe(4);+ expect(remainderByPeriod.get(3)).toBe(10);+ });++ it("reaches forward when no backward forecast exists", () => {+ const { consumedByPeriod } = consumeForecast({+ forecast: new Map([[2, 10]]),+ actuals: new Map([[1, 10]]),+ window: WINDOW+ });+ expect(consumedByPeriod.get(2)).toBe(10);+ });++ it("consumes nothing when the only forecast is outside the window", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([[0, 5]]),+ actuals: new Map([[6, 10]]),+ window: WINDOW+ });+ expect(consumedByPeriod.get(0)).toBe(0);+ expect(remainderByPeriod.get(0)).toBe(5);+ });++ it("spills backward across multiple periods, nearest first", () => {+ const { remainderByPeriod } = consumeForecast({+ forecast: new Map([+ [1, 4],+ [2, 4]+ ]),+ actuals: new Map([[3, 10]]),+ window: { backwardPeriods: 2, forwardPeriods: 1 }+ });+ expect(remainderByPeriod.get(1)).toBe(0);+ expect(remainderByPeriod.get(2)).toBe(0);+ });++ it("degrades to strict per-bucket netting with a 0/0 window", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([[2, 10]]),+ actuals: new Map([+ [1, 10],+ [2, 3]+ ]),+ window: { backwardPeriods: 0, forwardPeriods: 0 }+ });+ expect(consumedByPeriod.get(2)).toBe(3);+ expect(remainderByPeriod.get(2)).toBe(7);+ });++ it("lets earlier actuals claim forecast first", () => {+ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast: new Map([[2, 10]]),+ actuals: new Map([+ [1, 8],+ [3, 8]+ ]),+ window: { backwardPeriods: 1, forwardPeriods: 1 }+ });+ // Period 1's actual reaches forward and takes 8; period 3's actual takes the last 2.+ expect(consumedByPeriod.get(2)).toBe(10);+ expect(remainderByPeriod.get(2)).toBe(0);+ });++ it("does not mutate its inputs and clamps negative forecast to 0", () => {+ const forecast = new Map([+ [2, -5],+ [3, 10]+ ]);+ const actuals = new Map([[3, 4]]);+ const { remainderByPeriod } = consumeForecast({+ forecast,+ actuals,+ window: WINDOW+ });+ expect(remainderByPeriod.get(2)).toBe(0);+ expect(remainderByPeriod.get(3)).toBe(6);+ expect(forecast.get(2)).toBe(-5);+ expect(actuals.get(3)).toBe(4);+ });+});++// An overdue order was bucketed into the first period and consumed its+// forecast: a late order for 80 against a forecast of 100 left 20 planned for+// this week's predicted customers instead of 100.+describe("actualConsumesForecast", () => {+ const weekStart = parseDate("2026-10-05");++ it("does not consume for backlog dated before the first period", () => {+ expect(actualConsumesForecast(parseDate("2026-09-14"), weekStart)).toBe(+ false+ );+ expect(actualConsumesForecast(parseDate("2026-10-04"), weekStart)).toBe(+ false+ );+ });++ it("consumes from the first period's start on, even before today", () => {+ expect(actualConsumesForecast(parseDate("2026-10-05"), weekStart)).toBe(+ true+ );+ expect(actualConsumesForecast(parseDate("2026-11-30"), weekStart)).toBe(+ true+ );+ });++ it("consumes for an undated actual, which is due now", () => {+ expect(actualConsumesForecast(null, weekStart)).toBe(true);+ });+});diff --git a/packages/planning/src/mrp/forecast-consumption.ts b/packages/planning/src/mrp/forecast-consumption.tsnew file mode 100644index 0000000000..9eee5ae43a--- /dev/null+++ b/packages/planning/src/mrp/forecast-consumption.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { CalendarDate } from "@internationalized/date";++export type ConsumptionWindow = {+ /** How many periods BEFORE the actual's period may be consumed (0 = own period only). */+ backwardPeriods: number;+ /** How many periods AFTER the actual's period may be consumed. */+ forwardPeriods: number;+};++export type ConsumptionResult = {+ /** periodIndex -> quantity consumed from that period's forecast (0 ≤ consumed ≤ forecast). */+ consumedByPeriod: Map<number, number>;+ /** periodIndex -> forecast − consumed, floored at 0. Every input forecast period has an entry. */+ remainderByPeriod: Map<number, number>;+};++/**+ * Forecast consumption: actual demand consumes the authored forecast so the two+ * never double-count. Each actual consumes its own period's forecast first, then+ * searches backward (nearest first) up to `backwardPeriods`, then forward up to+ * `forwardPeriods`. Backward-before-forward is the industry consensus (SAP+ * consumption mode 2, Oracle, SyteLine): an order landing "late" relative to a+ * forecast bucket was almost certainly part of the just-passed forecast.+ *+ * Actual quantity beyond the reachable forecast consumes nothing further — it+ * simply stands as real demand (the caller adds actuals in full; only the+ * forecast remainder is what this function decides).+ */+export function consumeForecast(args: {+ /** periodIndex -> authored forecast quantity (entries may be 0; negative treated as 0). */+ forecast: Map<number, number>;+ /** periodIndex -> total consuming actual quantity (SO quantityToConsume + job-material quantityToIssue). */+ actuals: Map<number, number>;+ window: ConsumptionWindow;+}): ConsumptionResult {+ const { forecast, actuals, window } = args;++ const remaining = new Map<number, number>();+ const consumedByPeriod = new Map<number, number>();+ for (const [periodIndex, quantity] of forecast) {+ remaining.set(periodIndex, Math.max(quantity, 0));+ consumedByPeriod.set(periodIndex, 0);+ }++ const actualIndices = [...actuals.keys()].sort((a, b) => a - b);+ for (const periodIndex of actualIndices) {+ let quantity = actuals.get(periodIndex) ?? 0;+ if (quantity <= 0) continue;++ const candidates: number[] = [periodIndex];+ for (let back = 1; back <= window.backwardPeriods; back++) {+ const candidate = periodIndex - back;+ if (candidate < 0) break;+ candidates.push(candidate);+ }+ for (let forward = 1; forward <= window.forwardPeriods; forward++) {+ candidates.push(periodIndex + forward);+ }++ for (const candidate of candidates) {+ if (quantity <= 0) break;+ const available = remaining.get(candidate) ?? 0;+ if (available <= 0) continue;+ const take = Math.min(quantity, available);+ remaining.set(candidate, available - take);+ consumedByPeriod.set(+ candidate,+ (consumedByPeriod.get(candidate) ?? 0) + take+ );+ quantity -= take;+ }+ }++ const remainderByPeriod = new Map<number, number>();+ for (const [periodIndex] of consumedByPeriod) {+ remainderByPeriod.set(periodIndex, remaining.get(periodIndex) ?? 0);+ }++ return { consumedByPeriod, remainderByPeriod };+}++/**+ * Whether an actual consumes forecast. An actual dated before the first+ * planning period is backlog: the forecast that predicted it was for a week+ * that is gone. MRP still plans it as demand in the first period, but it must+ * not consume that period's forecast, or this week's predicted customers go+ * unplanned. An undated actual counts as due now and consumes.+ */+export function actualConsumesForecast(+ date: CalendarDate | null,+ firstPeriodStart: CalendarDate+): boolean {+ return !date || date.compare(firstPeriodStart) >= 0;+}diff --git a/packages/planning/src/mrp/mrp.ts b/packages/planning/src/mrp/mrp.tsindex 62124d2b93..a735756614 100644--- a/packages/planning/src/mrp/mrp.ts+++ b/packages/planning/src/mrp/mrp.ts@@ -24,16 +24,25 @@ import {type Redirect} from "@carbon/database/supersession-pick";import { getLogger } from "@carbon/logger";-import { datetime } from "@carbon/utils";+import { datetime, round } from "@carbon/utils";import {type CalendarDate,parseDate,startOfWeek} from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";-import type { Kysely } from "kysely";+import { type Kysely, sql } from "kysely";import { z } from "zod";import { toIsoDate } from "../scheduling/date-utils.ts";+import {+ actualConsumesForecast,+ consumeForecast+} from "./forecast-consumption.ts";+import { generatePlanningActions } from "./planning-actions.ts";+import {+ jobCompletionDate,+ purchaseOrderLineArrivalDate+} from "./supply-date.ts";const logger = getLogger("planning", "mrp");@@ -189,6 +198,25 @@ export async function runMrp(if (demandProjections.error)throw new Error("Failed to load demand projections");+ // Forecast-consumption window (weekly periods): how far an actual reaches+ // to consume forecast beyond its own week — backward first, then forward.+ const consumptionSettings = await client+ .from("companySettings")+ .select(+ "forecastConsumptionBackwardPeriods, forecastConsumptionForwardPeriods"+ )+ .eq("id", companyId)+ .maybeSingle();+ // No fallback to the defaults on a failed read: the window decides how much+ // forecast is consumed, and that result is persisted for every read path.+ if (consumptionSettings.error) throw consumptionSettings.error;+ const consumptionWindow = {+ backwardPeriods:+ consumptionSettings.data?.forecastConsumptionBackwardPeriods ?? 4,+ forwardPeriods:+ consumptionSettings.data?.forecastConsumptionForwardPeriods ?? 1+ };+// Bulk-load item metadataconst [allItems, allReplenishments] = await Promise.all([db@@ -378,11 +406,7 @@ export async function runMrp(// supplyActual_locationId_fkey and aborting the whole run. Skip it.if (!line.itemId || !line.quantityToReceive || !line.locationId) continue;- const dueDate = line.dueDate- ? parseDate(line.dueDate)- : line.deadlineType === "No Deadline"- ? today.add({ days: 30 })- : today;+ const dueDate = parseDate(jobCompletionDate(line, today.toString()));const period = findPeriod(dueDate, today, periods);if (!period) continue;@@ -406,11 +430,11 @@ export async function runMrp(// supplyActual with locationId="" and violate its FK.if (!line.itemId || !line.quantityToReceive || !line.locationId) continue;- const dueDate = line.promisedDate- ? parseDate(line.promisedDate)- : line.orderDate- ? parseDate(line.orderDate).add({ days: line.leadTime ?? 7 })- : today.add({ days: line.leadTime ?? 7 });+ // Same date the reschedule check walks (supply-date.ts) — the projection+ // and the Expedite / Defer verdicts must see one arrival date per line.+ const dueDate = parseDate(+ purchaseOrderLineArrivalDate(line, today.toString())+ );const period = findPeriod(dueDate, today, periods);if (!period) continue;@@ -446,52 +470,52 @@ export async function runMrp(type DemandForecastSourceInsert =Database["public"]["Tables"]["demandForecastSource"]["Insert"];- // Demand projections. Do NOT net firm job/PO supply here — supply is- // credited exactly once by explodeBom's running balance (which receives- // jobAndPoSupplyByLocationPeriodItem below). Netting here as well would- // double-count supply and under-drive child demand.- for (const projection of demandProjections.data ?? []) {- // locationId is part of the demandForecast primary key (hence NOT NULL)- // and an FK to location; a null one would write locationId="" and violate- // demandForecast_locationId_fkey, aborting the run.- if (- !projection.itemId ||- !projection.forecastQuantity ||- !projection.locationId- )- continue;-- const netDemand = projection.forecastQuantity;-- if (netDemand > 0) {- const key = makeKey(- projection.locationId ?? "",- projection.periodId,- projection.itemId- );- grossDemand.set(key, (grossDemand.get(key) ?? 0) + netDemand);-- // Seed top-level contributor for this projection. Use the projection's- // surrogate id (added in 20260527115843_demand-projection-source.sql).- const projectionId = projection.id;- if (projectionId && projection.itemId) {- const contributors = topLevelContributors.get(key) ?? [];- contributors.push({- sourceType: "Demand Projection",- demandProjectionId: projectionId,- parentItemId: projection.itemId,- quantity: netDemand- });- topLevelContributors.set(key, contributors);- }- }- }+ // Forecast-consumption prelude. The projections loop moved BELOW the two+ // actual-demand loops so their quantities can consume the forecast before+ // it enters gross demand. Actuals consume at their own period first, then+ // backward/forward per the company window (consumeForecast).+ const periodIndexById = new Map<string, number>();+ periods.forEach((p: DemandPeriod, index: number) => {+ if (p.id) periodIndexById.set(p.id, index);+ });+ // locationId␟itemId (makeLocationItemKey) -> periodIndex -> consuming qty+ const consumptionActuals = new Map<string, Map<number, number>>();+ // Actuals dated before this are backlog and consume no forecast.+ const firstPeriodStart = periods[0]?.startDate ?? today;+ const addConsumption = (+ locationId: string,+ itemId: string,+ periodId: string,+ quantity: number+ ) => {+ const periodIndex = periodIndexById.get(periodId);+ if (periodIndex === undefined || quantity <= 0) return;+ const key = makeLocationItemKey(locationId, itemId);+ const byPeriod = consumptionActuals.get(key) ?? new Map<number, number>();+ byPeriod.set(periodIndex, (byPeriod.get(periodIndex) ?? 0) + quantity);+ consumptionActuals.set(key, byPeriod);+ };+ // Persisted in Phase 7 for EVERY loaded projection row (0 included, so a+ // stale consumedQuantity from a prior run is always overwritten).+ const consumptionUpdates: Array<{+ itemId: string;+ locationId: string;+ periodId: string;+ consumedQuantity: number;+ }> = [];// Sales order linesfor (const line of salesOrderLines.data ?? []) {// A null locationId would write demandForecast/demandActual with// locationId="" and violate their locationId FK — skip (see above).- if (!line.itemId || !line.quantityToSend || !line.locationId) continue;+ // quantityToConsume is the line's PRE-job-dedup open quantity: an MTO+ // line fully covered by its linked job has quantityToSend 0 but must+ // still consume the forecast that predicted it — otherwise the forecast+ // remainder drives phantom stock production on top of the job.+ const quantityToSend = line.quantityToSend ?? 0;+ const quantityToConsume = line.quantityToConsume ?? 0;+ if (!line.itemId || !line.locationId) continue;+ if (quantityToSend <= 0 && quantityToConsume <= 0) continue;const promiseDate = line.promisedDate? parseDate(line.promisedDate)@@ -499,8 +523,18 @@ export async function runMrp(const period = findPeriod(promiseDate, today, periods);if (!period) continue;+ if (actualConsumesForecast(promiseDate, firstPeriodStart)) {+ addConsumption(+ line.locationId,+ line.itemId,+ period.id,+ quantityToConsume+ );+ }+ if (quantityToSend <= 0) continue;+const key = makeKey(line.locationId ?? "", period.id ?? "", line.itemId);- grossDemand.set(key, (grossDemand.get(key) ?? 0) + line.quantityToSend);+ grossDemand.set(key, (grossDemand.get(key) ?? 0) + quantityToSend);const actualKey = makeActualKey(line.itemId,@@ -510,7 +544,7 @@ export async function runMrp();salesDemandByKey.set(actualKey,- (salesDemandByKey.get(actualKey) ?? 0) + line.quantityToSend+ (salesDemandByKey.get(actualKey) ?? 0) + quantityToSend);if (line.id && line.itemId) {@@ -519,7 +553,7 @@ export async function runMrp(sourceType: "Sales Order",salesOrderLineId: line.id,parentItemId: line.itemId,- quantity: line.quantityToSend+ quantity: quantityToSend});topLevelContributors.set(key, contributors);}@@ -536,6 +570,19 @@ export async function runMrp(const period = findPeriod(requiredDate, today, periods);if (!period) continue;+ // Real dependent demand consumes component-level forecast too. Backlog+ // is judged on the job's due date, not the lead-time-shifted required+ // date: a job due this week whose material should have been ordered+ // last week is this week's demand.+ if (actualConsumesForecast(dueDate, firstPeriodStart)) {+ addConsumption(+ line.locationId,+ line.itemId,+ period.id,+ line.quantityToIssue+ );+ }+const key = makeKey(line.locationId ?? "", period.id ?? "", line.itemId);grossDemand.set(key, (grossDemand.get(key) ?? 0) + line.quantityToIssue);@@ -563,6 +610,89 @@ export async function runMrp(}}+ // Demand projections, net of forecast consumption. Do NOT net firm job/PO+ // supply here — supply is credited exactly once by explodeBom's running+ // balance (which receives jobAndPoSupplyByLocationPeriodItem below);+ // netting it here as well would double-count supply and under-drive child+ // demand. Consumption is a different reconciliation: the actual DEMAND+ // accumulated above consumes the forecast (own period, then backward/+ // forward per the company window), so forecast and actuals never+ // double-count. Only the unconsumed remainder enters gross demand.+ // Consumption runs BEFORE the Phase 4.5 supersession redirect on purpose:+ // the read paths (planning RPCs) do not redirect projections/actuals+ // either, so netting on authored identity keeps engine and grid agreeing.+ const projectionsByLocationItem = new Map<+ string,+ Array<Database["public"]["Tables"]["demandProjection"]["Row"]>+ >();+ for (const projection of demandProjections.data ?? []) {+ // locationId is part of the demandForecast primary key (hence NOT NULL)+ // and an FK to location; a null one would write locationId="" and violate+ // demandForecast_locationId_fkey, aborting the run.+ if (!projection.itemId || !projection.locationId) continue;+ const locationItemKey = makeLocationItemKey(+ projection.locationId,+ projection.itemId+ );+ const rows = projectionsByLocationItem.get(locationItemKey) ?? [];+ rows.push(projection);+ projectionsByLocationItem.set(locationItemKey, rows);+ }++ for (const [locationItemKey, rows] of projectionsByLocationItem) {+ const forecast = new Map<number, number>();+ for (const projection of rows) {+ const periodIndex = periodIndexById.get(projection.periodId);+ if (periodIndex === undefined) continue;+ forecast.set(+ periodIndex,+ (forecast.get(periodIndex) ?? 0) + (projection.forecastQuantity ?? 0)+ );+ }++ const { consumedByPeriod, remainderByPeriod } = consumeForecast({+ forecast,+ actuals: consumptionActuals.get(locationItemKey) ?? new Map(),+ window: consumptionWindow+ });++ for (const projection of rows) {+ const { itemId, locationId, periodId } = projection;+ if (!itemId || !locationId) continue;+ const periodIndex = periodIndexById.get(periodId);+ if (periodIndex === undefined) continue;++ consumptionUpdates.push({+ itemId,+ locationId,+ periodId,+ consumedQuantity: round(consumedByPeriod.get(periodIndex) ?? 0)+ });++ // Round at the compare: the consumed side is a float sum, so an+ // exactly-consumed forecast can leave a ~1e-16 remainder.+ const remainder = round(remainderByPeriod.get(periodIndex) ?? 0);+ if (remainder <= 0) continue;++ const key = makeKey(locationId, periodId, itemId);+ grossDemand.set(key, (grossDemand.get(key) ?? 0) + remainder);++ // Seed top-level contributor for this projection. Use the projection's+ // surrogate id (added in 20260527110002_demand-forecast-source.sql).+ const projectionId = projection.id;+ if (projectionId) {+ const contributors = topLevelContributors.get(key) ?? [];+ contributors.push({+ sourceType: "Demand Projection",+ demandProjectionId: projectionId,+ parentItemId: itemId,+ quantity: remainder+ });+ topLevelContributors.set(key, contributors);+ }+ }+ }+// ──────────────────────────────────────────────────────────────// PHASE 4.5: Supersession demand redirection// ──────────────────────────────────────────────────────────────@@ -1116,8 +1246,41 @@ export async function runMrp().execute();}++ // Persist forecast consumption in batches — an UPDATE, not an upsert,+ // so a projection deleted mid-run can never be resurrected by the+ // write phase. Every loaded projection has a row here (0 included),+ // so stale consumption from a prior run is always overwritten.+ // Consumption is derived data, not an edit: the row's updatedAt /+ // updatedBy stay with the planner who entered the forecast, and a row+ // whose consumption did not change is not written at all.+ for (let i = 0; i < consumptionUpdates.length; i += BATCH_SIZE) {+ const batch = consumptionUpdates.slice(i, i + BATCH_SIZE);+ await sql`+ UPDATE "demandProjection" AS dp+ SET "consumedQuantity" = v."consumedQuantity"::numeric+ FROM (VALUES ${sql.join(+ batch.map(+ (r) =>+ sql`(${r.itemId}, ${r.locationId}, ${r.periodId}, ${r.consumedQuantity})`+ )+ )}) AS v("itemId", "locationId", "periodId", "consumedQuantity")+ WHERE dp."itemId" = v."itemId"+ AND dp."locationId" = v."locationId"+ AND dp."periodId" = v."periodId"+ AND dp."companyId" = ${companyId}+ AND dp."consumedQuantity" IS DISTINCT FROM v."consumedQuantity"::numeric+ `.execute(trx);+ }});+ // Persist the planning action messages (spec §P1) in their own atomic+ // transaction AFTER the forecast/actual write commits — the planning+ // RPCs it reads see only committed data. Errors PROPAGATE: the run must+ // not report success with stale actions (forecasts are committed and+ // correct; actions self-heal on the next successful run).+ await generatePlanningActions(client, db, { companyId, userId });+return { success: true };} catch (err) {logger.error("write phase failed", { companyId, error: String(err) });diff --git a/packages/planning/src/mrp/planning-actions.test.ts b/packages/planning/src/mrp/planning-actions.test.tsnew file mode 100644index 0000000000..9058f48000--- /dev/null+++ b/packages/planning/src/mrp/planning-actions.test.ts@@ -0,0 +1,1451 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { computePlanningOrders } from "@carbon/utils";+import { describe, expect, it } from "vitest";+import type {+ ExistingPlanningAction,+ PlanningActionCandidate+} from "./planning-actions";+import {+ convertOrdersToIncreases,+ daysBetween,+ deriveChangeActions,+ deriveReleaseActions,+ diffPlanningActions,+ earlierDate,+ earlierRelease,+ firstNeedPeriodByOrder,+ isCommittedJobStatus,+ isCommittedPurchaseOrderStatus,+ keyPeriodFor,+ naturalKey,+ projectionsWithExpedites,+ releaseByDate+} from "./planning-actions";++const PERIODS = [+ { id: "p1", startDate: "2026-10-05" },+ { id: "p2", startDate: "2026-10-12" },+ { id: "p3", startDate: "2026-10-19" },+ { id: "p4", startDate: "2026-10-26" },+ { id: "p5", startDate: "2026-11-02" }+];++const TODAY = "2026-09-11";+const TOLERANCE = 7;++const base = {+ periods: PERIODS,+ policyFloor: 0,+ toleranceDays: TOLERANCE,+ todayDate: TODAY+};++describe("daysBetween", () => {+ it("returns the signed day difference (pins CalendarDate.compare semantics)", () => {+ expect(daysBetween("2026-10-12", "2026-10-05")).toBe(7);+ expect(daysBetween("2026-10-05", "2026-10-12")).toBe(-7);+ expect(daysBetween("2026-10-05", "2026-10-05")).toBe(0);+ });+});++describe("earlierDate", () => {+ it("returns the earlier of two ISO dates, either way round", () => {+ expect(earlierDate("2026-10-05", "2026-10-26")).toBe("2026-10-05");+ expect(earlierDate("2026-10-26", "2026-10-05")).toBe("2026-10-05");+ expect(earlierDate("2026-10-05", "2026-10-05")).toBe("2026-10-05");+ });+});++describe("commitment gates", () => {+ it("PO: Draft and Planned are NOT committed; sent statuses are", () => {+ expect(isCommittedPurchaseOrderStatus("Draft")).toBe(false);+ expect(isCommittedPurchaseOrderStatus("Planned")).toBe(false);+ for (const status of [+ "To Receive",+ "To Receive and Invoice",+ "To Invoice",+ "Completed",+ "Closed"+ ] as const) {+ expect(isCommittedPurchaseOrderStatus(status)).toBe(true);+ }+ });++ it("job: Ready and later are committed; Draft/Planned are not", () => {+ expect(isCommittedJobStatus("Draft")).toBe(false);+ expect(isCommittedJobStatus("Planned")).toBe(false);+ expect(isCommittedJobStatus("Ready")).toBe(true);+ expect(isCommittedJobStatus("In Progress")).toBe(true);+ expect(isCommittedJobStatus("Paused")).toBe(true);+ });+});++describe("deriveChangeActions", () => {+ it("raises Expedite when an open PO lands more than the tolerance after its requirement", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-26", // 21 days after the need+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Expedite",+ purchaseOrderLineId: "pol-1",+ suggestedDate: "2026-10-05",+ // inside a fence from the day it is NEEDED, not the day it lands+ horizonDate: "2026-10-05",+ latestOrderDate: null,+ periodId: "p1",+ suggestedQuantity: 10+ });+ });++ it("suppresses a date gap at exactly the tolerance and fires at tolerance + 1 (strict >)", () => {+ const make = (dueDate: string) =>+ deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 5 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 5,+ dueDate,+ requiresManualAction: false+ }+ ]+ });++ // gap of exactly 7 days → no message+ expect(make("2026-10-12")).toEqual([]);+ // gap of 8 days → Expedite+ expect(make("2026-10-13").map((a) => a.type)).toEqual(["Expedite"]);+ });++ it("raises Defer when an order lands more than the tolerance before its requirement", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [{ periodId: "p4", startDate: "2026-10-26", quantity: 5 }],+ openOrders: [+ {+ jobId: "job-1",+ quantity: 5,+ dueDate: "2026-10-05", // 21 days early+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Defer",+ jobId: "job-1",+ suggestedDate: "2026-10-26",+ // inside a fence from where the order sits TODAY — deferring it is a+ // near-term decision even though the requirement is weeks out+ horizonDate: "2026-10-05",+ latestOrderDate: null,+ periodId: "p4"+ });+ });++ it("gives no verdict on an order due after the last planning week", () => {+ // PERIODS ends with the week of 2026-11-02. Demand beyond it is not+ // loaded, so an order out there is not "unneeded" — it is unjudged.+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [],+ openOrders: [+ {+ purchaseOrderLineId: "pol-far",+ quantity: 25,+ dueDate: "2026-11-09", // first day past the horizon+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toEqual([]);+ });++ it("still judges an order due on the last day of the last planning week", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [],+ openOrders: [+ {+ purchaseOrderLineId: "pol-edge",+ quantity: 25,+ dueDate: "2026-11-08",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toMatchObject([+ { type: "Cancel", purchaseOrderLineId: "pol-edge" }+ ]);+ });++ it("does not pull an order from beyond the horizon in to cover an earlier need", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-far",+ quantity: 10,+ dueDate: "2026-12-14",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toEqual([]);+ });++ it("raises Cancel for an order with no remaining requirement", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 100, // on-hand covers all demand+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 25,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Cancel",+ purchaseOrderLineId: "pol-1",+ suggestedQuantity: 25+ });+ });++ it("raises Decrease for the unneeded tail of a partially required order", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [{ periodId: "p2", startDate: "2026-10-12", quantity: 6 }],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-12", // on time → no date action+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Decrease",+ suggestedQuantity: 6 // decrease TO the required amount+ });+ });++ it("does not raise Decrease when fractional demand consumes the order exactly", () => {+ // 0.7 + 0.1 is 0.7999999999999999 in floats; the raw leftover would be+ // ~1e-16 and read as an unneeded tail of a fully required order.+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 0.7 },+ { periodId: "p2", startDate: "2026-10-12", quantity: 0.1 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 0.8,+ dueDate: "2026-10-05", // on time → no date action+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toEqual([]);+ });++ it("emits exactly ONE action per target — a date problem beats a quantity problem", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [{ periodId: "p1", startDate: "2026-10-05", quantity: 6 }],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10, // wrong qty AND+ dueDate: "2026-10-26", // wrong date (21 days late)+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]?.type).toBe("Expedite");+ });++ it("never cancels stock held for the policy floor (safety stock)", () => {+ const actions = deriveChangeActions({+ ...base,+ policyFloor: 25, // safety stock justifies the order+ onHand: 0,+ demandPeriods: [],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 25,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toEqual([]);+ });++ // The floor used to take what the demand walk left, undated: an order+ // holding safety stock was dated by a later demand and offered a Defer, and+ // applying it put stock under the floor until that date.+ it("never defers an order that holds the policy floor", () => {+ const actions = deriveChangeActions({+ ...base,+ policyFloor: 10,+ onHand: 0,+ demandPeriods: [+ { periodId: "p5", startDate: "2026-11-02", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 20,+ dueDate: "2026-10-05",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toEqual([]);+ });++ it("holds the floor with the earliest order and defers the later one", () => {+ const actions = deriveChangeActions({+ ...base,+ policyFloor: 10,+ onHand: 0,+ demandPeriods: [+ { periodId: "p5", startDate: "2026-11-02", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-b",+ quantity: 10,+ dueDate: "2026-10-12",+ requiresManualAction: false+ },+ {+ purchaseOrderLineId: "pol-a",+ quantity: 10,+ dueDate: "2026-10-05",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Defer",+ purchaseOrderLineId: "pol-b",+ suggestedDate: "2026-11-02"+ });+ });++ it("carries requiresManualAction from the committed target", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 100,+ demandPeriods: [],+ openOrders: [+ {+ purchaseOrderLineId: "pol-sent",+ quantity: 10,+ dueDate: "2026-10-12",+ requiresManualAction: true+ }+ ]+ });+ expect(actions[0]).toMatchObject({+ type: "Cancel",+ requiresManualAction: true+ });+ });++ // An overdue order arrives today at the earliest. Measured from its old due+ // date it read as early and was offered a Defer to a date already past.+ it("raises nothing for an overdue order that is needed now", () => {+ const actions = deriveChangeActions({+ ...base,+ todayDate: "2026-10-07",+ onHand: 0,+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-09-23", // two weeks late+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toEqual([]);+ });++ it("measures an overdue order's Defer from today, never to a past date", () => {+ const actions = deriveChangeActions({+ ...base,+ todayDate: "2026-10-07",+ onHand: 0,+ demandPeriods: [+ { periodId: "p4", startDate: "2026-10-26", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-09-23",+ requiresManualAction: false+ }+ ]+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Defer",+ suggestedDate: "2026-10-26",+ reason: "Not needed until 19 days after its current date"+ });+ });++ // Apply moves a PO line's required date; a supplier's promised date+ // outranks it, so applying a date change there moved nothing and the same+ // action came back every run.+ it("sends a date change on a promised line to the PO for review", () => {+ const promised = (dueDate: string, needStart: string, periodId: string) =>+ deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [{ periodId, startDate: needStart, quantity: 10 }],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate,+ requiresManualAction: false,+ dateIsPromised: true+ }+ ]+ });++ expect(promised("2026-10-26", "2026-10-05", "p1")[0]).toMatchObject({+ type: "Expedite",+ requiresManualAction: true+ });+ expect(promised("2026-10-05", "2026-10-26", "p4")[0]).toMatchObject({+ type: "Defer",+ requiresManualAction: true+ });+ });++ it("still lets a promised line's quantity be changed", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 100,+ demandPeriods: [+ { periodId: "p1", startDate: "2026-10-05", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-05",+ requiresManualAction: false,+ dateIsPromised: true+ }+ ]+ });+ expect(actions[0]).toMatchObject({+ type: "Cancel",+ requiresManualAction: false+ });+ });++ // Apply changes a PO line in whole PURCHASE units (it writes+ // round(suggested / conversionFactor, Up)). A Decrease to 55 on a line+ // bought in tens became 60, and the next run offered "Decrease to 55" again.+ describe("on a purchase order line, quantities are whole purchase units", () => {+ const decrease = (order: {+ quantity: number;+ conversionFactor?: number;+ need: number;+ }) =>+ deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [+ { periodId: "p2", startDate: "2026-10-12", quantity: order.need }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: order.quantity,+ conversionFactor: order.conversionFactor,+ dueDate: "2026-10-12", // on time → no date action+ requiresManualAction: false+ }+ ]+ });++ it("decreases to the next whole purchase unit above the requirement", () => {+ const actions = decrease({+ quantity: 100,+ conversionFactor: 10,+ need: 55+ });+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Decrease",+ suggestedQuantity: 60+ });+ });++ it("raises nothing once the line is already at that whole purchase unit", () => {+ expect(+ decrease({ quantity: 60, conversionFactor: 10, need: 55 })+ ).toEqual([]);+ });++ it("raises nothing for a fractional requirement a whole unit already covers", () => {+ expect(+ decrease({ quantity: 13, conversionFactor: 1, need: 12.5 })+ ).toEqual([]);+ // a line with no factor is bought one for one+ expect(decrease({ quantity: 13, need: 12.5 })).toEqual([]);+ });++ it("leaves a job's quantity unrounded", () => {+ const actions = deriveChangeActions({+ ...base,+ onHand: 0,+ demandPeriods: [+ { periodId: "p2", startDate: "2026-10-12", quantity: 12.5 }+ ],+ openOrders: [+ {+ jobId: "job-1",+ quantity: 13,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ]+ });+ expect(actions[0]).toMatchObject({+ type: "Decrease",+ suggestedQuantity: 12.5+ });+ });+ });++ // MRP's weeks start on Sunday; most days, that is before today. Apply+ // writes an Expedite's date onto the order, so an Expedite to the week+ // start put the order "overdue", it read as arriving today, four days after+ // the week start it was measured against, and the same Expedite came back+ // every run.+ describe("an Expedite never asks for a date before today", () => {+ const weeks = [+ { id: "w1", startDate: "2026-10-04" }, // Sunday+ { id: "w2", startDate: "2026-10-11" },+ { id: "w3", startDate: "2026-10-18" },+ { id: "w4", startDate: "2026-10-25" },+ { id: "w5", startDate: "2026-11-01" }+ ];+ const thursday = "2026-10-08";+ const expedite = (dueDate: string) =>+ deriveChangeActions({+ periods: weeks,+ policyFloor: 0,+ toleranceDays: 2,+ todayDate: thursday,+ onHand: 0,+ demandPeriods: [+ { periodId: "w1", startDate: "2026-10-04", quantity: 10 }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate,+ requiresManualAction: false+ }+ ]+ });++ it("raises nothing for a line already moved to this week's start", () => {+ expect(expedite("2026-10-04")).toEqual([]);+ });++ it("raises nothing for a line already due today", () => {+ expect(expedite(thursday)).toEqual([]);+ });++ it("expedites a later line to today, not to the week start", () => {+ const actions = expedite("2026-11-01");+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: "Expedite",+ periodId: "w1",+ suggestedDate: thursday,+ horizonDate: thursday,+ isASAP: true,+ reason: "Needed 24 days earlier than its current date"+ });+ });+ });+});++describe("convertOrdersToIncreases", () => {+ const orderCandidate = {+ type: "Order" as const,+ periodId: "p2",+ suggestedQuantity: 5,+ suggestedDate: "2026-10-12",+ horizonDate: "2026-10-12",+ latestOrderDate: "2026-10-07",+ isASAP: false,+ purchaseOrderLineId: null,+ jobId: null,+ requiresManualAction: false,+ supplierId: "sup-1",+ policyName: "Demand-Based Reorder",+ reason: null,+ triggerValues: null+ };++ it("folds a new-order suggestion into a same-window open PO as one Increase", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [orderCandidate],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ],+ changeActions: [],+ toleranceDays: TOLERANCE,+ todayDate: TODAY+ });+ expect(action).toMatchObject({+ type: "Increase",+ purchaseOrderLineId: "pol-1",+ suggestedQuantity: 15 // existing 10 + shortfall 5+ });+ });++ it("an Increase keeps the order-by date and takes the earlier fence date", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [orderCandidate],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-09", // 3 days before the suggestion, inside tolerance+ requiresManualAction: false+ }+ ],+ changeActions: [],+ toleranceDays: TOLERANCE,+ todayDate: TODAY+ });+ expect(action).toMatchObject({+ type: "Increase",+ horizonDate: "2026-10-09",+ latestOrderDate: "2026-10-07"+ });+ });++ it("keeps the Order when the open PO already carries a date action (one action per target)", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [orderCandidate],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ],+ changeActions: [+ {+ type: "Expedite",+ periodId: "p1",+ suggestedQuantity: 10,+ suggestedDate: "2026-10-05",+ horizonDate: "2026-10-05",+ latestOrderDate: null,+ isASAP: false,+ purchaseOrderLineId: "pol-1",+ jobId: null,+ requiresManualAction: false,+ supplierId: null,+ policyName: null,+ reason: null,+ triggerValues: null+ }+ ],+ toleranceDays: TOLERANCE,+ todayDate: TODAY+ });+ expect(action?.type).toBe("Order");+ });++ it("never folds a Make suggestion into a purchase order", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [{ ...orderCandidate, type: "Make" as const }],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ],+ changeActions: [],+ toleranceDays: TOLERANCE,+ todayDate: TODAY+ });+ expect(action?.type).toBe("Make");+ });++ // The Increase is a change to THAT line, on that line's PO; the item's+ // preferred supplier may not be the one it was bought from.+ it("names the purchase order line's supplier, not the item's preferred one", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [orderCandidate],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-12",+ requiresManualAction: false,+ supplierId: "sup-on-po"+ }+ ],+ changeActions: [],+ toleranceDays: TOLERANCE,+ todayDate: TODAY+ });+ expect(action).toMatchObject({+ type: "Increase",+ supplierId: "sup-on-po"+ });+ });++ it("sizes an Increase on a purchase order line in whole purchase units", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [orderCandidate],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 60,+ conversionFactor: 10,+ dueDate: "2026-10-12",+ requiresManualAction: false+ }+ ],+ changeActions: [],+ toleranceDays: TOLERANCE,+ todayDate: TODAY+ });+ // 60 + 5 is 6.5 purchase units; Apply writes 7+ expect(action).toMatchObject({ type: "Increase", suggestedQuantity: 70 });+ });++ // This week's suggestion is due on the week's Sunday; an order expedited+ // to today is the same week's supply, whatever the tolerance.+ it("folds this week's suggestion into an order due today", () => {+ const [action] = convertOrdersToIncreases({+ sizingCandidates: [+ {+ ...orderCandidate,+ suggestedDate: "2026-10-04", // Sunday, the week start+ horizonDate: "2026-10-04"+ }+ ],+ openOrders: [+ {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-08", // today, a Thursday+ requiresManualAction: false+ }+ ],+ changeActions: [],+ toleranceDays: 2,+ todayDate: "2026-10-08"+ });+ expect(action).toMatchObject({+ type: "Increase",+ purchaseOrderLineId: "pol-1"+ });+ });+});++describe("diffPlanningActions", () => {+ const candidate: PlanningActionCandidate = {+ itemId: "item-1",+ locationId: "loc-1",+ periodId: "p1",+ type: "Order",+ suggestedQuantity: 10,+ suggestedDate: "2026-10-05",+ horizonDate: "2026-10-05",+ latestOrderDate: "2026-09-30",+ isASAP: false,+ purchaseOrderLineId: null,+ jobId: null,+ requiresManualAction: false,+ supplierId: "sup-1",+ policyName: "Demand-Based Reorder",+ reason: null,+ triggerValues: { safetyStock: 10 },+ assignee: "buyer-1"+ };++ const existing: ExistingPlanningAction = {+ id: "pla-1",+ itemId: "item-1",+ locationId: "loc-1",+ periodId: "p1",+ type: "Order",+ status: "Open",+ suggestedQuantity: 10,+ suggestedDate: "2026-10-05",+ horizonDate: "2026-10-05",+ latestOrderDate: "2026-09-30",+ isASAP: false,+ purchaseOrderLineId: null,+ jobId: null,+ requiresManualAction: false,+ supplierId: "sup-1",+ policyName: "Demand-Based Reorder",+ reason: null,+ triggerValues: { safetyStock: 10 },+ assignee: "buyer-1",+ assigneeOverridden: false+ };++ it("two identical runs produce zero changes (idempotency)", () => {+ const diff = diffPlanningActions({+ existing: [existing],+ candidates: [candidate],+ toleranceDays: TOLERANCE+ });+ expect(diff).toEqual({ inserts: [], updates: [], deleteIds: [] });+ });++ it("triggerValues equality ignores jsonb key order (idempotency)", () => {+ // jsonb returns keys length-then-bytewise; the candidate builds them in+ // insertion order — identical values must not produce an update.+ const diff = diffPlanningActions({+ existing: [+ {+ ...existing,+ triggerValues: { reorderPoint: 5, leadTime: 14, projectedStock: 2 }+ }+ ],+ candidates: [+ {+ ...candidate,+ triggerValues: { projectedStock: 2, reorderPoint: 5, leadTime: 14 }+ }+ ],+ toleranceDays: TOLERANCE+ });+ expect(diff).toEqual({ inserts: [], updates: [], deleteIds: [] });+ });++ it("triggerValues equality still detects a changed value", () => {+ const diff = diffPlanningActions({+ existing: [{ ...existing, triggerValues: { safetyStock: 10 } }],+ candidates: [{ ...candidate, triggerValues: { safetyStock: 12 } }],+ toleranceDays: TOLERANCE+ });+ expect(diff.updates).toEqual([+ { id: "pla-1", patch: { triggerValues: { safetyStock: 12 } } }+ ]);+ });++ it("inserts a new candidate, deletes a vanished row", () => {+ const diff = diffPlanningActions({+ existing: [existing],+ candidates: [{ ...candidate, periodId: "p2" }],+ toleranceDays: TOLERANCE+ });+ expect(diff.inserts).toHaveLength(1);+ expect(diff.deleteIds).toEqual(["pla-1"]);+ });++ it("updates an Open row in place when the suggestion changes", () => {+ const diff = diffPlanningActions({+ existing: [existing],+ candidates: [{ ...candidate, suggestedQuantity: 12 }],+ toleranceDays: TOLERANCE+ });+ expect(diff.updates).toEqual([+ { id: "pla-1", patch: { suggestedQuantity: 12 } }+ ]);+ });++ it("preserves a human-overridden assignee but still refreshes the suggestion", () => {+ const diff = diffPlanningActions({+ existing: [{ ...existing, assignee: "lead-1", assigneeOverridden: true }],+ candidates: [{ ...candidate, suggestedQuantity: 12 }],+ toleranceDays: TOLERANCE+ });+ expect(diff.updates).toHaveLength(1);+ expect(diff.updates[0]?.patch).toEqual({ suggestedQuantity: 12 });+ expect(diff.updates[0]?.patch).not.toHaveProperty("assignee");+ });++ it("a Dismissed row stays dismissed across an unchanged run", () => {+ const diff = diffPlanningActions({+ existing: [{ ...existing, status: "Dismissed" }],+ candidates: [candidate],+ toleranceDays: TOLERANCE+ });+ expect(diff).toEqual({ inserts: [], updates: [], deleteIds: [] });+ });++ it("refreshes the grid-facing dates on an Open row", () => {+ const diff = diffPlanningActions({+ existing: [+ { ...existing, horizonDate: "2026-10-12", latestOrderDate: null }+ ],+ candidates: [candidate],+ toleranceDays: TOLERANCE+ });+ expect(diff.updates).toEqual([+ {+ id: "pla-1",+ patch: { horizonDate: "2026-10-05", latestOrderDate: "2026-09-30" }+ }+ ]);+ });++ it("refreshes the grid-facing dates on a Dismissed row WITHOUT reopening it", () => {+ const diff = diffPlanningActions({+ existing: [+ { ...existing, status: "Dismissed", horizonDate: "2026-10-12" }+ ],+ candidates: [candidate],+ toleranceDays: TOLERANCE+ });+ expect(diff.updates).toEqual([+ { id: "pla-1", patch: { horizonDate: "2026-10-05" } }+ ]);+ });++ it("float noise in the candidate quantity is not a material change", () => {+ // 0.1 + 0.2 is 0.30000000000000004: the same need, re-summed in a+ // different row order, must not reopen a Dismissed row.+ const diff = diffPlanningActions({+ existing: [{ ...existing, status: "Dismissed", suggestedQuantity: 0.3 }],+ candidates: [{ ...candidate, suggestedQuantity: 0.1 + 0.2 }],+ toleranceDays: TOLERANCE+ });+ expect(diff).toEqual({ inserts: [], updates: [], deleteIds: [] });+ });++ it("reopens a Dismissed row on a material change", () => {+ const diff = diffPlanningActions({+ existing: [{ ...existing, status: "Dismissed" }],+ candidates: [{ ...candidate, suggestedQuantity: 20 }],+ toleranceDays: TOLERANCE+ });+ expect(diff.updates).toHaveLength(1);+ expect(diff.updates[0]?.patch).toMatchObject({+ status: "Open",+ suggestedQuantity: 20+ });+ });++ it("deletes a Dismissed row whose need vanished so a returning need re-surfaces", () => {+ const diff = diffPlanningActions({+ existing: [{ ...existing, status: "Dismissed" }],+ candidates: [],+ toleranceDays: TOLERANCE+ });+ expect(diff.deleteIds).toEqual(["pla-1"]);+ });++ it("keys change actions by their target document", () => {+ const expediteA = naturalKey({+ itemId: "item-1",+ locationId: "loc-1",+ type: "Expedite",+ periodId: "p1",+ purchaseOrderLineId: "pol-a",+ jobId: null+ });+ const expediteB = naturalKey({+ itemId: "item-1",+ locationId: "loc-1",+ type: "Expedite",+ periodId: "p1",+ purchaseOrderLineId: "pol-b",+ jobId: null+ });+ expect(expediteA).not.toBe(expediteB);+ });++ it("passes candidate fields (incl. assignee) through to inserts unchanged", () => {+ const diff = diffPlanningActions({+ existing: [],+ candidates: [candidate],+ toleranceDays: TOLERANCE+ });+ expect(diff.inserts[0]).toEqual(candidate);+ });++ // MRP puts current and overdue demand in the first week, a different week+ // every Sunday, and a change action's need moves with it. Keyed on the week,+ // each such action got a new row weekly, losing its dismissal and assignee.+ describe("identity across weeks", () => {+ const thisRun = PERIODS; // p1 is the current week+ const lastWeek = "p0"; // a week before this run's first++ it("keys a change action by its order, whatever week its need is in", () => {+ const expedite = (periodId: string) =>+ naturalKey({+ itemId: "item-1",+ locationId: "loc-1",+ type: "Expedite",+ periodId,+ purchaseOrderLineId: "pol-a",+ jobId: null+ });+ expect(expedite("p1")).toBe(expedite("p2"));+ });++ it("keys every week up to the current one as one 'now', later weeks apart", () => {+ const keyPeriod = keyPeriodFor(thisRun);+ expect(keyPeriod(lastWeek)).toBe("now");+ expect(keyPeriod("p1")).toBe("now");+ expect(keyPeriod("p2")).toBe("p2");+ });++ it("moves a dismissed change action to its new week instead of replacing it", () => {+ const dismissed: ExistingPlanningAction = {+ ...existing,+ type: "Expedite",+ status: "Dismissed",+ periodId: "p1",+ purchaseOrderLineId: "pol-a"+ };+ const diff = diffPlanningActions({+ existing: [dismissed],+ candidates: [+ {+ ...candidate,+ type: "Expedite",+ periodId: "p2",+ purchaseOrderLineId: "pol-a"+ }+ ],+ periods: thisRun,+ toleranceDays: TOLERANCE+ });+ expect(diff.inserts).toEqual([]);+ expect(diff.deleteIds).toEqual([]);+ expect(diff.updates).toEqual([+ { id: "pla-1", patch: { periodId: "p2" } }+ ]);+ });++ it("keeps last week's current-week Order, and its assignee, when the shortage goes on", () => {+ const lastWeeksOrder: ExistingPlanningAction = {+ ...existing,+ periodId: lastWeek,+ assignee: "planner-2",+ assigneeOverridden: true+ };+ const diff = diffPlanningActions({+ existing: [lastWeeksOrder],+ candidates: [candidate], // p1+ periods: thisRun,+ toleranceDays: TOLERANCE+ });+ expect(diff.inserts).toEqual([]);+ expect(diff.deleteIds).toEqual([]);+ expect(diff.updates).toEqual([+ { id: "pla-1", patch: { periodId: "p1" } }+ ]);+ });++ it("keeps the row already on the current week when two share 'now'", () => {+ const diff = diffPlanningActions({+ existing: [+ { ...existing, id: "pla-old", periodId: lastWeek },+ { ...existing, id: "pla-now", periodId: "p1" }+ ],+ candidates: [candidate],+ periods: thisRun,+ toleranceDays: TOLERANCE+ });+ expect(diff.deleteIds).toEqual(["pla-old"]);+ expect(diff.updates).toEqual([]);+ expect(diff.inserts).toEqual([]);+ });+ });+});++// An Expedite and a new Order could both answer one shortage: sizing read the+// projection with the late order still in its old week. Sizing now reads the+// projection with every Expedite done.+describe("projectionsWithExpedites", () => {+ const expedite = (purchaseOrderLineId: string, periodId: string) => ({+ type: "Expedite" as const,+ periodId,+ purchaseOrderLineId,+ jobId: null+ });+ // p1..p5, stock below zero in p2 and p3 until the PO lands in p4+ const projections = [5, -5, -5, 5, 5];+ const lateOrder = {+ purchaseOrderLineId: "pol-1",+ quantity: 10,+ dueDate: "2026-10-28", // lands in p4+ requiresManualAction: false+ };++ it("counts an expedited order from its need week instead of its landing week", () => {+ expect(+ projectionsWithExpedites({+ projections,+ periods: PERIODS,+ changeActions: [expedite("pol-1", "p2")],+ openOrders: [lateOrder]+ })+ ).toEqual([5, 5, 5, 5, 5]);+ });++ it("covers to the end for an order landing after the last week", () => {+ expect(+ projectionsWithExpedites({+ projections: [5, -5, -5, -5, -5],+ periods: PERIODS,+ changeActions: [expedite("pol-1", "p2")],+ openOrders: [{ ...lateOrder, dueDate: "2026-12-14" }]+ })+ ).toEqual([5, 5, 5, 5, 5]);+ });++ it("leaves the projection alone for every action but Expedite", () => {+ expect(+ projectionsWithExpedites({+ projections,+ periods: PERIODS,+ changeActions: [{ ...expedite("pol-1", "p2"), type: "Defer" as const }],+ openOrders: [lateOrder]+ })+ ).toEqual(projections);+ });++ // Late within the tolerance: no Expedite, but the order still covers the+ // need, so it counts from the need week.+ it("counts an order from its first need week when no action moves it", () => {+ expect(+ projectionsWithExpedites({+ projections,+ periods: PERIODS,+ changeActions: [],+ openOrders: [lateOrder],+ firstNeedPeriods: new Map([["pol-1", "p2"]])+ })+ ).toEqual([5, 5, 5, 5, 5]);+ });++ it("moves an order needed after it lands nowhere", () => {+ expect(+ projectionsWithExpedites({+ projections,+ periods: PERIODS,+ changeActions: [],+ openOrders: [lateOrder],+ firstNeedPeriods: new Map([["pol-1", "p5"]])+ })+ ).toEqual(projections);+ });++ it("moves an expedited order once, not once per source", () => {+ expect(+ projectionsWithExpedites({+ projections,+ periods: PERIODS,+ changeActions: [expedite("pol-1", "p2")],+ openOrders: [lateOrder],+ firstNeedPeriods: new Map([["pol-1", "p2"]])+ })+ ).toEqual([5, 5, 5, 5, 5]);+ });+});++// The whole new-supply path for one item, as generatePlanningActions runs it:+// the change actions, then sizing on the adjusted projection, then the fold+// into an open order.+describe("new supply beside an order late within the tolerance", () => {+ const periods = [+ { id: "w0", startDate: "2026-10-04", endDate: "2026-10-10" },+ { id: "w1", startDate: "2026-10-11", endDate: "2026-10-17" },+ { id: "w2", startDate: "2026-10-18", endDate: "2026-10-24" },+ { id: "w3", startDate: "2026-10-25", endDate: "2026-10-31" }+ ];+ const today = "2026-10-06";++ function plan(demandPeriodId: string, poDue: string, raw: number[]) {+ const openOrders = [+ {+ purchaseOrderLineId: "X",+ quantity: 100,+ dueDate: poDue,+ requiresManualAction: false+ }+ ];+ const coverageInput = {+ onHand: 0,+ demandPeriods: [+ {+ periodId: demandPeriodId,+ startDate: periods.find((p) => p.id === demandPeriodId)!.startDate,+ quantity: 100+ }+ ],+ openOrders,+ periods,+ policyFloor: 0+ };+ const changeActions = deriveChangeActions({+ ...coverageInput,+ toleranceDays: TOLERANCE,+ todayDate: today+ });+ const sizing = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods,+ projections: projectionsWithExpedites({+ projections: raw,+ periods,+ changeActions,+ openOrders,+ firstNeedPeriods: firstNeedPeriodByOrder(coverageInput)+ }),+ todayDate: today,+ params: {+ reorderPoint: 0,+ reorderQuantity: 0,+ minimumOrderQuantity: 0,+ maximumOrderQuantity: 0,+ orderMultiple: 0,+ lotSize: 0,+ maximumInventoryQuantity: 0,+ demandAccumulationPeriod: 1,+ demandAccumulationSafetyStock: 0,+ leadTime: 0+ }+ }).map((o) => ({+ type: "Order" as const,+ periodId: o.periodId,+ suggestedQuantity: o.quantity,+ suggestedDate: o.dueDate,+ horizonDate: o.dueDate,+ latestOrderDate: o.startDate,+ isASAP: o.isASAP,+ purchaseOrderLineId: null,+ jobId: null,+ requiresManualAction: false,+ supplierId: null,+ policyName: o.policyName,+ reason: null,+ triggerValues: null+ }));+ return {+ changeActions,+ merged: convertOrdersToIncreases({+ sizingCandidates: sizing,+ openOrders,+ changeActions,+ toleranceDays: TOLERANCE,+ todayDate: today+ })+ };+ }++ // A need of 100 this week, the PO for 100 landing next Sunday — 5 days,+ // inside the 7-day tolerance. MRP's weekly projection still books the PO in+ // next week, so this week read short by 100, sizing ordered 100 and the+ // fold made it "Increase from 100 to 200" for a need the PO already covers.+ it("suggests nothing for a need this week the PO covers a few days late", () => {+ const { changeActions, merged } = plan("w0", "2026-10-11", [-100, 0, 0, 0]);+ expect(changeActions).toEqual([]);+ expect(merged).toEqual([]);+ });++ it("suggests nothing for a later need the PO covers at the next week start", () => {+ const { changeActions, merged } = plan("w2", "2026-10-25", [0, 0, -100, 0]);+ expect(changeActions).toEqual([]);+ expect(merged).toEqual([]);+ });++ it("still expedites an order late beyond the tolerance, with no new order", () => {+ const { changeActions, merged } = plan(+ "w0",+ "2026-10-18",+ [-100, -100, 0, 0]+ );+ expect(changeActions.map((a) => a.type)).toEqual(["Expedite"]);+ expect(merged).toEqual([]);+ });+});++describe("releaseByDate", () => {+ it("is the day before the due date less the lead time", () => {+ // due in 8 days with a 7-day lead time: release today+ expect(releaseByDate("2026-10-14", 7)).toBe("2026-10-06");+ });++ it("is the day before the due date with no lead time", () => {+ expect(releaseByDate("2026-10-14", 0)).toBe("2026-10-13");+ });+});++describe("earlierRelease", () => {+ const release = (date: string) => ({ date, dueDate: date, leadTime: 0 });++ it("keeps the release that comes first, whichever is passed first", () => {+ expect(+ earlierRelease(release("2026-10-08"), release("2026-10-12")).date+ ).toBe("2026-10-08");+ expect(+ earlierRelease(release("2026-10-12"), release("2026-10-08")).date+ ).toBe("2026-10-08");+ expect(earlierRelease(null, release("2026-10-12")).date).toBe("2026-10-12");+ });+});++describe("deriveReleaseActions", () => {+ const today = "2026-10-06";+ const periods = [+ { id: "w0", startDate: "2026-10-04" },+ { id: "w1", startDate: "2026-10-11" },+ { id: "w2", startDate: "2026-10-18" }+ ];+ const planned = (purchaseOrderLineId: string, releaseDate: string) => ({+ purchaseOrderLineId,+ quantity: 10,+ dueDate: "2026-10-20",+ requiresManualAction: false,+ release: { date: releaseDate, dueDate: "2026-10-20", leadTime: 7 }+ });++ it("raises one Release per planned order, dated its release day", () => {+ const [release] = deriveReleaseActions({+ openOrders: [planned("pol-1", "2026-10-12")],+ changeActions: [],+ periods,+ todayDate: today+ });+ expect(release).toMatchObject({+ type: "Release",+ purchaseOrderLineId: "pol-1",+ suggestedDate: "2026-10-12",+ horizonDate: "2026-10-12",+ periodId: "w1",+ isASAP: false,+ latestOrderDate: null,+ requiresManualAction: false,+ reason: "Due 2026-10-20 with a 7-day lead time"+ });+ });++ it("flags a release due today or already late as ASAP", () => {+ const actions = deriveReleaseActions({+ openOrders: [planned("today", today), planned("late", "2026-10-01")],+ changeActions: [],+ periods,+ todayDate: today+ });+ expect(+ actions.map((a) => [a.purchaseOrderLineId, a.isASAP, a.periodId])+ ).toEqual([+ ["today", true, "w0"],+ ["late", true, "w0"]+ ]);+ });++ it("raises nothing for an order past Planned", () => {+ expect(+ deriveReleaseActions({+ openOrders: [{ ...planned("pol-1", today), release: null }],+ changeActions: [],+ periods,+ todayDate: today+ })+ ).toEqual([]);+ });++ it("raises nothing for an order MRP would cancel", () => {+ expect(+ deriveReleaseActions({+ openOrders: [planned("pol-1", today)],+ changeActions: [+ { type: "Cancel", purchaseOrderLineId: "pol-1", jobId: null }+ ],+ periods,+ todayDate: today+ })+ ).toEqual([]);+ });++ it("keeps a Release beside a change to the same order", () => {+ expect(+ deriveReleaseActions({+ openOrders: [planned("pol-1", today)],+ changeActions: [+ { type: "Increase", purchaseOrderLineId: "pol-1", jobId: null }+ ],+ periods,+ todayDate: today+ })+ ).toHaveLength(1);+ });+});diff --git a/packages/planning/src/mrp/planning-actions.ts b/packages/planning/src/mrp/planning-actions.tsnew file mode 100644index 0000000000..3afe486b20--- /dev/null+++ b/packages/planning/src/mrp/planning-actions.ts@@ -0,0 +1,1657 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Planning action messages (spec §P1) — the persisted, assignable output of an+// MRP run. One row per suggested action:+//+// Order / Make — create new supply (from the shared reorder sizing)+// Expedite / Defer — move an existing open PO line / job (date)+// Increase / Decrease — change an existing order's quantity+// Cancel — an existing order has no remaining requirement+//+// Change actions follow the SAP "rescheduling check on a firmed receipt" model:+// open orders are matched to dated requirements chronologically; a date gap+// STRICTLY greater than companySettings.rescheduleToleranceDays fires+// Expedite/Defer; exactly ONE action is emitted per target document+// (Cancel → Expedite/Defer → Increase/Decrease).+//+// Persistence is a DIFF-WRITE keyed on the natural key (item, location, type,+// period, target document): Open rows update in place (a human-overridden+// assignee is never re-resolved), Dismissed rows stay dismissed unless the+// suggestion changed materially, vanished Open/Dismissed rows are deleted so a+// returning need re-surfaces, and Actioned rows are terminal. Failures+// PROPAGATE to the caller — a run must not report success with stale actions.+//+// Actions are generated over the WHOLE planning window. The per-item planning+// horizon (time fence) is a read-time lens applied by the planning grids, which+// compare each row's `horizonDate` with today + horizon days — so a planner can+// widen the fence on screen without a run. Nothing here reads the horizon.++import type { Database } from "@carbon/database";+import { getCompanyTimeZone } from "@carbon/database";+import type { DB } from "@carbon/database/client";+import { fetchAll } from "@carbon/database/fetch-all";+import { getLogger } from "@carbon/logger";+import {+ computePlanningOrders,+ datetime,+ equals,+ RoundingMode,+ round+} from "@carbon/utils";+import { parseDate, startOfWeek } from "@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";+import { type Kysely, sql } from "kysely";+import { toIsoDate } from "../scheduling/date-utils.ts";+import { loadResponsibleEmployeeResolver } from "./responsible-employee.ts";+import {+ jobCompletionDate,+ purchaseOrderLineArrivalDate+} from "./supply-date.ts";++const logger = getLogger("planning", "planning-actions");++const KEY_SEP = "\x1f";+const WEEKS_TO_PLAN = 48;+/** Planning periods are weeks. */+const DAYS_PER_PERIOD = 7;+const BATCH_SIZE = 500;++export type PlanningActionType =+ | "Order"+ | "Make"+ | "Expedite"+ | "Defer"+ | "Cancel"+ | "Increase"+ | "Decrease"+ | "Release";++export type PlanningActionCandidate = {+ itemId: string;+ locationId: string;+ periodId: string;+ type: PlanningActionType;+ suggestedQuantity: number;+ suggestedDate: string;+ /**+ * The date that decides whether this action is inside a planning horizon:+ * the earlier of the target order's current date and `suggestedDate`. A Defer+ * counts from where its order sits today, an Expedite from when it is needed.+ */+ horizonDate: string;+ /**+ * New-supply actions (Order / Make, and the Increase one folds into): the+ * required date less the item's lead time — the last day to place the order.+ */+ latestOrderDate: string | null;+ isASAP: boolean;+ purchaseOrderLineId: string | null;+ jobId: string | null;+ requiresManualAction: boolean;+ supplierId: string | null;+ policyName: string | null;+ reason: string | null;+ triggerValues: Record<string, number | null | undefined> | null;+ assignee: string | null;+};++export type ExistingPlanningAction = {+ id: string;+ itemId: string;+ locationId: string;+ periodId: string;+ type: PlanningActionType;+ status: "Open" | "Dismissed";+ suggestedQuantity: number;+ suggestedDate: string;+ horizonDate: string;+ latestOrderDate: string | null;+ isASAP: boolean;+ purchaseOrderLineId: string | null;+ jobId: string | null;+ requiresManualAction: boolean;+ supplierId: string | null;+ policyName: string | null;+ reason: string | null;+ triggerValues: unknown;+ assignee: string | null;+ assigneeOverridden: boolean;+};++/** Signed day difference a − b for two ISO calendar dates. */+export function daysBetween(a: string, b: string): number {+ return parseDate(a).compare(parseDate(b));+}++/** The earlier of two ISO calendar dates. */+export function earlierDate(a: string, b: string): string {+ return daysBetween(a, b) <= 0 ? a : b;+}++/** The later of two ISO calendar dates. */+export function laterDate(a: string, b: string): string {+ return daysBetween(a, b) >= 0 ? a : b;+}++/**+ * The view only yields open POs ('Planned' | 'To Receive' | 'To Receive and+ * Invoice'); anything past 'Planned'/'Draft' has been sent to the supplier+ * (mirrors PURCHASE_ORDER_LOCKED_STATUSES in purchasing.models.ts). Never gate+ * on orderDate — insertPurchaseOrder defaults it to today for planned POs.+ */+export function isCommittedPurchaseOrderStatus(+ status: Database["public"]["Enums"]["purchaseOrderStatus"] | null | undefined+): boolean {+ return status !== "Planned" && status !== "Draft";+}++/** Job statuses at/after release-to-floor are committed supply. */+export function isCommittedJobStatus(+ status: Database["public"]["Enums"]["jobStatus"] | null | undefined+): boolean {+ return status === "Ready" || status === "In Progress" || status === "Paused";+}++export type OpenSupplyOrder = {+ purchaseOrderLineId?: string;+ jobId?: string;+ quantity: number;+ /** the date the order is currently expected to land (ISO) */+ dueDate: string;+ requiresManualAction: boolean;+ /**+ * `dueDate` is the supplier's promise (a PO line's or its delivery's+ * promised date). Apply moves only the required date, which a promise+ * outranks, so a date change on such a line is the planner's to agree with+ * the supplier: Expedite / Defer become "Review on PO".+ */+ dateIsPromised?: boolean;+ supplierId?: string | null;+ /**+ * A PO line's inventory units per purchase unit (`purchaseOrderLine.+ * conversionFactor`). `quantity` is in inventory units; Apply writes the+ * line in whole purchase units. Missing or not positive means 1.+ */+ conversionFactor?: number | null;+ /**+ * When a PLANNED order is due to be released (`releaseByDate`); null or+ * absent once it is past Planned — a Release applies only while it is.+ */+ release?: PlannedOrderRelease | null;+};++export type PlannedOrderRelease = {+ /** The last day to release it: due date − lead time − 1 day. */+ date: string;+ /** The due date and lead time that set it — for a purchase order, those of+ * the line that needs releasing first. */+ dueDate: string;+ leadTime: number;+};++/**+ * The last day to release a planned order so it still arrives on time: its+ * due date less the item's lead time, less one more day. Due in 8 days with a+ * 7-day lead time is today.+ */+export function releaseByDate(dueDate: string, leadTimeDays: number): string {+ return parseDate(dueDate)+ .subtract({ days: Math.max(leadTimeDays, 0) + 1 })+ .toString();+}++/** The earlier of two releases (a purchase order is released once, for the+ * line that needs it first). */+export function earlierRelease(+ a: PlannedOrderRelease | null | undefined,+ b: PlannedOrderRelease+): PlannedOrderRelease {+ // daysBetween(a, b) is a − b+ return a && daysBetween(a.date, b.date) <= 0 ? a : b;+}++/**+ * The quantity an order holds once a change to `quantity` is applied. Apply+ * writes a PO line in whole PURCHASE units — `round(suggested /+ * conversionFactor, 0, Up)` — so a suggestion between two multiples was+ * rounded up on the line, read as over-supply by the next run, and suggested+ * again: forever. A suggested quantity is therefore what the line will+ * actually hold. A job's quantity is written as suggested.+ */+export function quantityAfterApply(+ order: Pick<OpenSupplyOrder, "purchaseOrderLineId" | "conversionFactor">,+ quantity: number+): number {+ if (!order.purchaseOrderLineId) return quantity;+ const factor =+ order.conversionFactor && order.conversionFactor > 0+ ? order.conversionFactor+ : 1;+ // Strip float noise before the ceil: 1.1 / 0.1 is 11.000000000000002,+ // which would otherwise ceil a whole purchase unit up to the next one.+ const purchaseUnits = round(round(quantity / factor), 0, RoundingMode.Up);+ return round(purchaseUnits * factor);+}++export type DeriveChangeActionsInput = {+ onHand: number;+ /** total demand per period, chronological */+ demandPeriods: { periodId: string; startDate: string; quantity: number }[];+ openOrders: OpenSupplyOrder[];+ /** all planning periods, chronological (for mapping a date to a period) */+ periods: { id: string; startDate: string }[];+ /**+ * The reorder policy's terminal stock target (safety stock / reorder point).+ * The floor is needed now, so it is claimed first: from on-hand, then the+ * earliest orders. An order holding part of it is never Cancelled, Decreased+ * or Deferred. The floor has no date of its own and never Expedites an order+ * (a reorder point is a trigger to order, not a date stock is due), but+ * demand that on-hand no longer covers once the floor is held can.+ */+ policyFloor: number;+ toleranceDays: number;+ todayDate: string;+};++type ChangeCandidate = Omit<+ PlanningActionCandidate,+ "itemId" | "locationId" | "assignee"+>;++type OrderCoverage = {+ order: OpenSupplyOrder;+ consumed: number;+ holdsFloor: boolean;+ firstNeed: { periodId: string; startDate: string } | null;+};++/**+ * The chronological consumption walk both the change actions and the sizing+ * projection read: the policy floor first (it is needed now), then demand,+ * each drawing down on-hand first, then the earliest open orders. The first+ * requirement an order covers is its need date.+ */+function walkOrderCoverage(+ input: Pick<+ DeriveChangeActionsInput,+ "onHand" | "demandPeriods" | "openOrders" | "periods" | "policyFloor"+ >+): OrderCoverage[] {+ const { onHand, demandPeriods, openOrders, periods, policyFloor } = input;++ // An order due after the last planning week is outside what this walk can+ // judge: the demand it was raised for is not loaded (MRP plans further out+ // than the reschedule check looks), so every such order would read as+ // "nothing needs it" and be offered for Cancel. It gets no verdict instead —+ // and is not pulled in to cover an earlier need either.+ const lastPeriod = periods[periods.length - 1];+ const isInsideHorizon = (order: OpenSupplyOrder) =>+ !lastPeriod ||+ daysBetween(order.dueDate, lastPeriod.startDate) < DAYS_PER_PERIOD;++ const orders: OrderCoverage[] = openOrders+ .filter(isInsideHorizon)+ .map((order) => ({+ order,+ consumed: 0,+ holdsFloor: false,+ firstNeed: null+ }))+ .sort((a, b) => daysBetween(a.order.dueDate, b.order.dueDate));++ // Chronological consumption walk: the policy floor first (it is needed now),+ // then demand, each drawing down on-hand first, then the earliest open+ // orders. The first requirement an order covers is its need date.+ let balance = onHand;+ let cursor = 0;+ const cover = (need: { periodId: string; startDate: string } | null) => {+ while (balance < 0 && cursor < orders.length) {+ const state = orders[cursor];+ if (!state) break;+ const available = state.order.quantity - state.consumed;+ if (available <= 0) {+ cursor++;+ continue;+ }+ const take = Math.min(available, -balance);+ state.consumed += take;+ balance += take;+ if (!need) state.holdsFloor = true;+ else if (!state.firstNeed) state.firstNeed = need;+ if (state.consumed >= state.order.quantity) cursor++;+ }+ };+ // Covered after the demand walk, the floor took whatever was left: an order+ // that held safety stock was dated by a later demand and offered a Defer,+ // and applying it put stock under the floor until that date.+ balance -= Math.max(policyFloor, 0);+ cover(null);+ for (const demand of demandPeriods) {+ balance -= demand.quantity;+ cover({ periodId: demand.periodId, startDate: demand.startDate });+ }++ return orders;+}++/**+ * The week each open order is first needed in, by its target (PO line or+ * job id) — from the same walk as the change actions. Orders that cover no+ * dated need (unneeded, or holding only the policy floor) are absent.+ */+export function firstNeedPeriodByOrder(+ input: Pick<+ DeriveChangeActionsInput,+ "onHand" | "demandPeriods" | "openOrders" | "periods" | "policyFloor"+ >+): Map<string, string> {+ const needs = new Map<string, string>();+ for (const { order, firstNeed } of walkOrderCoverage(input)) {+ const ref = order.purchaseOrderLineId ?? order.jobId;+ if (ref && firstNeed) needs.set(ref, firstNeed.periodId);+ }+ return needs;+}++/**+ * SAP-style rescheduling check over one item+location. Claims the policy+ * floor, then walks demand chronologically, against on-hand and then open+ * orders (earliest first) as the balance goes negative; each order's FIRST+ * covered demand dates it, and an order holding the floor is never deferred.+ * Emits at most ONE action per open order:+ * consumed = 0 → Cancel+ * |expected − needed| > tolerance → Expedite / Defer, where expected is+ * the due date and needed the first+ * need's week start, each no earlier+ * than today+ * leftover quantity (no date action) → Decrease, to what the order will+ * hold (`quantityAfterApply`)+ */+export function deriveChangeActions(+ input: DeriveChangeActionsInput+): ChangeCandidate[] {+ const { openOrders, periods, toleranceDays, todayDate } = input;++ if (openOrders.length === 0) return [];++ const periodFor = (dateIso: string): { id: string; startDate: string } => {+ let match = periods[0];+ for (const p of periods) {+ if (daysBetween(p.startDate, dateIso) <= 0) match = p;+ else break;+ }+ return match ?? { id: "", startDate: dateIso };+ };++ const orders = walkOrderCoverage(input);++ const actions: ChangeCandidate[] = [];+ for (const { order, consumed, holdsFloor, firstNeed } of orders) {+ const target = {+ purchaseOrderLineId: order.purchaseOrderLineId ?? null,+ jobId: order.jobId ?? null,+ requiresManualAction: order.requiresManualAction,+ supplierId: order.supplierId ?? null,+ policyName: null,+ triggerValues: null,+ latestOrderDate: null+ };++ if (consumed <= 0) {+ const period = periodFor(order.dueDate);+ actions.push({+ ...target,+ type: "Cancel",+ periodId: period.id,+ suggestedQuantity: order.quantity,+ suggestedDate: order.dueDate,+ horizonDate: order.dueDate,+ isASAP: false,+ reason: "No remaining requirement for this order"+ });+ continue;+ }++ if (firstNeed) {+ // An overdue order arrives today at the earliest, not on its old due+ // date: measured from that date it read as "early" and was offered a+ // Defer to a date already past.+ const expectedDate = laterDate(order.dueDate, todayDate);+ // Likewise a need in the current week is needed today, not on the+ // week's start: Apply writes the suggested date onto the order, so an+ // Expedite to a past week start made the order overdue — read as+ // arriving today, days after the week start — and the same Expedite+ // came back every run whenever the tolerance was under a week.+ const needDate = laterDate(firstNeed.startDate, todayDate);+ // gap > 0: the order lands AFTER it is needed+ const gap = daysBetween(expectedDate, needDate);+ // Moving a promised date is agreed with the supplier, not applied.+ const dateTarget = {+ ...target,+ requiresManualAction:+ target.requiresManualAction || Boolean(order.dateIsPromised)+ };+ if (gap > toleranceDays) {+ actions.push({+ ...dateTarget,+ type: "Expedite",+ periodId: firstNeed.periodId,+ suggestedQuantity: order.quantity,+ suggestedDate: needDate,+ horizonDate: earlierDate(order.dueDate, needDate),+ isASAP: daysBetween(firstNeed.startDate, todayDate) < 0,+ reason: `Needed ${gap} days earlier than its current date`+ });+ continue;+ }+ // An order holding the floor is needed now, whatever demand follows.+ if (gap < -toleranceDays && !holdsFloor) {+ actions.push({+ ...dateTarget,+ type: "Defer",+ periodId: firstNeed.periodId,+ suggestedQuantity: order.quantity,+ suggestedDate: needDate,+ horizonDate: earlierDate(order.dueDate, needDate),+ isASAP: false,+ reason: `Not needed until ${-gap} days after its current date`+ });+ continue;+ }+ }++ // Round at the compare: `consumed` is a running float sum, so the raw+ // difference can be ~1e-16 for an order that is fully required.+ const required = round(consumed);+ // What the order holds once decreased — a PO line in whole purchase+ // units — so a line already at the rounded quantity is left alone.+ const decreasedTo = quantityAfterApply(order, required);+ if (round(order.quantity - decreasedTo) > 0) {+ const period = periodFor(order.dueDate);+ actions.push({+ ...target,+ type: "Decrease",+ periodId: period.id,+ suggestedQuantity: decreasedTo,+ suggestedDate: order.dueDate,+ horizonDate: order.dueDate,+ isASAP: false,+ reason: `Only ${required} of ${order.quantity} is required`+ });+ }+ }++ return actions;+}++/**+ * The stock projection as if every open order arrived when it is needed: an+ * expedited order's quantity counts from the week it is needed instead of the+ * week it lands — and so does an order that is late by no more than the+ * reschedule tolerance, which gets no Expedite (`firstNeedPeriods`).+ *+ * New-supply sizing reads this projection. Sized on the raw one, a shortage an+ * Expedite already covers also got an Order (or Make) for the same week, and+ * applying both doubled that week's supply and left the order's old week short.+ * An order a few days late was the same case without the Expedite: a need of+ * 100 this week and a PO of 100 landing next Sunday read as short by 100 this+ * week, so sizing ordered 100 more — folded into "Increase from 100 to 200"+ * on that very PO, and a Decrease back on the next run.+ * Only Expedite moves supply EARLIER; Defer, Cancel and Decrease take away+ * supply nothing needs, so they cannot open a shortage and are not applied.+ *+ * `projections[i]` is the projected on-hand at the end of `periods[i]`. An order+ * dated before the first week counts in it (as MRP books overdue supply); one+ * dated after the last week is outside the projection.+ */+export function projectionsWithExpedites(args: {+ projections: number[];+ periods: { id: string; startDate: string }[];+ changeActions: Pick<+ ChangeCandidate,+ "type" | "periodId" | "purchaseOrderLineId" | "jobId"+ >[];+ openOrders: OpenSupplyOrder[];+ /** The week each order is first needed in (`firstNeedPeriodByOrder`). */+ firstNeedPeriods?: Map<string, string>;+}): number[] {+ const { projections, periods, changeActions, openOrders } = args;+ const adjusted = [...projections];+ const lastPeriod = periods[periods.length - 1];++ const weekOf = (dateIso: string): number => {+ if (+ lastPeriod &&+ daysBetween(dateIso, lastPeriod.startDate) >= DAYS_PER_PERIOD+ ) {+ return periods.length;+ }+ let index = 0;+ periods.forEach((p, i) => {+ if (daysBetween(p.startDate, dateIso) <= 0) index = i;+ });+ return index;+ };++ // Each order moves once, to the week it is needed. An Expedite names that+ // week itself; the walk's first need covers the rest.+ const needPeriodByOrder = new Map<string, string>();+ for (const action of changeActions) {+ if (action.type !== "Expedite") continue;+ const target = action.purchaseOrderLineId ?? action.jobId;+ if (target) needPeriodByOrder.set(target, action.periodId);+ }+ for (const [target, periodId] of args.firstNeedPeriods ?? []) {+ if (!needPeriodByOrder.has(target)) needPeriodByOrder.set(target, periodId);+ }++ for (const [target, periodId] of needPeriodByOrder) {+ const order = openOrders.find(+ (o) => (o.purchaseOrderLineId ?? o.jobId) === target+ );+ const needIndex = periods.findIndex((p) => p.id === periodId);+ if (!order || needIndex < 0) continue;++ // an order landing in or before its need week moves nothing+ const landIndex = Math.min(weekOf(order.dueDate), adjusted.length);+ for (let i = needIndex; i < landIndex; i++) {+ adjusted[i] = (adjusted[i] ?? 0) + order.quantity;+ }+ }+ return adjusted;+}++/**+ * Fold a new-supply suggestion into an existing open order landing in the same+ * window: instead of "create another order" AND leaving the existing one+ * unchanged, emit ONE Increase on that order (to existing + suggested). Only+ * orders that received no other action are eligible — one action per target.+ */+export function convertOrdersToIncreases(args: {+ sizingCandidates: ChangeCandidate[];+ openOrders: OpenSupplyOrder[];+ changeActions: ChangeCandidate[];+ toleranceDays: number;+ todayDate: string;+}): ChangeCandidate[] {+ const { sizingCandidates, openOrders, changeActions, toleranceDays } = args;+ // Both dates as the day they mean: an overdue order lands today, and a+ // suggestion for the current week (dated its start) is needed today — so+ // an order an Expedite moved to today still matches this week's shortfall.+ const asOfToday = (dateIso: string) => laterDate(dateIso, args.todayDate);++ const targeted = new Set(+ changeActions.map((a) => a.purchaseOrderLineId ?? a.jobId ?? "")+ );+ const used = new Set<string>();++ return sizingCandidates.map((candidate) => {+ if (candidate.type !== "Order" && candidate.type !== "Make") {+ return candidate;+ }+ const match = openOrders.find((order) => {+ const ref = order.purchaseOrderLineId ?? order.jobId ?? "";+ if (!ref || targeted.has(ref) || used.has(ref)) return false;+ const isBuy = Boolean(order.purchaseOrderLineId);+ if (candidate.type === "Order" && !isBuy) return false;+ if (candidate.type === "Make" && isBuy) return false;+ return (+ Math.abs(+ daysBetween(+ asOfToday(order.dueDate),+ asOfToday(candidate.suggestedDate)+ )+ ) <= toleranceDays+ );+ });+ if (!match) return candidate;+ // What the order holds once increased — a PO line in whole purchase+ // units — so the next run reads exactly what Apply wrote.+ const increasedTo = quantityAfterApply(+ match,+ match.quantity + candidate.suggestedQuantity+ );+ if (round(increasedTo - match.quantity) <= 0) return candidate;+ used.add(match.purchaseOrderLineId ?? match.jobId ?? "");+ return {+ ...candidate,+ type: "Increase",+ purchaseOrderLineId: match.purchaseOrderLineId ?? null,+ jobId: match.jobId ?? null,+ requiresManualAction: match.requiresManualAction,+ // the line's own supplier — the candidate carries the item's preferred+ // one, which need not be who this PO is with+ supplierId: match.supplierId ?? null,+ horizonDate: earlierDate(match.dueDate, candidate.suggestedDate),+ suggestedQuantity: increasedTo,+ reason: `Increase from ${match.quantity} to cover a shortfall of ${round(candidate.suggestedQuantity)}`+ };+ });+}++/**+ * One Release per planned order (`OpenSupplyOrder.release`), dated the last+ * day to release it. Released from the order itself — the planning pages link+ * to it — so it is never applied. An order MRP would Cancel gets none.+ */+export function deriveReleaseActions(args: {+ openOrders: OpenSupplyOrder[];+ changeActions: Pick<+ ChangeCandidate,+ "type" | "purchaseOrderLineId" | "jobId"+ >[];+ periods: { id: string; startDate: string }[];+ todayDate: string;+}): ChangeCandidate[] {+ const { openOrders, changeActions, periods, todayDate } = args;+ const cancelled = new Set(+ changeActions+ .filter((a) => a.type === "Cancel")+ .map((a) => a.purchaseOrderLineId ?? a.jobId)+ );+ // the week a date falls in; an earlier date is the first week+ const periodFor = (dateIso: string) => {+ let match = periods[0];+ for (const p of periods) {+ if (daysBetween(p.startDate, dateIso) <= 0) match = p;+ else break;+ }+ return match;+ };++ const actions: ChangeCandidate[] = [];+ for (const order of openOrders) {+ const release = order.release;+ if (!release) continue;+ if (cancelled.has(order.purchaseOrderLineId ?? order.jobId ?? null)) {+ continue;+ }+ const period = periodFor(release.date);+ if (!period) continue;+ actions.push({+ type: "Release",+ periodId: period.id,+ suggestedQuantity: order.quantity,+ suggestedDate: release.date,+ horizonDate: release.date,+ // the latest-order-date column is for new supply, not this+ latestOrderDate: null,+ // its day has come (or gone): release it now+ isASAP: daysBetween(release.date, todayDate) <= 0,+ purchaseOrderLineId: order.purchaseOrderLineId ?? null,+ jobId: order.jobId ?? null,+ requiresManualAction: false,+ supplierId: order.supplierId ?? null,+ policyName: null,+ reason: `Due ${release.dueDate} with a ${release.leadTime}-day lead time`,+ triggerValues: { leadTime: release.leadTime }+ });+ }+ return actions;+}++/**+ * The identity an action keeps from run to run.+ *+ * A change action belongs to its ORDER: item, location, type and target. Its+ * period (the week of the need it was measured against) is data, so a need+ * that moves a week updates the same row instead of replacing it.+ *+ * A new-supply action (Order / Make) has no order yet, so its week is its+ * identity — except that every week up to the current one is one "now" key+ * (`keyPeriod`). MRP puts all current and overdue demand in the first week,+ * which is a different week every Sunday; keyed on it, a shortage that went on+ * got a new row each week and lost its dismissal and its hand-set assignee.+ */+export function naturalKey(+ action: {+ itemId: string;+ locationId: string;+ type: string;+ periodId: string;+ purchaseOrderLineId: string | null;+ jobId: string | null;+ },+ keyPeriod: (periodId: string) => string = (periodId) => periodId+): string {+ const target = action.purchaseOrderLineId ?? action.jobId;+ return [+ action.itemId,+ action.locationId,+ action.type,+ target ? `order:${target}` : `period:${keyPeriod(action.periodId)}`+ ].join(KEY_SEP);+}++/**+ * `naturalKey`'s period mapping for one run: the current week, and any week+ * before it (a row written in an earlier week), are all "now".+ */+export function keyPeriodFor(+ periods: { id: string }[]+): (periodId: string) => string {+ const current = periods[0]?.id;+ const later = new Set(periods.slice(1).map((p) => p.id));+ return (periodId) =>+ periodId === current || !later.has(periodId) ? "now" : periodId;+}++export type PlanningActionDiff = {+ inserts: PlanningActionCandidate[];+ updates: {+ id: string;+ patch: Record<string, unknown>;+ }[];+ deleteIds: string[];+};++/**+ * JSON-value equality independent of object key order. Postgres jsonb returns+ * keys in length-then-bytewise order while candidates build insertion-ordered+ * literals, so a raw JSON.stringify comparison re-patched identical+ * triggerValues on every run — breaking the two-identical-runs-produce-zero-+ * changes invariant and churning updatedAt/updatedBy.+ */+export function jsonEquals(a: unknown, b: unknown): boolean {+ if (a === b) return true;+ if (+ typeof a !== "object" ||+ typeof b !== "object" ||+ a === null ||+ b === null+ ) {+ return false;+ }+ if (Array.isArray(a) || Array.isArray(b)) {+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {+ return false;+ }+ return a.every((value, index) => jsonEquals(value, b[index]));+ }+ const aKeys = Object.keys(a);+ const bKeys = Object.keys(b);+ if (aKeys.length !== bKeys.length) return false;+ return aKeys.every((key) =>+ jsonEquals(+ (a as Record<string, unknown>)[key],+ (b as Record<string, unknown>)[key]+ )+ );+}++/**+ * Diff-write plan: never delete-and-recreate — assignment and dismissal state+ * must survive a run. Two identical consecutive runs produce zero changes.+ */+export function diffPlanningActions(args: {+ existing: ExistingPlanningAction[];+ candidates: PlanningActionCandidate[];+ toleranceDays: number;+ /** This run's weeks, current first; their ids decide what is "now". */+ periods?: { id: string }[];+}): PlanningActionDiff {+ const { existing, candidates, toleranceDays } = args;+ const keyPeriod = args.periods ? keyPeriodFor(args.periods) : undefined;+ const keyOf = (action: Parameters<typeof naturalKey>[0]) =>+ naturalKey(action, keyPeriod);++ // Two stored rows can share a "now" key (last week's current-week row and+ // one written for this week): keep the one already on the current week; the+ // other is deleted below as unseen.+ const currentPeriodId = args.periods?.[0]?.id;+ const existingByKey = new Map<string, ExistingPlanningAction>();+ for (const row of existing) {+ const key = keyOf(row);+ const kept = existingByKey.get(key);+ if (!kept || row.periodId === currentPeriodId) existingByKey.set(key, row);+ }+ const keptIds = new Set([...existingByKey.values()].map((row) => row.id));+ const seen = new Set<string>();++ const inserts: PlanningActionCandidate[] = [];+ const updates: PlanningActionDiff["updates"] = [];++ for (const candidate of candidates) {+ const key = keyOf(candidate);+ if (seen.has(key)) continue; // one action per natural key+ seen.add(key);++ const current = existingByKey.get(key);+ if (!current) {+ inserts.push(candidate);+ continue;+ }++ const materialChange =+ !equals(current.suggestedQuantity, candidate.suggestedQuantity) ||+ Math.abs(daysBetween(current.suggestedDate, candidate.suggestedDate)) >+ toleranceDays;++ const patch: Record<string, unknown> = {};+ // The week and the grid-facing dates track the candidate on every row,+ // dismissed ones included: keeping them current never re-opens anything.+ if (current.periodId !== candidate.periodId) {+ patch.periodId = candidate.periodId;+ }+ if (current.horizonDate !== candidate.horizonDate) {+ patch.horizonDate = candidate.horizonDate;+ }+ if ((current.latestOrderDate ?? null) !== candidate.latestOrderDate) {+ patch.latestOrderDate = candidate.latestOrderDate;+ }++ if (current.status === "Dismissed" && !materialChange) {+ // dismissed suppresses a persisting, unchanged need+ if (Object.keys(patch).length > 0) {+ updates.push({ id: current.id, patch });+ }+ continue;+ }++ if (current.status === "Dismissed") patch.status = "Open";+ if (!equals(current.suggestedQuantity, candidate.suggestedQuantity)) {+ patch.suggestedQuantity = candidate.suggestedQuantity;+ }+ if (current.suggestedDate !== candidate.suggestedDate) {+ patch.suggestedDate = candidate.suggestedDate;+ }+ if (current.isASAP !== candidate.isASAP) patch.isASAP = candidate.isASAP;+ if (current.requiresManualAction !== candidate.requiresManualAction) {+ patch.requiresManualAction = candidate.requiresManualAction;+ }+ if ((current.supplierId ?? null) !== candidate.supplierId) {+ patch.supplierId = candidate.supplierId;+ }+ if ((current.policyName ?? null) !== candidate.policyName) {+ patch.policyName = candidate.policyName;+ }+ if ((current.reason ?? null) !== candidate.reason) {+ patch.reason = candidate.reason;+ }+ if (+ !jsonEquals(+ current.triggerValues ?? null,+ candidate.triggerValues ?? null+ )+ ) {+ patch.triggerValues = candidate.triggerValues;+ }+ if (+ !current.assigneeOverridden &&+ (current.assignee ?? null) !== candidate.assignee+ ) {+ patch.assignee = candidate.assignee;+ }++ if (Object.keys(patch).length > 0) {+ updates.push({ id: current.id, patch });+ }+ }++ const deleteIds = existing+ .filter((e) => !keptIds.has(e.id) || !seen.has(keyOf(e)))+ .map((e) => e.id);++ return { inserts, updates, deleteIds };+}++/**+ * The Postgres type of every column a diff patch can set: the cast each+ * `VALUES` column needs, since a bound parameter arrives untyped. A patch key+ * missing here is a programming error and throws before anything is written.+ */+const PATCH_COLUMN_TYPES: Record<string, string> = {+ periodId: "text",+ horizonDate: "date",+ latestOrderDate: "date",+ status: '"planningActionStatus"',+ suggestedQuantity: "numeric",+ suggestedDate: "date",+ isASAP: "boolean",+ requiresManualAction: "boolean",+ supplierId: "text",+ policyName: "text",+ reason: "text",+ triggerValues: "jsonb",+ assignee: "text"+};++/**+ * Writes one run's diff inside the caller's transaction.+ *+ * The run read the actions before it computed this diff, so a row a planner+ * applied in between still reads as Open or Dismissed here. Every DELETE and+ * UPDATE therefore skips `Actioned` rows itself: without that, the run deleted+ * an applied action (and its claim) or reopened it with a `status: "Open"`+ * patch, offering it to be applied twice.+ *+ * Updates are grouped by the columns they change and sent as one+ * `UPDATE … FROM (VALUES …)` per group and chunk. They were one statement per+ * row — thousands of round trips on the weekly roll of the first period, with+ * the transaction holding a connection of the job pool throughout. Each row+ * keeps its own patch: writing every column would also move a dismissed row's+ * stored quantity, and a changed need would then never cross the tolerance.+ */+export async function writePlanningActionDiff(+ trx: Kysely<DB>,+ args: {+ companyId: string;+ userId: string;+ diff: PlanningActionDiff;+ updatedAt: string;+ }+): Promise<void> {+ const { companyId, userId, diff, updatedAt } = args;++ for (let i = 0; i < diff.deleteIds.length; i += BATCH_SIZE) {+ await trx+ .deleteFrom("planningAction")+ .where("companyId", "=", companyId)+ .where("status", "!=", "Actioned")+ .where("id", "in", diff.deleteIds.slice(i, i + BATCH_SIZE))+ .execute();+ }++ const groups = new Map<string, PlanningActionDiff["updates"]>();+ for (const update of diff.updates) {+ const shape = Object.keys(update.patch).sort().join(",");+ const group = groups.get(shape);+ if (group) group.push(update);+ else groups.set(shape, [update]);+ }++ for (const [shape, rows] of groups) {+ const columns = shape.split(",");+ for (const column of columns) {+ if (!PATCH_COLUMN_TYPES[column]) {+ throw new Error(`No column type for planning action patch "${column}"`);+ }+ }+ // The diff skipped an overridden assignee when it READ the row, but a+ // planner can assign between that read and this write (Assign does not+ // take the run's lock), so the statement re-checks the flag on the row.+ const assignments = sql.join(+ columns.map((column) =>+ column === "assignee"+ ? sql`"assignee" = CASE WHEN t."assigneeOverridden" THEN t."assignee" ELSE v."assignee"::text END`+ : sql`${sql.id(column)} = v.${sql.id(column)}::${sql.raw(+ PATCH_COLUMN_TYPES[column]!+ )}`+ )+ );+ const valueColumns = sql.join(["id", ...columns].map((c) => sql.id(c)));++ for (let i = 0; i < rows.length; i += BATCH_SIZE) {+ const values = sql.join(+ rows.slice(i, i + BATCH_SIZE).map(+ (row) =>+ sql`(${sql.join([+ row.id,+ ...columns.map((column) => {+ const value = row.patch[column] ?? null;+ return column === "triggerValues" && value !== null+ ? JSON.stringify(value)+ : value;+ })+ ])})`+ )+ );+ await sql`+ UPDATE "planningAction" AS t+ SET ${assignments}, "updatedBy" = ${userId}, "updatedAt" = ${updatedAt}+ FROM (VALUES ${values}) AS v(${valueColumns})+ WHERE t."id" = v."id"+ AND t."companyId" = ${companyId}+ AND t."status" <> 'Actioned'+ `.execute(trx);+ }+ }++ for (let i = 0; i < diff.inserts.length; i += BATCH_SIZE) {+ const chunk = diff.inserts.slice(i, i + BATCH_SIZE);+ await trx+ .insertInto("planningAction")+ .values(+ chunk.map((candidate) => ({+ companyId,+ itemId: candidate.itemId,+ locationId: candidate.locationId,+ periodId: candidate.periodId,+ type: candidate.type,+ suggestedQuantity: candidate.suggestedQuantity,+ suggestedDate: candidate.suggestedDate,+ horizonDate: candidate.horizonDate,+ latestOrderDate: candidate.latestOrderDate,+ isASAP: candidate.isASAP,+ purchaseOrderLineId: candidate.purchaseOrderLineId,+ jobId: candidate.jobId,+ requiresManualAction: candidate.requiresManualAction,+ supplierId: candidate.supplierId,+ policyName: candidate.policyName,+ reason: candidate.reason,+ triggerValues: candidate.triggerValues+ ? JSON.stringify(candidate.triggerValues)+ : null,+ assignee: candidate.assignee,+ createdBy: userId+ }))+ )+ .execute();+ }+}++// ──────────────────────────────────────────────────────────────+// Orchestrator+// ──────────────────────────────────────────────────────────────++type RpcPlanningRow =+ Database["public"]["Functions"]["get_purchasing_planning"]["Returns"][number];+type ProductionPlanningRow =+ Database["public"]["Functions"]["get_production_planning"]["Returns"][number];++function policyFloorFor(row: {+ reorderingPolicy: string;+ demandAccumulationSafetyStock: number;+ reorderPoint: number;+ supersessionMode: string | null;+ minimumReserveQuantity: number;+}): number {+ if (row.supersessionMode === "Stock Only") {+ return Number(row.minimumReserveQuantity) || 0;+ }+ switch (row.reorderingPolicy) {+ case "Demand-Based Reorder":+ return Number(row.demandAccumulationSafetyStock) || 0;+ case "Fixed Reorder Quantity":+ case "Maximum Quantity":+ return Number(row.reorderPoint) || 0;+ default:+ return 0;+ }+}++export async function generatePlanningActions(+ client: SupabaseClient<Database>,+ db: Kysely<DB>,+ args: { companyId: string; userId: string }+): Promise<{ inserted: number; updated: number; deleted: number }> {+ const { companyId, userId } = args;++ const timeZone = await getCompanyTimeZone(db, companyId);+ const todayDate = datetime.today(timeZone).toString();+ const weekStart = startOfWeek(datetime.today(timeZone), "en-US").toString();++ const [settings, locations, periodRows] = await Promise.all([+ db+ .selectFrom("companySettings")+ .select(["rescheduleToleranceDays"])+ .where("id", "=", companyId)+ .executeTakeFirst(),+ db+ .selectFrom("location")+ .select(["id"])+ .where("companyId", "=", companyId)+ .execute(),+ db+ .selectFrom("period")+ .select(["id", "startDate"])+ .where("periodType", "=", "Week")+ .where("startDate", ">=", weekStart)+ .orderBy("startDate", "asc")+ .limit(WEEKS_TO_PLAN)+ .execute()+ ]);++ const toleranceDays = Number(settings?.rescheduleToleranceDays ?? 7);+ const periods = periodRows.map((p) => ({+ id: p.id,+ startDate: toIsoDate(p.startDate as unknown as string | Date)!+ }));+ const periodIds = periods.map((p) => p.id);+ const periodIdSet = new Set(periodIds);+ const periodById = new Map(periods.map((p) => [p.id, p]));++ if (periods.length === 0 || locations.length === 0) {+ return { inserted: 0, updated: 0, deleted: 0 };+ }++ // Every read below is independent of the others, so they run together in+ // two groups instead of one after another (they were six waits in a row).+ // Two groups, not one: the resolver alone takes five Kysely reads from the+ // shared process pool, so a bounded group leaves connections for the run's+ // other work — the PostgREST views ride alongside it.+ const [resolveAssignee, openPoLines, openJobs] = await Promise.all([+ loadResponsibleEmployeeResolver(db, companyId),+ // ── open supply (real documents change actions target)+ fetchAll<Database["public"]["Views"]["openPurchaseOrderLines"]["Row"]>(() =>+ client+ .from("openPurchaseOrderLines")+ .select("*")+ .eq("companyId", companyId)+ .order("id")+ ),+ fetchAll<Database["public"]["Views"]["openProductionOrders"]["Row"]>(() =>+ client+ .from("openProductionOrders")+ .select("*")+ .eq("companyId", companyId)+ .order("id")+ )+ ]);+ if (openPoLines.error) throw openPoLines.error;+ if (openJobs.error) throw openJobs.error;+ const poLineRows = openPoLines.data ?? [];+ const jobRows = openJobs.data ?? [];++ // ── demand per (item, location, period): actual + forecast + projection+ // (net of consumption), the same union the planning RPCs read; on-hand;+ // the open jobs' status and good-unit quantity, and the open PO lines'+ // conversion factor, which the openProductionOrders / openPurchaseOrderLines+ // views do not expose — one read each of the company's open documents+ // (the views' own filters), no id list.+ const [+ demandActuals,+ demandForecasts,+ demandProjections,+ inventoryRows,+ openJobRows,+ poLineFactorRows+ ] = await Promise.all([+ db+ .selectFrom("demandActual")+ .select(["itemId", "locationId", "periodId", "actualQuantity"])+ .where("companyId", "=", companyId)+ .execute(),+ db+ .selectFrom("demandForecast")+ .select(["itemId", "locationId", "periodId", "forecastQuantity"])+ .where("companyId", "=", companyId)+ .execute(),+ db+ .selectFrom("demandProjection")+ .select([+ "itemId",+ "locationId",+ "periodId",+ "forecastQuantity",+ "consumedQuantity"+ ])+ .where("companyId", "=", companyId)+ .execute(),+ db+ .selectFrom("itemStockQuantities")+ .select(["itemId", "locationId", "quantityOnHand"])+ .where("companyId", "=", companyId)+ .execute(),+ db+ .selectFrom("job")+ .select(["id", "status", "quantity", "quantityReceivedToInventory"])+ .where("companyId", "=", companyId)+ .where("status", "in", ["Planned", "Ready", "In Progress", "Paused"])+ .execute(),+ // Only the lines bought in a unit other than the inventory unit: every+ // other line's factor is 1, the default below.+ db+ .selectFrom("purchaseOrderLine as pol")+ .innerJoin("purchaseOrder as po", "po.id", "pol.purchaseOrderId")+ .select(["pol.id", "pol.conversionFactor"])+ .where("pol.companyId", "=", companyId)+ .where("po.status", "in", [+ "To Receive",+ "To Receive and Invoice",+ "Planned"+ ])+ .where("pol.receivedComplete", "=", false)+ .where("pol.conversionFactor", "!=", 1)+ .execute()+ ]);++ const demandByItemLocation = new Map<string, Map<string, number>>();+ const addDemand = (+ itemId: string | null,+ locationId: string | null,+ periodId: string | null,+ quantity: number | null+ ) => {+ if (!itemId || !locationId || !periodId) return;+ if (!periodIdSet.has(periodId)) return;+ const key = `${itemId}${KEY_SEP}${locationId}`;+ const byPeriod = demandByItemLocation.get(key) ?? new Map<string, number>();+ byPeriod.set(+ periodId,+ (byPeriod.get(periodId) ?? 0) + (Number(quantity) || 0)+ );+ demandByItemLocation.set(key, byPeriod);+ };+ for (const row of demandActuals) {+ addDemand(row.itemId, row.locationId, row.periodId, row.actualQuantity);+ }+ for (const row of demandForecasts) {+ addDemand(row.itemId, row.locationId, row.periodId, row.forecastQuantity);+ }+ for (const row of demandProjections) {+ addDemand(+ row.itemId,+ row.locationId,+ row.periodId,+ Math.max(+ (Number(row.forecastQuantity) || 0) -+ (Number(row.consumedQuantity) || 0),+ 0+ )+ );+ }++ const onHandByItemLocation = new Map<string, number>();+ for (const row of inventoryRows) {+ if (row.itemId && row.locationId) {+ onHandByItemLocation.set(+ `${row.itemId}${KEY_SEP}${row.locationId}`,+ Number(row.quantityOnHand) || 0+ );+ }+ }++ const jobById = new Map<+ string,+ {+ status: Database["public"]["Enums"]["jobStatus"];+ quantity: number;+ quantityReceivedToInventory: number;+ }+ >();+ for (const row of openJobRows) {+ if (!row.status) continue;+ jobById.set(row.id, {+ status: row.status,+ quantity: Number(row.quantity) || 0,+ quantityReceivedToInventory: Number(row.quantityReceivedToInventory) || 0+ });+ }++ const conversionFactorByLineId = new Map(+ poLineFactorRows.map((row) => [row.id, Number(row.conversionFactor)])+ );++ const openOrdersByItemLocation = new Map<string, OpenSupplyOrder[]>();+ const pushOrder = (key: string, order: OpenSupplyOrder) => {+ const list = openOrdersByItemLocation.get(key) ?? [];+ list.push(order);+ openOrdersByItemLocation.set(key, list);+ };+ // A Planned purchase order is released once, for whichever of its lines+ // needs it first — every line's Release carries that date.+ const releaseByPurchaseOrder = new Map<string, PlannedOrderRelease>();+ for (const line of poLineRows) {+ if (line.status !== "Planned" || !line.purchaseOrderId) continue;+ if ((Number(line.quantityToReceive) || 0) <= 0) continue;+ const dueDate = purchaseOrderLineArrivalDate(line, todayDate);+ const leadTime = Number(line.leadTime) || 0;+ releaseByPurchaseOrder.set(+ line.purchaseOrderId,+ earlierRelease(releaseByPurchaseOrder.get(line.purchaseOrderId), {+ date: releaseByDate(dueDate, leadTime),+ dueDate,+ leadTime+ })+ );+ }++ for (const line of poLineRows) {+ if (!line.id || !line.itemId || !line.locationId) continue;+ const quantity = Number(line.quantityToReceive) || 0;+ if (quantity <= 0) continue;+ // the same arrival date the projection buckets this line on+ const dueDate = purchaseOrderLineArrivalDate(line, todayDate);+ pushOrder(`${line.itemId}${KEY_SEP}${line.locationId}`, {+ purchaseOrderLineId: line.id,+ quantity,+ dueDate,+ requiresManualAction: isCommittedPurchaseOrderStatus(line.status),+ dateIsPromised: Boolean(line.promisedDate),+ supplierId: line.supplierId,+ conversionFactor: conversionFactorByLineId.get(line.id) ?? 1,+ release:+ line.status === "Planned" && line.purchaseOrderId+ ? (releaseByPurchaseOrder.get(line.purchaseOrderId) ?? null)+ : null+ });+ }+ for (const job of jobRows) {+ if (!job.id || !job.itemId || !job.locationId) continue;+ const details = jobById.get(job.id);+ // The view's quantityToReceive is productionQuantity (quantity + scrap)+ // less received. A change action is applied to `job.quantity`, the good+ // units, so the order is measured in those: on the view's figure every+ // job with a scrap allowance read as over-supplied, got a Decrease to its+ // own quantity, and got it again after it was applied.+ const quantity = details+ ? Math.max(details.quantity - details.quantityReceivedToInventory, 0)+ : Number(job.quantityToReceive) || 0;+ if (quantity <= 0) continue;+ // the same date the projection buckets this job on — an undated job is+ // supply there, so it is supply here too+ const dueDate = jobCompletionDate(job, todayDate);+ const leadTime = Number(job.leadTime) || 0;+ pushOrder(`${job.itemId}${KEY_SEP}${job.locationId}`, {+ jobId: job.id,+ quantity,+ dueDate,+ requiresManualAction: isCommittedJobStatus(details?.status),+ release:+ details?.status === "Planned"+ ? { date: releaseByDate(dueDate, leadTime), dueDate, leadTime }+ : null+ });+ }++ // ── planning rows (projections + reorder params) per location+ const candidates: PlanningActionCandidate[] = [];++ for (const location of locations) {+ // Paged like every other read in the run: a bare RPC call stops at+ // PostgREST's max_rows, and an item missing from these rows has no+ // candidates — the diff below would then DELETE its existing actions,+ // dismissals and assignee overrides included. `id` is the item id, unique+ // per row, so the pages neither overlap nor skip.+ const [purchasing, production] = await Promise.all([+ fetchAll<RpcPlanningRow>(() =>+ client+ .rpc("get_purchasing_planning", {+ company_id: companyId,+ location_id: location.id,+ periods: periodIds+ })+ .order("id")+ ),+ fetchAll<ProductionPlanningRow>(() =>+ client+ .rpc("get_production_planning", {+ company_id: companyId,+ location_id: location.id,+ periods: periodIds+ })+ .order("id")+ )+ ]);+ if (purchasing.error) throw new Error(purchasing.error.message);+ if (production.error) throw new Error(production.error.message);++ const process = (+ row: RpcPlanningRow | ProductionPlanningRow,+ kind: "Order" | "Make"+ ) => {+ const itemLocationKey = `${row.id}${KEY_SEP}${location.id}`;+ const openOrders = openOrdersByItemLocation.get(itemLocationKey) ?? [];++ // change actions against real open documents+ const demandMap =+ demandByItemLocation.get(itemLocationKey) ?? new Map<string, number>();+ const demandPeriods = periods+ .filter((p) => (demandMap.get(p.id) ?? 0) > 0)+ .map((p) => ({+ periodId: p.id,+ startDate: p.startDate,+ quantity: demandMap.get(p.id) ?? 0+ }));++ const coverageInput = {+ onHand: onHandByItemLocation.get(itemLocationKey) ?? 0,+ demandPeriods,+ openOrders,+ periods,+ policyFloor: policyFloorFor(row)+ };+ const changeActions = deriveChangeActions({+ ...coverageInput,+ toleranceDays,+ todayDate+ });++ // new-supply suggestions from the shared sizing (same math as the grid),+ // sized on the projection with every open order counted from the week+ // it is needed: every Expedite above done, and an order late within the+ // tolerance counted as on time, as the reschedule check judged it+ let sizing: ChangeCandidate[] = [];+ if (row.supersessionMode === "Stock Only") {+ const shortfall = Math.max(0, Number(row.quantityToOrder) || 0);+ const firstPeriod = periods[0];+ if (shortfall > 0 && firstPeriod) {+ const startDate = parseDate(firstPeriod.startDate)+ .subtract({ days: Number(row.leadTime) || 0 })+ .toString();+ sizing = [+ {+ type: kind,+ periodId: firstPeriod.id,+ suggestedQuantity: shortfall,+ suggestedDate: firstPeriod.startDate,+ horizonDate: firstPeriod.startDate,+ latestOrderDate: startDate,+ isASAP: daysBetween(startDate, todayDate) < 0,+ purchaseOrderLineId: null,+ jobId: null,+ requiresManualAction: false,+ supplierId:+ kind === "Order"+ ? ((row as RpcPlanningRow).preferredSupplierId ?? null)+ : null,+ policyName: "Stock Only",+ reason: "Below the minimum reserve for a superseded item",+ triggerValues: {+ projectedStock: Number(row.quantityOnHand) || 0,+ reorderPoint: Number(row.minimumReserveQuantity) || 0,+ leadTime: Number(row.leadTime) || 0+ }+ }+ ];+ }+ } else {+ const projections = projectionsWithExpedites({+ projections: periods.map((_, i) => {+ const value = row[`week${i + 1}` as keyof typeof row];+ return Number(value) || 0;+ }),+ periods,+ changeActions,+ openOrders,+ firstNeedPeriods: firstNeedPeriodByOrder(coverageInput)+ });+ sizing = computePlanningOrders({+ reorderingPolicy: row.reorderingPolicy,+ periods,+ projections,+ todayDate,+ params: {+ reorderPoint: Number(row.reorderPoint) || 0,+ reorderQuantity: Number(row.reorderQuantity) || 0,+ minimumOrderQuantity: Number(row.minimumOrderQuantity) || 0,+ maximumOrderQuantity: Number(row.maximumOrderQuantity) || 0,+ orderMultiple: Number(row.orderMultiple) || 0,+ lotSize: Number(row.lotSize) || 0,+ maximumInventoryQuantity: Number(row.maximumInventoryQuantity) || 0,+ demandAccumulationPeriod: Number(row.demandAccumulationPeriod) || 1,+ demandAccumulationSafetyStock:+ Number(row.demandAccumulationSafetyStock) || 0,+ leadTime: Number(row.leadTime) || 0+ }+ }).map((order) => ({+ type: kind,+ periodId: order.periodId,+ suggestedQuantity: order.quantity,+ suggestedDate: order.dueDate,+ horizonDate: order.dueDate,+ latestOrderDate: order.startDate,+ isASAP: order.isASAP,+ purchaseOrderLineId: null,+ jobId: null,+ requiresManualAction: false,+ supplierId:+ kind === "Order"+ ? ((row as RpcPlanningRow).preferredSupplierId ?? null)+ : null,+ policyName: order.policyName,+ reason: null,+ triggerValues: order.triggerValues+ }));+ }++ const merged = convertOrdersToIncreases({+ sizingCandidates: sizing,+ openOrders,+ changeActions,+ toleranceDays,+ todayDate+ });++ // Lot-size splitting can emit several new-supply suggestions in one+ // period; persist ONE action per (type, period) with the summed quantity+ // — the natural key would otherwise collide and silently drop batches.+ const aggregated = new Map<string, ChangeCandidate>();+ const passthrough: ChangeCandidate[] = [];+ for (const candidate of merged) {+ const isNewSupply =+ (candidate.type === "Order" || candidate.type === "Make") &&+ !candidate.purchaseOrderLineId &&+ !candidate.jobId;+ if (!isNewSupply) {+ passthrough.push(candidate);+ continue;+ }+ const key = `${candidate.type}${KEY_SEP}${candidate.periodId}`;+ const current = aggregated.get(key);+ if (current) {+ current.suggestedQuantity += candidate.suggestedQuantity;+ current.isASAP = current.isASAP || candidate.isASAP;+ current.suggestedDate = earlierDate(+ current.suggestedDate,+ candidate.suggestedDate+ );+ current.horizonDate = earlierDate(+ current.horizonDate,+ candidate.horizonDate+ );+ if (candidate.latestOrderDate) {+ current.latestOrderDate = current.latestOrderDate+ ? earlierDate(current.latestOrderDate, candidate.latestOrderDate)+ : candidate.latestOrderDate;+ }+ } else {+ aggregated.set(key, { ...candidate });+ }+ }++ const releaseActions = deriveReleaseActions({+ openOrders,+ changeActions,+ periods,+ todayDate+ });++ const assignee = resolveAssignee(row.id, location.id);+ for (const action of [+ ...aggregated.values(),+ ...passthrough,+ ...changeActions,+ ...releaseActions+ ]) {+ if (!action.periodId || !periodById.has(action.periodId)) continue;+ candidates.push({+ ...action,+ // Persist boundary: every source above is float arithmetic.+ suggestedQuantity: round(action.suggestedQuantity),+ itemId: row.id,+ locationId: location.id,+ assignee+ });+ }+ };++ for (const row of purchasing.data ?? []) process(row, "Order");+ for (const row of production.data ?? []) process(row, "Make");+ }++ // ── diff-write. One transaction holds a per-company advisory lock across+ // the read and the write: two runs for one company can overlap (the cron+ // racing a route-triggered run), and both reading "no row" for a natural+ // key then inserting fails the second on planningAction_natural_key_idx —+ // which rolls back the whole write. Under the lock the second run reads+ // the first run's rows and updates them in place instead.+ const diff = await db.transaction().execute(async (trx) => {+ await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`planning-actions:${companyId}`}, 0))`.execute(+ trx+ );++ const existingRows = await trx+ .selectFrom("planningAction")+ .select([+ "id",+ "itemId",+ "locationId",+ "periodId",+ "type",+ "status",+ "suggestedQuantity",+ "suggestedDate",+ "horizonDate",+ "latestOrderDate",+ "isASAP",+ "purchaseOrderLineId",+ "jobId",+ "requiresManualAction",+ "supplierId",+ "policyName",+ "reason",+ "triggerValues",+ "assignee",+ "assigneeOverridden"+ ])+ .where("companyId", "=", companyId)+ .where("status", "!=", "Actioned")+ .execute();++ const existing: ExistingPlanningAction[] = existingRows.map((row) => ({+ ...row,+ type: row.type as PlanningActionType,+ status: row.status as "Open" | "Dismissed",+ suggestedQuantity: Number(row.suggestedQuantity),+ suggestedDate: toIsoDate(row.suggestedDate as unknown as string | Date)!,+ horizonDate: toIsoDate(row.horizonDate as unknown as string | Date)!,+ latestOrderDate: row.latestOrderDate+ ? toIsoDate(row.latestOrderDate as unknown as string | Date)+ : null,+ triggerValues: row.triggerValues ?? null+ }));++ const diff = diffPlanningActions({+ existing,+ candidates,+ periods,+ toleranceDays+ });++ await writePlanningActionDiff(trx, {+ companyId,+ userId,+ diff,+ updatedAt: datetime.timestamp()+ });++ return diff;+ });++ logger.info("planning actions written", {+ companyId,+ inserted: diff.inserts.length,+ updated: diff.updates.length,+ deleted: diff.deleteIds.length+ });++ return {+ inserted: diff.inserts.length,+ updated: diff.updates.length,+ deleted: diff.deleteIds.length+ };+}diff --git a/packages/planning/src/mrp/planning-actions.write.test.ts b/packages/planning/src/mrp/planning-actions.write.test.tsnew file mode 100644index 0000000000..b5912a60ed--- /dev/null+++ b/packages/planning/src/mrp/planning-actions.write.test.ts@@ -0,0 +1,156 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { DB } from "@carbon/database/client";+import {+ type CompiledQuery,+ type DatabaseConnection,+ DummyDriver,+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler,+ type QueryResult+} from "kysely";+import { describe, expect, it } from "vitest";+import {+ type PlanningActionDiff,+ writePlanningActionDiff+} from "./planning-actions";++// The Postgres wire is the boundary: every statement the writer sends is+// recorded as compiled SQL with its parameters.+class RecordingDriver extends DummyDriver {+ readonly sent: CompiledQuery[] = [];+ override async acquireConnection(): Promise<DatabaseConnection> {+ return {+ executeQuery: async <R>(+ query: CompiledQuery+ ): Promise<QueryResult<R>> => {+ this.sent.push(query);+ return { rows: [] };+ },+ // biome-ignore lint/correctness/useYield: never streamed+ streamQuery: async function* () {+ throw new Error("not streamed");+ }+ };+ }+}++function database() {+ const driver = new RecordingDriver();+ const db = new Kysely<DB>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => driver,+ createIntrospector: (k) => new PostgresIntrospector(k),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+ });+ return { db, driver };+}++const emptyDiff: PlanningActionDiff = {+ inserts: [],+ updates: [],+ deleteIds: []+};++async function write(diff: Partial<PlanningActionDiff>) {+ const { db, driver } = database();+ await writePlanningActionDiff(db, {+ companyId: "c1",+ userId: "u1",+ diff: { ...emptyDiff, ...diff },+ updatedAt: "2026-10-06T00:00:00.000Z"+ });+ return driver.sent;+}++describe("writePlanningActionDiff", () => {+ // The run reads the actions, then writes its diff. A row applied in between+ // was deleted, or reopened by a `status: "Open"` patch.+ it("never deletes an applied action", async () => {+ const [statement] = await write({ deleteIds: ["a1", "a2"] });+ expect(statement?.sql).toMatch(/^delete from "planningAction"/);+ expect(statement?.sql).toContain('"status" != $');+ expect(statement?.parameters).toContain("Actioned");+ expect(statement?.parameters).toContain("c1");+ });++ it("never updates an applied action", async () => {+ const [statement] = await write({+ updates: [{ id: "a1", patch: { status: "Open" } }]+ });+ expect(statement?.sql).toContain(`t."status" <> 'Actioned'`);+ expect(statement?.sql).toContain(`t."companyId" = $`);+ });++ // One UPDATE per row was thousands of round trips on the weekly roll.+ it("sends one statement per set of changed columns, not per row", async () => {+ const sent = await write({+ updates: [+ { id: "a1", patch: { periodId: "p2" } },+ { id: "a2", patch: { periodId: "p3" } },+ { id: "a3", patch: { periodId: "p4" } },+ { id: "a4", patch: { suggestedQuantity: 12, status: "Open" } }+ ]+ });+ expect(sent).toHaveLength(2);++ const periodOnly = sent.find((q) => !q.sql.includes("suggestedQuantity"));+ expect(periodOnly?.sql).toContain(`"periodId" = v."periodId"::text`);+ expect(periodOnly?.parameters).toEqual(+ expect.arrayContaining(["a1", "p2", "a2", "p3", "a3", "p4"])+ );++ const reopen = sent.find((q) => q.sql.includes("suggestedQuantity"));+ expect(reopen?.sql).toContain(+ `"status" = v."status"::"planningActionStatus"`+ );+ expect(reopen?.sql).toContain(+ `"suggestedQuantity" = v."suggestedQuantity"::numeric`+ );+ // Only the patched columns: a period-only row keeps its stored quantity.+ expect(periodOnly?.sql).not.toContain("suggestedQuantity");+ });++ // The diff skips an overridden assignee when it READS the row; a planner+ // who assigns between that read and the write (Assign takes no lock) must+ // still win, so the statement re-checks the flag on the row itself.+ it("keeps a planner's overridden assignee in the statement itself", async () => {+ const [statement] = await write({+ updates: [{ id: "a1", patch: { assignee: "u2", suggestedQuantity: 3 } }]+ });+ expect(statement?.sql).toContain(+ `"assignee" = CASE WHEN t."assigneeOverridden" THEN t."assignee" ELSE v."assignee"::text END`+ );+ // The other columns of the same statement still update unconditionally.+ expect(statement?.sql).toContain(+ `"suggestedQuantity" = v."suggestedQuantity"::numeric`+ );+ });++ it("writes trigger values as JSON", async () => {+ const [statement] = await write({+ updates: [{ id: "a1", patch: { triggerValues: { reorderPoint: 5 } } }]+ });+ expect(statement?.sql).toContain(`"triggerValues"::jsonb`);+ expect(statement?.parameters).toContain('{"reorderPoint":5}');+ });++ it("refuses a patch column it has no type for, before writing", async () => {+ const { db, driver } = database();+ await expect(+ writePlanningActionDiff(db, {+ companyId: "c1",+ userId: "u1",+ diff: { ...emptyDiff, updates: [{ id: "a1", patch: { bogus: 1 } }] },+ updatedAt: "2026-10-06T00:00:00.000Z"+ })+ ).rejects.toThrow(/bogus/);+ expect(driver.sent).toHaveLength(0);+ });+});diff --git a/packages/planning/src/mrp/responsible-employee.test.ts b/packages/planning/src/mrp/responsible-employee.test.tsnew file mode 100644index 0000000000..81ccd8e804--- /dev/null+++ b/packages/planning/src/mrp/responsible-employee.test.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { resolveResponsibleEmployee } from "./responsible-employee";++describe("resolveResponsibleEmployee", () => {+ it("item overrides group, location, and company", () => {+ expect(+ resolveResponsibleEmployee({+ item: "item-owner",+ itemGroup: "group-owner",+ location: "location-owner",+ company: "company-owner"+ })+ ).toBe("item-owner");+ });++ it("location-specific item group beats location and company", () => {+ expect(+ resolveResponsibleEmployee({+ item: null,+ itemGroup: "group-owner",+ location: "location-owner",+ company: "company-owner"+ })+ ).toBe("group-owner");+ });++ it("location beats company", () => {+ expect(+ resolveResponsibleEmployee({+ item: null,+ itemGroup: null,+ location: "location-owner",+ company: "company-owner"+ })+ ).toBe("location-owner");+ });++ it("falls back to the company default", () => {+ expect(+ resolveResponsibleEmployee({+ item: null,+ itemGroup: null,+ location: null,+ company: "company-owner"+ })+ ).toBe("company-owner");+ });++ it("returns null (Unassigned) when every rung is empty", () => {+ expect(+ resolveResponsibleEmployee({+ item: null,+ itemGroup: null,+ location: null,+ company: null+ })+ ).toBeNull();+ });+});diff --git a/packages/planning/src/mrp/responsible-employee.ts b/packages/planning/src/mrp/responsible-employee.tsnew file mode 100644index 0000000000..b5209ae724--- /dev/null+++ b/packages/planning/src/mrp/responsible-employee.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// responsibleEmployee ownership ladder (spec §P1.3): resolve who owns an+// item+location's planning actions, most-specific first. Drawn as a tree it is+// company default → location → location-specific item group → item; resolution+// walks the rungs leaf-first and returns the first non-null.+//+// This is a hierarchical inheritance tree, NOT a classification matrix: each+// rung stores at most one employee, and the item-group rung is looked up by+// (locationId, itemPostingGroupId) from the sparse itemPostingGroupResponsibility+// table — the same group can have a different owner at each location.++import type { DB } from "@carbon/database/client";+import type { Kysely } from "kysely";++const KEY_SEP = "\x1f";++export type ResponsibleEmployeeRungs = {+ /** itemPlanning.responsibleEmployee for (itemId, locationId) — leaf override */+ item: string | null;+ /** itemPostingGroupResponsibility for (locationId, group) — location-specific */+ itemGroup: string | null;+ /** location.responsibleEmployee */+ location: string | null;+ /** companySettings.defaultResponsibleEmployee */+ company: string | null;+};++export function resolveResponsibleEmployee(+ rungs: ResponsibleEmployeeRungs+): string | null {+ return (+ rungs.item ?? rungs.itemGroup ?? rungs.location ?? rungs.company ?? null+ );+}++export type ResponsibleEmployeeResolver = (+ itemId: string,+ locationId: string+) => string | null;++/**+ * Bulk-load every rung for a company in a handful of set queries (never+ * per-item), returning a resolver closure the action generator calls per+ * (itemId, locationId).+ */+export async function loadResponsibleEmployeeResolver(+ db: Kysely<DB>,+ companyId: string+): Promise<ResponsibleEmployeeResolver> {+ const [+ itemPlanningRows,+ itemGroups,+ groupResponsibilities,+ locations,+ settings+ ] = await Promise.all([+ db+ .selectFrom("itemPlanning")+ .select(["itemId", "locationId", "responsibleEmployee"])+ .where("companyId", "=", companyId)+ .where("responsibleEmployee", "is not", null)+ .execute(),+ db+ .selectFrom("itemCost")+ .select(["itemId", "itemPostingGroupId"])+ .where("companyId", "=", companyId)+ .where("itemPostingGroupId", "is not", null)+ .execute(),+ db+ .selectFrom("itemPostingGroupResponsibility")+ .select(["locationId", "itemPostingGroupId", "responsibleEmployee"])+ .where("companyId", "=", companyId)+ .where("responsibleEmployee", "is not", null)+ .execute(),+ db+ .selectFrom("location")+ .select(["id", "responsibleEmployee"])+ .where("companyId", "=", companyId)+ .execute(),+ db+ .selectFrom("companySettings")+ .select(["defaultResponsibleEmployee"])+ .where("id", "=", companyId)+ .executeTakeFirst()+ ]);++ const itemRung = new Map<string, string>();+ for (const row of itemPlanningRows) {+ if (row.responsibleEmployee) {+ itemRung.set(+ `${row.itemId}${KEY_SEP}${row.locationId}`,+ row.responsibleEmployee+ );+ }+ }++ const groupByItem = new Map<string, string>();+ for (const row of itemGroups) {+ if (row.itemPostingGroupId) {+ groupByItem.set(row.itemId, row.itemPostingGroupId);+ }+ }++ const groupRung = new Map<string, string>();+ for (const row of groupResponsibilities) {+ if (row.responsibleEmployee) {+ groupRung.set(+ `${row.locationId}${KEY_SEP}${row.itemPostingGroupId}`,+ row.responsibleEmployee+ );+ }+ }++ const locationRung = new Map<string, string | null>();+ for (const row of locations) {+ locationRung.set(row.id, row.responsibleEmployee ?? null);+ }++ const companyDefault = settings?.defaultResponsibleEmployee ?? null;++ return (itemId: string, locationId: string) => {+ const group = groupByItem.get(itemId);+ return resolveResponsibleEmployee({+ item: itemRung.get(`${itemId}${KEY_SEP}${locationId}`) ?? null,+ itemGroup: group+ ? (groupRung.get(`${locationId}${KEY_SEP}${group}`) ?? null)+ : null,+ location: locationRung.get(locationId) ?? null,+ company: companyDefault+ });+ };+}diff --git a/packages/planning/src/mrp/supply-date.test.ts b/packages/planning/src/mrp/supply-date.test.tsnew file mode 100644index 0000000000..07e6a3c7be--- /dev/null+++ b/packages/planning/src/mrp/supply-date.test.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ jobCompletionDate,+ purchaseOrderLineArrivalDate+} from "./supply-date.ts";++const TODAY = "2026-10-01";++describe("purchaseOrderLineArrivalDate", () => {+ it("uses the supplier's promised date when there is one", () => {+ expect(+ purchaseOrderLineArrivalDate(+ {+ promisedDate: "2026-11-20",+ dueDate: "2026-11-01",+ orderDate: "2026-10-01",+ leadTime: 5+ },+ TODAY+ )+ ).toBe("2026-11-20");+ });++ it("uses the required date when nothing is promised — the field planning writes", () => {+ expect(+ purchaseOrderLineArrivalDate(+ { promisedDate: null, dueDate: "2026-11-01", orderDate: "2026-10-01" },+ TODAY+ )+ ).toBe("2026-11-01");+ });++ it("falls back to order date + lead time", () => {+ expect(+ purchaseOrderLineArrivalDate(+ { orderDate: "2026-10-10", leadTime: 14 },+ TODAY+ )+ ).toBe("2026-10-24");+ });++ it("assumes 7 days when the item has no lead time, and 0 means 0", () => {+ expect(+ purchaseOrderLineArrivalDate({ orderDate: "2026-10-10" }, TODAY)+ ).toBe("2026-10-17");+ expect(+ purchaseOrderLineArrivalDate(+ { orderDate: "2026-10-10", leadTime: 0 },+ TODAY+ )+ ).toBe("2026-10-10");+ });++ it("counts from today when the order has no date yet", () => {+ expect(purchaseOrderLineArrivalDate({ leadTime: 3 }, TODAY)).toBe(+ "2026-10-04"+ );+ });+});++// The reschedule check skipped a job with no due date while the projection+// counted it as supply, so the two saw different supply and the job itself+// was never offered a Cancel, Defer or Expedite.+describe("jobCompletionDate", () => {+ it("uses the job's due date", () => {+ expect(+ jobCompletionDate(+ { dueDate: "2026-11-20", deadlineType: "No Deadline" },+ TODAY+ )+ ).toBe("2026-11-20");+ });++ it("assumes 30 days out for an undated No Deadline job", () => {+ expect(+ jobCompletionDate({ dueDate: null, deadlineType: "No Deadline" }, TODAY)+ ).toBe("2026-10-31");+ });++ it("assumes today for any other undated job", () => {+ expect(+ jobCompletionDate({ dueDate: null, deadlineType: "ASAP" }, TODAY)+ ).toBe(TODAY);+ expect(jobCompletionDate({}, TODAY)).toBe(TODAY);+ });+});diff --git a/packages/planning/src/mrp/supply-date.ts b/packages/planning/src/mrp/supply-date.tsnew file mode 100644index 0000000000..399db23978--- /dev/null+++ b/packages/planning/src/mrp/supply-date.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+// When open supply (a purchase order line, a job) arrives, for planning purposes.+//+// ONE definition each, used by the projection (`runMrp`) and by the reschedule+// check (`generatePlanningActions`). They used to answer this separately — the+// projection ignored the line's required date, the check read it first — so+// applying an Expedite (which writes the required date) moved the action and+// left the projected shortage where it was. Jobs drifted the same way: the+// projection dated an undated job, the check skipped it.++import { parseDate } from "@internationalized/date";++/** Lead time assumed for a line whose item has none recorded. */+const DEFAULT_LEAD_TIME_DAYS = 7;++export type PurchaseOrderLineDates = {+ /** The supplier's confirmed date (line, else the order's delivery). */+ promisedDate?: string | null;+ /** The date we asked for: `purchaseOrderLine.requiredDate`. */+ dueDate?: string | null;+ orderDate?: string | null;+ leadTime?: number | null;+};++/**+ * The ISO date supply from a PO line is expected, most reliable source first:+ * what the supplier promised, else what we required, else order date + lead+ * time (today + lead time when the order has no date yet).+ *+ * A promise outranks the requirement because it is when the goods actually+ * come; a line still being planned has no promise, so its required date — the+ * field the planning grid writes and edits — is what moves it.+ */+export function purchaseOrderLineArrivalDate(+ line: PurchaseOrderLineDates,+ todayIso: string+): string {+ if (line.promisedDate) return line.promisedDate;+ if (line.dueDate) return line.dueDate;+ return parseDate(line.orderDate ?? todayIso)+ .add({ days: line.leadTime ?? DEFAULT_LEAD_TIME_DAYS })+ .toString();+}++/** How far out a job with no deadline is assumed to finish. */+const NO_DEADLINE_DAYS = 30;++export type JobDates = {+ dueDate?: string | null;+ deadlineType?: Database["public"]["Enums"]["deadlineType"] | null;+};++/**+ * The ISO date a job's output is expected: its due date, else today + 30 days+ * for a "No Deadline" job (the default on a new job), else today (an ASAP or+ * hard-deadline job that has not been given its date yet).+ */+export function jobCompletionDate(job: JobDates, todayIso: string): string {+ if (job.dueDate) return job.dueDate;+ if (job.deadlineType === "No Deadline") {+ return parseDate(todayIso).add({ days: NO_DEADLINE_DAYS }).toString();+ }+ return todayIso;+}diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.mdindex b4795adc3c..af8c9e9772 100644--- a/packages/react/AGENTS.md+++ b/packages/react/AGENTS.md@@ -9,6 +9,7 @@ Shared UI component library — primitives, layout, data display, and overlays b- **Components live flat in `src/`** (e.g. `src/Button.tsx`), not under a `components/` subdirectory. Follow this convention for new components.- **Concentric border radius**: outer radius = inner radius + padding. Card shell is `rounded-lg`; don't re-add borders/radius on CardContent.- **Popover inside Drawer/Dialog**: `stopPropagation` on `onWheel`/`onTouchMove` of `PopoverContent` to prevent scroll-lock from swallowing events.+- **Drawer closing animation**: the panel slides out only when the `Drawer` stays mounted and its `open` prop goes false. `{item && <Drawer open />}` removes it in the same render, so nothing animates — keep the record while it closes (`useDrawerItem` in the ERP, `~/hooks`). The positioning div in `DrawerPortal` runs a no-op exit animation matched to the panel's closing duration; Radix unmounts the portal as soon as that div stops animating, so change the two durations together.## Ask First@@ -41,6 +42,7 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";- **Choice screens**: `ChoiceCardGroup` (card radios, `autoFocus` focuses the selected card) and `RadioGroupButton` (radio styled as a secondary Button) give one tab stop + arrow-key select; Enter stays free for the screen's continue action- **Layout**: `VStack` / `HStack` with numeric `spacing` prop (maps to `space-y-*`/`space-x-*`)- **Overlays**: `Drawer`, `Modal`, `ModalDrawer` (unified drawer/modal), `BottomSheet`, `Popover`. A controlled `Modal`/`Drawer` with no `onOpenChange` cannot be dismissed and shows no close button; never pass a handler that does nothing (`no-noop-open-change` check). A route rendered as a modal or drawer closes with `useCloseRoute()` (back when this tab has history, else the parent route), not `navigate(-1)`+- **Status**: `iconOnly` renders just the coloured icon, with the label in an always-on tooltip and as the `aria-label` (string children only) — for dense rows and narrow drawers. `TooltipContent` takes `anchor` to position against a different element than the trigger, when one tooltip serves many small hover targets (a strip of bars)- **App nav**: `NavRail` is the primary left nav of both the ERP and MES shells (56px icon rail, expands after a 150ms mouse hover or when pinned via `SidebarProvider` (⌘B unless `keyboardShortcut={false}`, as in the ERP), left drawer below md that closes itself on navigation). Optional `header` (use `NavRailBrand` for a logo + name) and `footer` slots; `NavRailGroup` adds a titled section that shows as a divider while collapsed. Entries are `NavRailItem` (a button, or `asChild` for a trigger/link) and `NavRailLink`; `label` is a string and doubles as the accessible name. A Radix menu/popover opened from a `NavRailItem` keeps the rail as it was (open or collapsed) until it closes. Render inside `SidebarProvider`; the shadcn-style `Sidebar*` primitives remain for other layouts- **Links that prefetch**: `PrefetchLink` is a React Router `Link` that prefetches its destination when the pointer goes down on it. Use it instead of `<Link prefetch="intent">`, which prefetches on a 100 ms hover and so runs a page's loaders for every row the mouse passes over. The click reuses the prefetch only because `prefetchCacheMiddleware` (`@carbon/utils`, in each app's root `middleware`) gives a prefetch response a few seconds of private cache; without it both requests reach the server and the click waits behind the prefetch. `NavRailLink` and both apps' `Hyperlink` already use it- **Record outlet**: `RecordOutlet` is the `<Outlet>` of every route under `/x`. It remounts the page inside it when that page is shown for a different record (the params of the route in the outlet, not of a drawer below it), so nothing seeded from the previous record survives. A plain `<Outlet>` there fails the `no-bare-outlet` checkdiff --git a/packages/react/src/Drawer.tsx b/packages/react/src/Drawer.tsxindex 9ef529e5e5..36b9688342 100644--- a/packages/react/src/Drawer.tsx+++ b/packages/react/src/Drawer.tsx@@ -25,17 +25,26 @@ const DrawerTrigger = DialogPrimitive.Trigger;const DrawerCloseButton = DialogPrimitive.Close;-const portalVariants = cva("fixed inset-0 z-50 flex p-3", {- variants: {- position: {- top: "items-start",- bottom: "items-end",- left: "justify-start",- right: "justify-end"- }- },- defaultVariants: { position: "right" }-});+// Radix keeps a closing dialog mounted only while the element it wraps is+// animating, and what the portal wraps is this positioning div, not the panel.+// So the div runs a no-op exit animation for as long as its panel is closing+// (`animate-out` with no modifiers animates to the element's own state);+// without it the portal removes the panel before it can slide out. The+// duration must match the panel's closing duration below.+const portalVariants = cva(+ "fixed inset-0 z-50 flex p-3 [&:has(>[role=dialog][data-state=closed])]:animate-out [&:has(>[role=dialog][data-state=closed])]:duration-200",+ {+ variants: {+ position: {+ top: "items-start",+ bottom: "items-end",+ left: "justify-start",+ right: "justify-end"+ }+ },+ defaultVariants: { position: "right" }+ }+);interface DrawerPortalPropsextends DialogPrimitive.DialogPortalProps,diff --git a/packages/react/src/Status.tsx b/packages/react/src/Status.tsxindex 923f97c73d..32e06e5a6d 100644--- a/packages/react/src/Status.tsx+++ b/packages/react/src/Status.tsx@@ -20,6 +20,13 @@ type StatusProps = ComponentProps<"div"> & {color?: "green" | "orange" | "red" | "yellow" | "blue" | "gray" | "purple";tooltip?: ReactNode;disableTooltip?: boolean;+ /**+ * Show the status as its icon alone, in the status colour, with the label+ * in the tooltip. For places that have no width for the pill — a dense table+ * row, a narrow drawer — where the status is context, not the headline. The+ * tooltip is the only place the label is readable, so it is always on.+ */+ iconOnly?: boolean;};const getStatusIcon = (color: string) => {@@ -47,21 +54,29 @@ const Status = ({children,tooltip,disableTooltip,+ iconOnly = false,className,...props}: StatusProps) => {const badge = (<Badgevariant={color}- className={cn("inline-flex items-center gap-1", className)}+ className={cn(+ "inline-flex items-center gap-1",+ iconOnly && "shrink-0 px-1.5",+ className+ )}+ aria-label={+ iconOnly && typeof children === "string" ? children : undefined+ }{...props}>{getStatusIcon(color)}- {children}+ {!iconOnly && children}</Badge>);- if (disableTooltip) return badge;+ if (disableTooltip && !iconOnly) return badge;return (<Tooltip>diff --git a/packages/react/src/Tabs.tsx b/packages/react/src/Tabs.tsxindex adc2497ea0..7b83d30278 100644--- a/packages/react/src/Tabs.tsx+++ b/packages/react/src/Tabs.tsx@@ -22,7 +22,7 @@ const TabsList = forwardRef<// No fixed height and no border — p-1 sizes the box, so the space// around the triggers is uniform on every side (a fixed h-* squeezed// them, and a border-b read as an extra pixel of bottom padding)- "inline-flex items-center justify-center rounded-[0.5rem] bg-muted p-1 text-muted-foreground border border-border",+ "inline-flex items-center justify-center rounded-[0.5rem] bg-muted p-0.5 text-muted-foreground border border-border",className)}{...props}diff --git a/packages/react/src/Tooltip.tsx b/packages/react/src/Tooltip.tsxindex 2a54ab0aa9..d6d195075b 100644--- a/packages/react/src/Tooltip.tsx+++ b/packages/react/src/Tooltip.tsx@@ -81,10 +81,15 @@ const TooltipTrigger = forwardRef<HTMLButtonElement, TriggerProps>();TooltipTrigger.displayName = "TooltipTrigger";+/**+ * `anchor` positions the popup against a different element than the trigger.+ * Use it when one tooltip serves many small hover targets inside its trigger+ * (a strip of bars): the content follows the hovered target, not the strip.+ */type ContentProps = TooltipPrimitive.Popup.Props &Pick<TooltipPrimitive.Positioner.Props,- "side" | "sideOffset" | "align" | "alignOffset"+ "side" | "sideOffset" | "align" | "alignOffset" | "anchor"> & {/*** Portal to `document.body` and paint above other overlays. Opt in only for a@@ -125,6 +130,7 @@ const TooltipContent = forwardRef<HTMLDivElement, ContentProps>(sideOffset = 4,align = "center",alignOffset = 0,+ anchor,elevated = false,...props},@@ -140,6 +146,7 @@ const TooltipContent = forwardRef<HTMLDivElement, ContentProps>(sideOffset={sideOffset}align={align}alignOffset={alignOffset}+ anchor={anchor}className={elevated ? "z-[9999]" : "z-50"}><TooltipPrimitive.Popupdiff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.mdindex 5da847ed56..48f4877e27 100644--- a/packages/utils/AGENTS.md+++ b/packages/utils/AGENTS.md@@ -46,10 +46,9 @@ pnpm --filter @carbon/utils typecheck| `journal-dimensions` / `intercompany-capture` | Automatic `journalLineDimension` rows for posted journal lines; intercompany posting-line classification || `short-close` | Short-close-aware billable / remaining-to-invoice PO line quantities || `calculate-due-date` | `calculateDueDate` / `DEFAULT_PAYMENT_TERM` — an invoice's due date from its payment term (shared by the ERP and invoice posting) |-| `async` | Promise helpers used as a namespace (`import { async } from "@carbon/utils"`): `async.map` (bounded `concurrency`, input order kept), `async.all`, `async.allSettled`, `async.background(task, onError)` (fire-and-forget with a mandatory error handler) — use these over bare `Promise.all` over rows, void async IIFEs, or unhandled `.then` chains |-| `errors` | `getErrorMessage(error, fallback)` — the error's own message, else the caller's copy (server functions leave `message` empty for data-layer failures so the fallback wins) |-| `arrays` | Array manipulation, grouping, deduplication || `async` | The `async` object: `Promise.all`, `Promise.allSettled` and `items.map` with a limit on how many run at once (`DEFAULT_CONCURRENCY`, 8, unless `{ concurrency }` says otherwise). `map(items, mapper)` follows p-map, `all(tasks)` and `allSettled(tasks)` take FUNCTIONS (a promise is already running) and keep the tuple's types, `limit(n)` follows p-limit. After a failure `map` / `all` start nothing further. Database calls inside a request need no limit of their own — the client `requirePermissions` returns has at most 8 in flight. `background(task, onError)` is fire-and-forget with a required error handler. `onBackground(hook)` registers what keeps the process alive for that work — both apps register Vercel's `waitUntil` in `entry.server.tsx` — so use `background` (never a bare unawaited promise) for anything a request leaves running |+| `errors` | `getErrorMessage(error, fallback)` — the error's own message, else the caller's copy (server functions leave `message` empty for data-layer failures so the fallback wins); `isUniqueViolation(error)` / `isForeignKeyViolation(error)` — the Postgres SQLSTATE checks (23505 / 23503) on a Supabase result or a thrown Kysely error; `getDatabaseErrorMessage(error, fallback, { duplicate?, referenced? })` — the caller's copy for the constraint Postgres named |+| `arrays` | Array manipulation, grouping, deduplication || `bom` | Bill of Materials traversal and level computation || `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`); `HOUR_MS`/`DAY_MS` millisecond constants for instant arithmetic || `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Pair with `getCompanyTimeZone` / `getLocationTimeZone` from `@carbon/database` |@@ -57,6 +56,7 @@ pnpm --filter @carbon/utils typecheck| `hash` | The repo's stable content hashes — `fnv1a32`/`fnv1a64` (cache and idempotency keys) and `getBucket`. Browser-safe; never add `node:crypto` here || `math` | `clamp`/`lerp`/`inverseLerp` only — it re-exports nothing || `mode` | Light / dark / system. `getModeFromCookies` resolves the root loader's `mode` (what to render) and `modePreference` (what the user chose): the explicit `mode` cookie wins, else the OS hint cookie, else light. `colorSchemeHintScript` is the inline `<head>` script that writes the OS hint and reloads once when a `system` user was rendered in the wrong mode. The browser-side halves (`useMode`, `useModePreference`, `getSystemMode`) live in `@carbon/react` |+| `planning-sizing` | `computePlanningOrders` — reorder-quantity sizing for the four reordering policies (`ComputePlanningOrdersInput` — `{ reorderingPolicy, periods, projections, todayDate, params: PlanningSizingParams }` — in, `PlanningOrderSuggestion[]` out). Pure and clock-free (`todayDate` is injected). Shared by the MRP engine and the item planning tab's `ItemReorderPolicy`, so both size an order the same way; `planning-sizing.test.ts` pins it against hand-computed results of the SQL `calculate_quantity_to_order` || `precision` | The whole numeric-precision API (re-exported from `@carbon/database/precision`): `SCALE`, `EPSILON`, `RoundingMode`, `round`, `distributeRoundingResidual`, `scrapAllowance`, `applyRate`, `deriveRate`, `isBalanced`, `assertBalanced` || `format` | The ONLY place display/input digit counts are chosen: `moneyFormatOptions` (settlement — the currency's decimals are floor AND ceiling), `rateFormatOptions` (per-unit RATE — those decimals are only the floor, ceiling is `SCALE`), the `PERCENT_FORMAT` / `PERCENT_POINTS_FORMAT` / `SCALE_FORMAT` constants, `cldrCurrencyDecimals`, their `format*` helpers, and `INPUT_FORMAT` / `INPUT_STEP` for editable fields. Call sites pick a KIND, never a digit count || `string` | Slugify, truncate, camelCase/titleCase conversions |diff --git a/packages/utils/src/errors.test.ts b/packages/utils/src/errors.test.tsnew file mode 100644index 0000000000..1efeedae46--- /dev/null+++ b/packages/utils/src/errors.test.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ getDatabaseErrorMessage,+ isForeignKeyViolation,+ isUniqueViolation+} from "./errors";++describe("isUniqueViolation / isForeignKeyViolation", () => {+ it("reads the SQLSTATE code off the error", () => {+ expect(isUniqueViolation({ code: "23505" })).toBe(true);+ expect(isUniqueViolation({ code: "23503" })).toBe(false);+ expect(isForeignKeyViolation({ code: "23503" })).toBe(true);+ expect(isForeignKeyViolation({ code: "23505" })).toBe(false);+ });++ it("is false for anything without that code", () => {+ for (const error of [null, undefined, "23505", {}, new Error("23505")]) {+ expect(isUniqueViolation(error)).toBe(false);+ expect(isForeignKeyViolation(error)).toBe(false);+ }+ });++ it("does not read the message text", () => {+ const error = { message: "duplicate key value violates unique constraint" };+ expect(isUniqueViolation(error)).toBe(false);+ });+});++describe("getDatabaseErrorMessage", () => {+ const messages = { duplicate: "Already exists", referenced: "Still in use" };++ it("picks the caller's message for the refused constraint", () => {+ expect(getDatabaseErrorMessage({ code: "23505" }, "Failed", messages)).toBe(+ "Already exists"+ );+ expect(getDatabaseErrorMessage({ code: "23503" }, "Failed", messages)).toBe(+ "Still in use"+ );+ });++ it("falls back for any other error, and for a constraint the caller did not name", () => {+ expect(getDatabaseErrorMessage({ code: "42501" }, "Failed", messages)).toBe(+ "Failed"+ );+ expect(getDatabaseErrorMessage(null, "Failed", messages)).toBe("Failed");+ expect(+ getDatabaseErrorMessage({ code: "23505" }, "Failed", {+ referenced: "Still in use"+ })+ ).toBe("Failed");+ });+});diff --git a/packages/utils/src/errors.ts b/packages/utils/src/errors.tsindex 9b5b242bb2..a177cca6db 100644--- a/packages/utils/src/errors.ts+++ b/packages/utils/src/errors.ts@@ -14,3 +14,37 @@ export function getErrorMessage(error: unknown, fallback: string): string {: (error as { message?: unknown } | null | undefined)?.message;return typeof message === "string" && message !== "" ? message : fallback;}++// Postgres SQLSTATE codes. PostgREST and node-postgres both report them on+// `error.code`, so one check covers a Supabase result and a thrown Kysely error.+const UNIQUE_VIOLATION = "23505";+const FOREIGN_KEY_VIOLATION = "23503";++function hasCode(error: unknown, code: string): boolean {+ return (error as { code?: unknown } | null | undefined)?.code === code;+}++/** The write was refused because a unique constraint already holds that row. */+export function isUniqueViolation(error: unknown): boolean {+ return hasCode(error, UNIQUE_VIOLATION);+}++/** The write was refused because another record still references the row. */+export function isForeignKeyViolation(error: unknown): boolean {+ return hasCode(error, FOREIGN_KEY_VIOLATION);+}++/**+ * The message to show for a refused write: the caller's own copy for the+ * constraint Postgres named, else `fallback`. The copy stays at the call site+ * because only the route knows what a duplicate or a reference means there.+ */+export function getDatabaseErrorMessage(+ error: unknown,+ fallback: string,+ messages: { duplicate?: string; referenced?: string }+): string {+ if (isUniqueViolation(error)) return messages.duplicate ?? fallback;+ if (isForeignKeyViolation(error)) return messages.referenced ?? fallback;+ return fallback;+}diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex b56d2d8763..14812b7894 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -45,6 +45,7 @@ export * from "./mode";export * from "./object";export * from "./payment-funding";export * from "./pick-guards";+export * from "./planning-sizing";export * from "./prefetch";export * from "./purchase-cost-adjustment";export * from "./receiving";diff --git a/packages/utils/src/planning-sizing.test.ts b/packages/utils/src/planning-sizing.test.tsnew file mode 100644index 0000000000..5a27e14b91--- /dev/null+++ b/packages/utils/src/planning-sizing.test.ts@@ -0,0 +1,348 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import type { PlanningSizingParams } from "./planning-sizing";+import { computePlanningOrders } from "./planning-sizing";++const params = (+ overrides: Partial<PlanningSizingParams> = {}+): PlanningSizingParams => ({+ reorderPoint: 0,+ reorderQuantity: 0,+ minimumOrderQuantity: 0,+ maximumOrderQuantity: 0,+ orderMultiple: 0,+ lotSize: 0,+ maximumInventoryQuantity: 0,+ demandAccumulationPeriod: 1,+ demandAccumulationSafetyStock: 0,+ leadTime: 7,+ ...overrides+});++const weeklyPeriods = (startDates: string[]) =>+ startDates.map((startDate, i) => ({ id: `p${i + 1}`, startDate }));++const TODAY = "2026-09-11";++describe("computePlanningOrders", () => {+ it("Manual Reorder returns no orders", () => {+ expect(+ computePlanningOrders({+ reorderingPolicy: "Manual Reorder",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [-50],+ todayDate: TODAY,+ params: params({ reorderPoint: 10 })+ })+ ).toEqual([]);+ });++ it("unknown policy returns no orders", () => {+ expect(+ computePlanningOrders({+ reorderingPolicy: "Bogus",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [-50],+ todayDate: TODAY,+ params: params()+ })+ ).toEqual([]);+ });++ describe("Demand-Based Reorder", () => {+ it("sizes to end-of-window shortfall and dates at the first dip", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods([+ "2026-10-05",+ "2026-10-12",+ "2026-10-19",+ "2026-10-26"+ ]),+ projections: [8, 5, 12, 3],+ todayDate: TODAY,+ params: params({+ demandAccumulationPeriod: 2,+ demandAccumulationSafetyStock: 10+ })+ });++ // Window 1 (p1-p2): dip at p1 (8 < 10), end-of-window 5 → order 5 at p1.+ // Window 2 (p3-p4): +5 already ordered → 17, 8; dip at p4, end 8 → order 2.+ expect(orders).toHaveLength(2);+ expect(orders[0]).toMatchObject({+ periodId: "p1",+ dueDate: "2026-10-05",+ startDate: "2026-09-28",+ quantity: 5,+ isASAP: false,+ policyName: "Demand-Based Reorder"+ });+ expect(orders[0]?.triggerValues).toMatchObject({+ projectedStock: 5,+ safetyStock: 10,+ leadTime: 7+ });+ expect(orders[1]).toMatchObject({+ periodId: "p4",+ dueDate: "2026-10-26",+ quantity: 2+ });+ });++ it("skips windows that end at or above safety stock", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods(["2026-10-05", "2026-10-12"]),+ projections: [2, 10], // mid-window dip that recovers by window end+ todayDate: TODAY,+ params: params({+ demandAccumulationPeriod: 2,+ demandAccumulationSafetyStock: 10+ })+ });+ expect(orders).toEqual([]);+ });++ // The form refuses 0, but an import or API write can store it, and a+ // step of 0 never ended the window loop — the planning page hung.+ it("treats a stored accumulation period of 0 (or null) as one week", () => {+ for (const demandAccumulationPeriod of [0, Number.NaN]) {+ const orders = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods(["2026-10-05", "2026-10-12"]),+ projections: [-5, -5],+ todayDate: TODAY,+ params: params({ demandAccumulationPeriod })+ });+ expect(orders.map((o) => o.periodId)).toEqual(["p1"]);+ expect(orders[0]?.quantity).toBe(5);+ }+ });++ it("applies max OQ, min OQ, and order multiple", () => {+ // Shortfall 100, capped to maxOQ 30+ const capped = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [0],+ todayDate: TODAY,+ params: params({+ demandAccumulationSafetyStock: 100,+ maximumOrderQuantity: 30+ })+ });+ expect(capped[0]?.quantity).toBe(30);++ // Shortfall 7, rounded up to multiple 5 → 10+ const multiple = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [3],+ todayDate: TODAY,+ params: params({+ demandAccumulationSafetyStock: 10,+ orderMultiple: 5+ })+ });+ expect(multiple[0]?.quantity).toBe(10);++ // Shortfall 2, floored to min OQ 6+ const minimum = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [8],+ todayDate: TODAY,+ params: params({+ demandAccumulationSafetyStock: 10,+ minimumOrderQuantity: 6+ })+ });+ expect(minimum[0]?.quantity).toBe(6);+ });++ it("splits into lot-size batches with spread due dates", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [5],+ todayDate: TODAY,+ params: params({+ demandAccumulationSafetyStock: 30, // shortfall 25, lot 10 → 10, 10, 5+ lotSize: 10+ })+ });+ expect(orders.map((o) => o.quantity)).toEqual([10, 10, 5]);+ // offsets: floor(0*7/3)=0, floor(7/3)=2, floor(14/3)=4+ expect(orders.map((o) => o.dueDate)).toEqual([+ "2026-10-05",+ "2026-10-07",+ "2026-10-09"+ ]);+ });+ });++ describe("Fixed Reorder Quantity", () => {+ it("orders reorderQuantity per day until the reorder point is covered", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Fixed Reorder Quantity",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [3],+ todayDate: TODAY,+ params: params({ reorderPoint: 10, reorderQuantity: 4, leadTime: 3 })+ });+ // 3 → +4 (=7) → +4 (=11 ≥ 10) stop+ expect(orders.map((o) => o.quantity)).toEqual([4, 4]);+ expect(orders.map((o) => o.dueDate)).toEqual([+ "2026-10-05",+ "2026-10-06"+ ]);+ expect(orders[0]?.startDate).toBe("2026-10-02");+ expect(orders[0]?.triggerValues).toMatchObject({+ projectedStock: 3,+ reorderPoint: 10,+ reorderQuantity: 4+ });+ });++ it("falls back to reorderPoint as the order quantity when reorderQuantity is 0", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Fixed Reorder Quantity",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [3],+ todayDate: TODAY,+ params: params({ reorderPoint: 10, reorderQuantity: 0 })+ });+ expect(orders.map((o) => o.quantity)).toEqual([10]);+ });++ // Both settings at their default 0 on a short item ordered 0, five times+ // per short week, and every one became an "Order 0" planning action.+ it("suggests nothing when both the reorder point and quantity are 0", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Fixed Reorder Quantity",+ periods: weeklyPeriods(["2026-10-05", "2026-10-12"]),+ projections: [-20, -20],+ todayDate: TODAY,+ params: params({ reorderPoint: 0, reorderQuantity: 0 })+ });+ expect(orders).toEqual([]);+ });+ });++ describe("Maximum Quantity", () => {+ it("orders up to maximum inventory", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Maximum Quantity",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [2],+ todayDate: TODAY,+ params: params({+ reorderPoint: 5,+ reorderQuantity: 1,+ maximumInventoryQuantity: 20+ })+ });+ expect(orders.map((o) => o.quantity)).toEqual([18]);+ });++ it("applies order multiple and max OQ clamps", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Maximum Quantity",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [2],+ todayDate: TODAY,+ params: params({+ reorderPoint: 5,+ reorderQuantity: 1,+ maximumInventoryQuantity: 20,+ orderMultiple: 5+ })+ });+ // required 18 → multiple 5 → 20+ expect(orders.map((o) => o.quantity)).toEqual([20]);+ });+ });++ describe("isASAP", () => {+ it("is true only when the start date is strictly before today", () => {+ const base = {+ reorderingPolicy: "Fixed Reorder Quantity",+ periods: weeklyPeriods(["2026-09-15"]),+ projections: [0],+ params: params({ reorderPoint: 1, reorderQuantity: 5, leadTime: 4 })+ };+ // startDate = 2026-09-11+ const onToday = computePlanningOrders({+ ...base,+ todayDate: "2026-09-11"+ });+ expect(onToday[0]?.isASAP).toBe(false);++ const afterToday = computePlanningOrders({+ ...base,+ todayDate: "2026-09-12"+ });+ expect(afterToday[0]?.isASAP).toBe(true);+ });+ });++ describe("parity with SQL calculate_quantity_to_order (hand-computed literals)", () => {+ // Each expected total below is the scalar the SQL function+ // (20260324120000_planning-quantity-to-order.sql) returns for the same+ // inputs, derived by hand from its branch logic. If this block fails after+ // a change here, the SQL and this module have diverged — fix the drift,+ // never the literals.+ const total = (orders: { quantity: number }[]) =>+ orders.reduce((sum, o) => sum + o.quantity, 0);++ it("DBR windows accumulate like the SQL loop", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Demand-Based Reorder",+ periods: weeklyPeriods([+ "2026-10-05",+ "2026-10-12",+ "2026-10-19",+ "2026-10-26"+ ]),+ projections: [8, 5, 12, 3],+ todayDate: TODAY,+ params: params({+ demandAccumulationPeriod: 2,+ demandAccumulationSafetyStock: 10+ })+ });+ expect(total(orders)).toBe(7); // SQL: window1 → 5, window2 → 2+ });++ it("FRQ loops to cover the reorder point", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Fixed Reorder Quantity",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [3],+ todayDate: TODAY,+ params: params({ reorderPoint: 10, reorderQuantity: 4 })+ });+ expect(total(orders)).toBe(8); // SQL: 4 + 4+ });++ it("Maximum Quantity tops up to the maximum with clamps", () => {+ const orders = computePlanningOrders({+ reorderingPolicy: "Maximum Quantity",+ periods: weeklyPeriods(["2026-10-05"]),+ projections: [2],+ todayDate: TODAY,+ params: params({+ reorderPoint: 5,+ reorderQuantity: 1,+ maximumInventoryQuantity: 20,+ orderMultiple: 5+ })+ });+ expect(total(orders)).toBe(20); // SQL: ceil(18/5)*5+ });+ });+});diff --git a/packages/utils/src/planning-sizing.ts b/packages/utils/src/planning-sizing.tsnew file mode 100644index 0000000000..419adc461c--- /dev/null+++ b/packages/utils/src/planning-sizing.ts@@ -0,0 +1,341 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Reorder-quantity sizing used by the MRP engine (@carbon/planning) when it+// writes Order / Make planning actions; the planning pages list those actions+// rather than sizing again. The math mirrors the SQL+// `calculate_quantity_to_order` (20260324120000_planning-quantity-to-order.sql).+// A parity test pins this module against hand-computed SQL results+// (planning-sizing.test.ts) — do NOT "improve" the math here without updating+// the SQL copy too.+//+// Pure and clock-free: `todayDate` is injected by the caller+// (datetime.today(companyTimeZone)) so this module never reads a timezone. No+// React, no DB, no app imports.++import { RoundingMode, round } from "@carbon/database/precision";+import { parseDate } from "@internationalized/date";++export type PlanningSizingParams = {+ reorderPoint: number;+ reorderQuantity: number;+ minimumOrderQuantity: number;+ maximumOrderQuantity: number;+ orderMultiple: number;+ lotSize: number;+ maximumInventoryQuantity: number;+ demandAccumulationPeriod: number;+ demandAccumulationSafetyStock: number;+ leadTime: number;+};++export type PlanningOrderSuggestion = {+ periodId: string;+ startDate: string;+ dueDate: string;+ quantity: number;+ isASAP: boolean;+ policyName: string;+ triggerValues: {+ projectedStock?: number;+ safetyStock?: number;+ reorderPoint?: number;+ reorderQuantity?: number;+ lotSize?: number;+ leadTime?: number;+ };+};++export type ComputePlanningOrdersInput = {+ reorderingPolicy: string;+ periods: { id: string; startDate: string }[];+ /** Per-period projected on-hand (week1..weekN), same order as `periods`. */+ projections: number[];+ /** ISO calendar date (YYYY-MM-DD). Caller supplies "today" — keeps this pure. */+ todayDate: string;+ params: PlanningSizingParams;+};++/** Away-from-zero ceil to the next multiple (float-artifact-immune). */+const ceilToMultiple = (value: number, multiple: number): number =>+ round(value / multiple, 0, RoundingMode.Up) * multiple;++/** Whole-unit ceil. */+const ceilUnits = (value: number): number => round(value, 0, RoundingMode.Up);++/** Integer floor of a non-negative integer division (a, b integers, b > 0). */+const intFloorDiv = (a: number, b: number): number => (a - (a % b)) / b;++export function computePlanningOrders(+ input: ComputePlanningOrdersInput+): PlanningOrderSuggestion[] {+ const { reorderingPolicy, periods, projections, todayDate, params } = input;+ const {+ demandAccumulationPeriod,+ demandAccumulationSafetyStock,+ leadTime,+ lotSize,+ maximumInventoryQuantity,+ maximumOrderQuantity,+ minimumOrderQuantity,+ orderMultiple,+ reorderPoint,+ reorderQuantity+ } = params;++ const orders: PlanningOrderSuggestion[] = [];++ if (reorderingPolicy === "Manual Reorder") return orders;++ const todaysDate = parseDate(todayDate);+ let orderedQuantity = 0;++ switch (reorderingPolicy) {+ case "Demand-Based Reorder": {+ // Process periods in chunks of demandAccumulationPeriod.+ //+ // End-of-window sizing: only fire an order when the LAST period in the+ // window dips below safety stock, and size it to lift the end-of-window+ // projection back to safety. Mirrors the SQL `calculate_quantity_to_order`+ // DBR branch exactly.+ //+ // A window of at least one week: the form refuses 0, but an import or+ // an API write can store it (or null, which arrives as NaN), and a step+ // of 0 never ends this loop — one such item froze the planning page.+ const windowLength = Math.max(+ 1,+ round(Number(demandAccumulationPeriod) || 1, 0, RoundingMode.Down)+ );+ for (let i = 0; i < periods.length; i += windowLength) {+ const windowEnd = Math.min(i + windowLength, periods.length);++ // Track first dip (for the order's trigger date) AND walk end-of-window+ // projection (for sizing).+ let firstDipIndex = -1;+ let endOfWindowProjection = 0;+ for (let j = i; j < windowEnd; j++) {+ const periodProjection = projections[j] || 0;+ const effective = periodProjection + orderedQuantity;+ if (+ firstDipIndex === -1 &&+ effective < demandAccumulationSafetyStock+ ) {+ firstDipIndex = j;+ }+ endOfWindowProjection = effective;+ }++ // Skip the window unless end-of-window is below safety.+ if (endOfWindowProjection >= demandAccumulationSafetyStock) continue;+ // Defensive: fall back to window start so we never emit an undated order.+ if (firstDipIndex === -1) firstDipIndex = i;++ const currentPeriod = periods[firstDipIndex];+ if (!currentPeriod) continue;++ let totalOrderQuantity = Math.max(+ 0,+ demandAccumulationSafetyStock - endOfWindowProjection+ );++ // Apply lot sizing rules+ if (maximumOrderQuantity > 0) {+ totalOrderQuantity = Math.min(+ totalOrderQuantity,+ maximumOrderQuantity+ );+ }+ totalOrderQuantity = Math.max(totalOrderQuantity, minimumOrderQuantity);++ if (orderMultiple > 0) {+ totalOrderQuantity = ceilToMultiple(+ totalOrderQuantity,+ orderMultiple+ );+ }++ // If we have a lot size and need to split orders+ if (lotSize > 0 && totalOrderQuantity > lotSize) {+ const numberOfBatches = ceilUnits(totalOrderQuantity / lotSize);+ const daysInPeriod = 7; // Weekly periods++ for (let batch = 0; batch < numberOfBatches; batch++) {+ const batchQuantity = Math.min(+ lotSize,+ totalOrderQuantity - batch * lotSize+ );++ // Spread due dates evenly across the period (integer floor —+ // mirrors the original Math.floor without a raw-rounding call)+ const dueDateOffset = intFloorDiv(+ batch * daysInPeriod,+ numberOfBatches+ );+ const dueDate = parseDate(currentPeriod.startDate).add({+ days: dueDateOffset+ });+ const startDate = dueDate.subtract({ days: leadTime });++ orders.push({+ startDate: startDate.toString(),+ dueDate: dueDate.toString(),+ quantity: batchQuantity,+ periodId: currentPeriod.id,+ isASAP: startDate.compare(todaysDate) < 0,+ policyName: "Demand-Based Reorder",+ triggerValues: {+ projectedStock: endOfWindowProjection,+ safetyStock: demandAccumulationSafetyStock,+ lotSize,+ leadTime+ }+ });+ }+ } else {+ // Single order for the period+ const orderQuantity =+ lotSize > 0+ ? Math.min(totalOrderQuantity, lotSize)+ : totalOrderQuantity;++ const dueDate = parseDate(currentPeriod.startDate);+ const startDate = dueDate.subtract({ days: leadTime });++ orders.push({+ startDate: startDate.toString(),+ dueDate: dueDate.toString(),+ quantity: orderQuantity,+ periodId: currentPeriod.id,+ isASAP: startDate.compare(todaysDate) < 0,+ policyName: "Demand-Based Reorder",+ triggerValues: {+ projectedStock: endOfWindowProjection,+ safetyStock: demandAccumulationSafetyStock,+ lotSize,+ leadTime+ }+ });+ }++ orderedQuantity += totalOrderQuantity;+ }+ return orders;+ }+ case "Fixed Reorder Quantity": {+ for (let i = 0; i < periods.length; i++) {+ const period = periods[i];+ if (!period) continue;+ const projectedQuantity = projections[i] || 0;++ let remainingQuantityNeeded =+ reorderPoint - (projectedQuantity + orderedQuantity);++ let day = 0;+ let maxIterations = 100; // Safety counter+ while (remainingQuantityNeeded > 0 && day < 5 && maxIterations-- > 0) {+ const dueDate = parseDate(period.startDate).add({ days: day });+ const startDate = dueDate.subtract({ days: leadTime });++ // If reorder quantity is 0, order the same quantity as the reorder point+ const orderQuantity =+ reorderQuantity > 0 ? reorderQuantity : reorderPoint;++ // Both left at 0 on a short item: ordering 0 covers nothing, so the+ // loop emitted an "Order 0" for every short day and week. Nothing to+ // size from — suggest nothing, as Maximum Quantity does.+ if (orderQuantity <= 0) break;++ orders.push({+ startDate: startDate.toString(),+ dueDate: dueDate.toString(),+ quantity: orderQuantity,+ periodId: period.id,+ isASAP: startDate.compare(todaysDate) < 0,+ policyName: "Fixed Reorder Quantity",+ triggerValues: {+ projectedStock: projectedQuantity + orderedQuantity,+ reorderPoint,+ reorderQuantity,+ leadTime+ }+ });+ day++;+ orderedQuantity += orderQuantity;+ remainingQuantityNeeded =+ reorderPoint - (projectedQuantity + orderedQuantity);+ }+ }+ return orders;+ }+ case "Maximum Quantity": {+ for (let i = 0; i < periods.length; i++) {+ const period = periods[i];+ if (!period) continue;+ const projectedQuantity = projections[i] || 0;++ let remainingQuantityNeeded =+ reorderPoint - (projectedQuantity + orderedQuantity);++ let day = 0;+ let maxIterations = 100; // Safety counter+ while (remainingQuantityNeeded > 0 && day < 5 && maxIterations-- > 0) {+ const dueDate = parseDate(period.startDate).add({ days: day });+ const startDate = dueDate.subtract({ days: leadTime });++ // Calculate required quantity up to maximum inventory+ const requiredQuantity =+ maximumInventoryQuantity - (projectedQuantity + orderedQuantity);++ // If reorder quantity is 0, use reorder point as the base order quantity+ let orderQuantity =+ reorderQuantity > 0+ ? Math.max(minimumOrderQuantity, requiredQuantity)+ : reorderPoint;++ // Ensure orderQuantity is positive to prevent infinite loop+ if (orderQuantity <= 0) break;++ // Round to nearest multiple if specified+ if (orderMultiple && orderMultiple > 1) {+ orderQuantity = ceilToMultiple(orderQuantity, orderMultiple);+ }++ // Only apply lot size if it's greater than 0+ if (lotSize > 0) {+ orderQuantity = ceilToMultiple(orderQuantity, lotSize);+ }++ // Apply maximum order quantity only if it's greater than 0+ if (maximumOrderQuantity > 0) {+ orderQuantity = Math.min(orderQuantity, maximumOrderQuantity);+ }++ orders.push({+ startDate: startDate.toString(),+ dueDate: dueDate.toString(),+ quantity: orderQuantity,+ periodId: period.id,+ isASAP:+ startDate.compare(todaysDate) < 0 &&+ projectedQuantity + orderedQuantity < 0,+ policyName: "Maximum Quantity",+ triggerValues: {+ projectedStock: projectedQuantity + orderedQuantity,+ reorderPoint,+ leadTime,+ reorderQuantity+ }+ });+ day++;+ orderedQuantity += orderQuantity;+ remainingQuantityNeeded =+ reorderPoint - (projectedQuantity + orderedQuantity);+ }+ }+ return orders;+ }+ default:+ return orders;+ }+}diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.tsindex 50c61d1122..731a427960 100644--- a/packages/utils/src/themes.ts+++ b/packages/utils/src/themes.ts@@ -250,24 +250,24 @@ export const themes = [name: "yellow",label: "Lemon",activeColor: {- light: "47.9 95.8% 53.1%",+ light: "59.9 95.8% 53.1%",dark: "61 100% 50%"},cssVars: {light: {- background: "47.9 4% 95%",+ background: "59.9 4% 95%",foreground: "20 14.3% 4.1%",card: "0 0% 100%","card-foreground": "20 14.3% 4.1%",popover: "0 0% 100%","popover-foreground": "20 14.3% 4.1%",- primary: "47.9 95.8% 53.1%",- "primary-foreground": "26 83.3% 14.1%",- active: "47.9 95.8% 88%",- "active-foreground": "47.9 95.8% 4%",- secondary: "47.9 4.8% 95.9%",- "secondary-foreground": "24 9.8% 10%",- muted: "47.9 4.8% 92.9%",+ primary: "59.9 95.8% 53.1%",+ "primary-foreground": "59 83.3% 14.1%",+ active: "59.9 95.8% 53.1%",+ "active-foreground": "59.9 95.8% 4%",+ secondary: "59.9 4.8% 95.9%",+ "secondary-foreground": "59 9.8% 10%",+ muted: "59 4.8% 92.9%","muted-foreground": "25 5.3% 44.7%",accent: "60 4.8% 95.9%","accent-foreground": "24 9.8% 10%",