Skip to content

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

feat(sales): predict quote line lead time from the finite schedule (#1711)

Brad Barbine6f5122e09a5
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 3a31d331b6..091e3af587 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2208,3 +2208,29 @@ load-bearing only for the old one.
**Applies to:** `packages/files/src/storage.ts` (`CompanyBucket`), its ~60 call
sites across `apps/erp`, `apps/mes`, `packages/{jobs,ee,lib}`, and any future
change to a helper whose result is destructured widely.
+
+## Lingui: a ternary inside t`` bakes the English words as runtime values
+
+**Context:** Building the quote lead-time modal, plural labels were written as
+`` t`${days} ${days === 1 ? "day" : "days"}` `` and
+`` t`${n} ${n === 1 ? "operation has" : "operations have"} no time standards` ``.
+
+**Problem:** Lingui extracts that as `{0} {1} no time standards` — the "day"/
+"days"/"operation has"/"operations have" strings are computed at runtime and
+passed in as PLACEHOLDER VALUES, never as translatable text. So every locale's
+`msgstr` still contains the English word, `linguito check` stays green (nothing
+is "missing"), and a French user reads "5 days", not "5 jours". The defect is
+invisible to the missing-translation gate because the placeholder IS filled.
+
+**Rule:** Never put a pluralizing (or any word-choosing) ternary inside a
+`t` tagged template or `<Trans>`. Use the ICU plural macro: `<Plural value={n}
+one="# day" other="# days" />` from `@lingui/react/macro` (or `plural()` in
+non-JSX). The whole phrase with `#` goes in each branch
+(`one="# operation has no time standards"`), so the words are extracted and
+translated. After adding one, re-run `lingui:extract` + `/translate` — the new
+ICU msgid needs its own filled `msgstr` per locale (locales with more CLDR
+categories, e.g. Polish/Russian `few`/`many`, get the extra branches).
+
+**Applies to:** any `apps/{erp,mes}/app` or `packages/{react,form}/src` string
+with a count-dependent word; grep `? "` inside `` t` `` templates when reviewing
+i18n.
diff --git a/.ai/plans/2026-09-22-quote-lead-time-prediction.md b/.ai/plans/2026-09-22-quote-lead-time-prediction.md
new file mode 100644
index 0000000000..2a08cf2cea
--- /dev/null
+++ b/.ai/plans/2026-09-22-quote-lead-time-prediction.md
@@ -0,0 +1,567 @@
+# Quote line lead time prediction — implementation plan
+
+**Spec:** .ai/specs/2026-09-22-quote-lead-time-prediction.md
+**Research:** .ai/research/quote-lead-time-prediction.md
+**Branch:** nukualofa
+
+Read first: `.claude/rules/scheduling-data-structures.md`, `packages/planning/AGENTS.md`,
+`apps/erp/app/modules/sales/AGENTS.md`, `.claude/rules/date-handling.md`,
+`.claude/rules/numeric-precision.md`, `.ai/lessons.md` (entry "Kysely returns NUMERIC
+as a string", ~line 1011 — `quoteOperation` times and `quoteMaterial.quantity` arrive
+as strings through Kysely; coerce with `Number(...)` at the loader boundary).
+
+## Progress
+- [x] Task 1: Add an optional `materialReadyAt` floor to finite placement
+- [x] Task 2: Extract `buildFiniteContext` into `finite-context.ts`
+- [x] Task 3: Pure quote-simulation builders + tests
+- [x] Task 4: `runQuoteLeadTimeWhatIf` orchestrator + package export (DB smoke deferred to Task 8 — stack not up)
+- [x] Task 5: ERP route, validator and path
+- [x] Task 6: `QuoteLeadTimeModal` + button on the pricing grid
+- [x] Task 7: Translations, docs
+- [ ] Task 8: Browser verification — BLOCKED: no dev stack booted for this worktree
+ (no `.env.local`; only shared postgres+redis up). Needs `crbn up` + a
+ satellite quote line with a routing. Confirm before booting (shared local
+ ports may collide with other worktrees).
+
+## Dependencies
+Task 2 needs Task 1 (same file region, avoid conflicts). Task 3 needs Task 1 (the
+`materialReadyAt` field). Task 4 needs Tasks 2 and 3. Task 5 needs Task 4. Task 6
+needs Task 5. Tasks 7–8 need Task 6. Tasks 1 and 3 could be done in parallel if Task 3
+adds the type field itself; simpler to run in order.
+
+---
+
+## Task 1: Add an optional `materialReadyAt` floor to finite placement
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/planning/src/scheduling/types.ts` — add the field to `BaseOperation`
+- Modify: `packages/planning/src/scheduling/work-center-selector.ts` — honor it at both earliest-start sites
+- Modify: `packages/planning/src/scheduling/work-center-selector.test.ts` — one new test
+
+**Steps:**
+1. In `types.ts`, inside `BaseOperation` (L30-74) add, after `operationLeadTime?`:
+ ```ts
+ /**
+ * Earliest instant this op's material is available (epoch ms). Only set by
+ * the quote lead-time what-if for ops that consume a purchased part; never
+ * set on job operations, so live scheduling is unchanged.
+ */
+ materialReadyAt?: number;
+ ```
+ `ScheduledOperation` extends `BaseOperation` (L120-137), so it inherits the field.
+2. In `work-center-selector.ts`, the regular-op earliest-start block (~L527-537,
+ `let earliestMs = ctx.now; let dominantDepId ...`): after the dependency loop and
+ before `const earliestStart = earliestMs;` add
+ ```ts
+ if (op.materialReadyAt !== undefined && op.materialReadyAt > earliestMs) {
+ earliestMs = op.materialReadyAt;
+ dominantDepId = null;
+ }
+ ```
+3. In the Outside Processing branch (~L419-445, `let earliestMs = ctx.now;` followed by
+ the `op.startDate` and dependency loop): after the dependency loop add
+ ```ts
+ if (op.materialReadyAt !== undefined) {
+ earliestMs = Math.max(earliestMs, op.materialReadyAt);
+ }
+ ```
+4. In `work-center-selector.test.ts`, copy the smallest existing single-op placement
+ test (the one around L112 that builds one op and asserts `placedStart`) and add a
+ test "materialReadyAt floors the placement": same fixture, set
+ `materialReadyAt = ctx.now + 3 * 24 * 3_600_000`, assert the planned reservation's
+ `startAt >= materialReadyAt`. Add a second assertion in the same test that an op
+ WITHOUT the field places at the same instant as before (run the fixture twice).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/planning test
+# Expected: all suites pass, including determinism.test.ts and the new test
+pnpm exec turbo run typecheck --filter=@carbon/planning
+# Expected: no errors
+```
+
+**Out of scope:** anything reading `materialReadyAt` on the job path; `need-by-calculator.ts`.
+
+---
+
+## Task 2: Extract `buildFiniteContext` into `finite-context.ts`
+
+**Depends on:** Task 1
+**Files:**
+- Create: `packages/planning/src/scheduling/finite-context.ts`
+- Modify: `packages/planning/src/scheduling/scheduling-engine.ts` — delegate `loadAvailabilityWindows` (L558-616) and `buildFiniteContext` (L673-897) to the new module
+
+**Steps:**
+1. Create `finite-context.ts` exporting:
+ ```ts
+ export type AvailabilityWindows = {
+ workCenterIds: Set<string>;
+ workCenterAvailability: Map<string, CalendarWindow[]>;
+ locationDefaultWindows: CalendarWindow[];
+ rangeStart: number;
+ rangeEnd: number;
+ };
+
+ export async function loadAvailabilityWindows(args: {
+ provider: MasterDataProvider;
+ workCenterSelector: WorkCenterSelector;
+ operations: ScheduledOperation[];
+ locationId: string | null;
+ now: number;
+ }): Promise<AvailabilityWindows>;
+
+ export async function buildFiniteContext(args: {
+ provider: MasterDataProvider;
+ operations: ScheduledOperation[];
+ dependencies: JobOperationDependency[];
+ availability: AvailabilityWindows;
+ locationId: string | null;
+ timeZone: string;
+ now: number;
+ excludeJobIds: string[];
+ }): Promise<FiniteSchedulingContext>;
+ ```
+ Move the bodies verbatim from the engine. Replace `this.provider` → `provider`,
+ `this.now` → `now`, `this.excludeJobIds` → `excludeJobIds`,
+ `this.job?.locationId` → `locationId`, `this.timezone` / `this.job?.timezone ?? "UTC"`
+ → `timeZone`, `this.dependencies` → `dependencies`,
+ `Array.from(this.scheduledOperations.values())` → `operations`,
+ `this.workCenterSelector?.getAllCandidateWorkCenterIds(...)` →
+ `workCenterSelector.getAllCandidateWorkCenterIds(...)`. Keep every comment.
+ Move the helper imports the bodies use (`expandCalendar`, `unionWindows`,
+ `buildAbsencesByEmployee`, `subtractAbsences`, `buildPeopleByWorkCenter`,
+ `buildAssignmentsByEmployee`, `buildOvertimeByEmployee`, `extendWindowsByOvertime`,
+ `buildPeopleBudgets`, `SCHEDULING_HORIZON_DAYS`) — export `SCHEDULING_HORIZON_DAYS`
+ from `finite-context.ts` and re-import it in the engine if it is currently defined
+ in the engine (L81).
+2. In the engine, keep the private methods as thin wrappers so no caller changes:
+ `loadAvailabilityWindows()` memoizes on `this.availabilityWindows` and calls the
+ new function; `buildFiniteContext()` returns `null` when `this.workCenterSelector`
+ is null, else awaits the windows and calls the new function. The need-by pass
+ (`computeNeedBys`, L625) keeps using `this.loadAvailabilityWindows()`.
+3. Do not change `selectWorkCenters()` or anything after it.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/planning test
+# Expected: every suite passes with no fixture edits — determinism.test.ts,
+# envelope.test.ts, batch-scheduler.test.ts, work-center-selector.test.ts
+pnpm exec turbo run typecheck --filter=@carbon/planning
+# Expected: no errors
+git diff --stat packages/planning/src/scheduling/scheduling-engine.ts
+# Expected: the file shrinks by roughly 250 lines; no other engine file changes
+```
+
+**Out of scope:** changing what the context contains; touching `run-schedule.ts`.
+
+---
+
+## Task 3: Pure quote-simulation builders + tests
+
+**Depends on:** Task 1
+**Files:**
+- Create: `packages/planning/src/scheduling/quote-lead-time.ts` (builders only in this task)
+- Create: `packages/planning/src/scheduling/quote-lead-time.test.ts`
+- Copy from (precedent): `scheduling-engine.ts` `createDependencies` (L332-420) for the dependency walk; `envelope.test.ts` `makeOperations` (L35-70) for hand-built ops in tests
+
+**Steps:**
+1. Define the input row types (plain objects, already `Number()`-coerced by the loader in Task 4):
+ ```ts
+ export type QuoteMakeMethodRow = { id: string; parentMaterialId: string | null };
+ export type QuoteMaterialRow = {
+ id: string; quoteMakeMethodId: string; itemId: string;
+ methodType: "Purchase to Order" | "Pull from Inventory" | "Make to Order";
+ quantity: number; // per parent unit
+ quoteOperationId: string | null; // consuming op
+ };
+ export type QuoteOperationRow = {
+ id: string; quoteMakeMethodId: string; processId: string | null;
+ workCenterId: string | null; order: number;
+ operationOrder: "After Previous" | "With Previous";
+ operationType: string | null; description: string | null;
+ setupTime: number; setupUnit: string; laborTime: number; laborUnit: string;
+ machineTime: number; machineUnit: string; operationLeadTime: number;
+ };
+ export type MaterialAvailability = {
+ leadTimeDaysByItem: Map<string, number>; // itemReplenishment.leadTime, default 7
+ onHandByItem: Map<string, number>; // itemStockQuantities at the location
+ };
+ ```
+2. Export the pure builder:
+ ```ts
+ export function buildQuoteSimulation(args: {
+ quoteLineId: string;
+ quantity: number;
+ makeMethods: QuoteMakeMethodRow[];
+ materials: QuoteMaterialRow[];
+ operations: QuoteOperationRow[];
+ availability: MaterialAvailability;
+ now: number; // epoch ms
+ }): {
+ jobId: string; // `quote:${quoteLineId}:${quantity}`
+ operations: BaseOperation[];
+ dependencies: JobOperationDependency[]; // { operationId, dependsOnId, jobId }
+ materialReadyDays: number; // max floor in whole days, 0 if none
+ zeroStandardOperationCount: number; // ops whose three times are all 0
+ }
+ ```
+ Algorithm:
+ - Root method = the one with `parentMaterialId === null`. Multiplier of the root = 1.
+ For every other method, its `parentMaterialId` names a `QuoteMaterialRow`; the
+ method's multiplier = multiplier(material.quoteMakeMethodId's method) ×
+ `material.quantity`. Walk parents-first (a loop that resolves any method whose
+ parent is resolved, until no progress; a method whose parent never resolves is
+ dropped).
+ - For each operation: `operationQuantity = quantity × multiplier(method)`,
+ `quantityComplete: 0`, `jobId`, `jobMakeMethodId: op.quoteMakeMethodId`,
+ `status: "Todo"`, copy `processId, workCenterId, order, operationOrder,
+ operationType, description, setupTime/Unit, laborTime/Unit, machineTime/Unit,
+ operationLeadTime`.
+ - Dependencies: per method `buildOperationDependencies(methodOps)` (from
+ `dependency-manager.ts`); for each non-root method, add the edge
+ `consumingOp depends on lastOpOfChild` where consumingOp = the parent material's
+ `quoteOperationId`, else the parent method's lowest-`order` op; skip when either
+ side is missing. Convert with `dependenciesToRecords(map, jobId, "")` and drop
+ the `companyId` key (the context only reads `operationId`/`dependsOnId`/`jobId`),
+ or build the `JobOperationDependency[]` array directly — either is fine.
+ - Material floors: for each material with a resolved method, required =
+ `quantity × multiplier(material's method) × material.quantity`; floorDays =
+ `leadTimeDaysByItem.get(itemId) ?? 7` when `methodType === "Purchase to Order"`,
+ or when `methodType === "Pull from Inventory"` and
+ `(onHandByItem.get(itemId) ?? 0) < required`; else none. Consuming op as above.
+ Set `op.materialReadyAt = now + floorDays × 24 × 3_600_000` (keep the max when
+ two materials hit one op). `materialReadyDays` = max floorDays over all, else 0.
+ - `zeroStandardOperationCount` = count of ops with `setupTime === 0 && laborTime === 0 && machineTime === 0`.
+3. Export `cloneFiniteContext(ctx: FiniteSchedulingContext): FiniteSchedulingContext`:
+ new `capacityByWorkCenter` Map whose values are `{ ...data, reservations: [...data.reservations] }`,
+ new `reservationsByEmployee` Map with copied arrays, every other property shared by
+ reference. Add a comment citing the type's doc ("Reservation arrays are mutated in-run").
+4. Export the pure day math:
+ ```ts
+ export function calendarDaysFromNow(finishMs: number, nowMs: number, timeZone: string): number
+ ```
+ using `@internationalized/date`: `toCalendarDate(fromAbsolute(ms, timeZone))` for
+ both, `days = finish.compare(today)` (already an integer — no rounding call needed),
+ returning `days < 1 ? 1 : days`.
+5. Tests in `quote-lead-time.test.ts` (vitest, colocated like the other suites):
+ - a root method with two ops "After Previous" → one dependency edge, quantities scale
+ (`operationQuantity` = quantity for root ops);
+ - a sub-assembly (child method via `parentMaterialId`, material quantity 2, consuming
+ op set) → child ops have `operationQuantity = 2 × quantity` and the edge
+ `consumingOp ← child's last op`;
+ - no `quoteOperationId` on the material → edge goes to the parent's first op;
+ - `Purchase to Order` material with lead time 10 → consuming op `materialReadyAt ===
+ now + 10 days`, `materialReadyDays === 10`; `Pull from Inventory` with on-hand ≥
+ required → no floor; below required → floor;
+ - `cloneFiniteContext` → pushing onto a clone's reservations leaves the original untouched;
+ - `calendarDaysFromNow` → a finish later the same local day returns 1; a finish two
+ local days ahead returns 2; a finish at 23:30 local vs a now at 00:30 next day
+ returns 1 (timezone-correct, use `"America/New_York"`).
+
+**Verify:**
+```bash
+pnpm --filter @carbon/planning test -- quote-lead-time
+# Expected: the new suite passes (6+ tests)
+pnpm exec turbo run typecheck --filter=@carbon/planning
+# Expected: no errors
+```
+
+**Out of scope:** any DB access in this file (that is Task 4); scrap quantities.
+
+---
+
+## Task 4: `runQuoteLeadTimeWhatIf` orchestrator + package export
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Modify: `packages/planning/src/scheduling/quote-lead-time.ts` — add the loader + orchestrator
+- Modify: `packages/planning/src/scheduling/run-schedule.ts` — `export` `loadOrderedBatch` (L73)
+- Modify: `packages/planning/src/index.ts` — export the new entry point and types
+- Copy from (precedent): `run-schedule.ts` `runExpediteWhatIf` (L242-294)
+
+**Steps:**
+1. Export the result types from the spec (`QuoteLeadTimeScenario`, `QuoteLeadTimeForecast`)
+ verbatim.
+2. Add `loadQuoteLineRouting(db, quoteLineId, companyId)` (module-private): three Kysely
+ selects filtered by `quoteLineId` AND `companyId` — `quoteMakeMethod`
+ (`id, parentMaterialId`), `quoteMaterial` (`id, quoteMakeMethodId, itemId, methodType,
+ quantity, quoteOperationId`), `quoteOperation` (the columns of `QuoteOperationRow`).
+ Coerce every numeric with `Number(...)`. Return `null` when there is no make method
+ (a `Pull from Inventory` / `Purchase to Order` quote line has no routing).
+3. Add `loadMaterialAvailability(db, itemIds, locationId, companyId)`: `itemReplenishment`
+ → `leadTimeDaysByItem` (`.select(["itemId","leadTime"]).where("itemId","in",…).where("companyId","=",…)`),
+ `itemStockQuantities` → `onHandByItem` (`.select(["itemId","quantityOnHand"]).where("locationId","=",…).where("companyId","=",…)`, the read `mrp.ts:277` uses).
+4. Add the orchestrator:
+ ```ts
+ export async function runQuoteLeadTimeWhatIf(params: {
+ db: Kysely<DB>; client: SupabaseClient<Database>;
+ companyId: string; userId: string; locationId: string;
+ quoteLineId: string; quantities: number[]; dueDate?: string | null;
+ }): Promise<QuoteLeadTimeForecast | null>
+ ```
+ - `now = Date.now()` (the engine's convention for its clock; do not use `Date` for anything else).
+ - `timeZone` = `db.selectFrom("location").select("timezone").where("id","=",locationId).where("companyId","=",companyId)` → `?? "UTC"`.
+ - `routing = await loadQuoteLineRouting(...)`; return `null` if none.
+ - `provider = new KyselyMasterDataProvider(db, client, companyId, { cacheCompanyData: true })`.
+ - `batch = await loadOrderedBatch(db, locationId, companyId)`.
+ - Batch placements exactly as `runExpediteWhatIf` does (`placeReleasedBatches` with
+ `persist: false`, try/catch → null).
+ - `selector = new WorkCenterSelector(provider, locationId); await selector.initialize()`.
+ - Build the simulation for the FIRST quantity to derive the op set for the windows
+ fetch (the op ids and process ids are the same for every quantity), then
+ `availability = await loadAvailabilityWindows({ provider, workCenterSelector: selector, operations, locationId, now })`.
+ - Build two contexts with `buildFiniteContext`: `queuedCtx` (`excludeJobIds: []`) and
+ `bestCtx` (`excludeJobIds: batch`); `dependencies` from the first simulation (same
+ graph for every quantity).
+ - For each quantity: `sim = buildQuoteSimulation(...)`;
+ `ops = Array.from(buildScheduledOperations(sim.operations).values())`
+ (`date-calculator.ts`); for each scenario, `selector.setFiniteContext(cloneFiniteContext(ctx))`,
+ `selections = selector.selectWorkCentersForOperations(ops, { jobDueDate: dueDate ?? null, batchPlacements })`,
+ `finishMs` = max `toInstantMs(selection.placedEnd)` over selections and
+ `p.endAt` over `selector.getPlannedReservations()` (the same union
+ `selectWorkCenters()` computes, engine L930-945); `cause` = the first non-null
+ `selection.conflict`, else the `scheduleNote` of the planned reservation with the
+ largest `startAt − earliestStartAt`, else `null`.
+ One selector instance is reused for every run: `selectWorkCentersForOperations`
+ resets `this.plannedReservations = []` at its start (`work-center-selector.ts:361`),
+ and `setFiniteContext` swaps the context, so a clone per run is the only isolation needed.
+ - `leadTimeDays = calendarDaysFromNow(finishMs, now, timeZone)`; `finishAt = msToInstantIso(finishMs)`.
+ - `target` when `dueDate` is set: `queuedFinishDate = businessDayFromMs(finishMs, timeZone)`
+ (the helper `work-center-selector.ts` uses for `outsideEndDate`), verdict `"on-time"` if
+ `queuedFinishDate <= dueDate`, else `"expedite"` if the best-case date `<= dueDate`,
+ else `"late"`; `slackDays = parseDate(dueDate).compare(parseDate(queuedFinishDate))`.
+ - `assumptions`: the three fixed sentences from the spec, with the location name
+ interpolated (read `location.name` in the same select as `timezone`).
+5. `run-schedule.ts`: add `export` to `loadOrderedBatch`.
+6. `index.ts`: add
+ ```ts
+ export {
+ type QuoteLeadTimeForecast,
+ type QuoteLeadTimeScenario,
+ runQuoteLeadTimeWhatIf
+ } from "./scheduling/quote-lead-time.ts";
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/planning
+# Expected: no errors
+pnpm --filter @carbon/planning test
+# Expected: all suites pass
+```
+Then a one-off smoke against the local database (needs `crbn up`): write a throwaway
+script under `.ai/scratch/` (gitignored) that imports `runQuoteLeadTimeWhatIf` from
+`@carbon/planning`, points at a satellite-dataset quote line with a routing, and prints
+the forecast. Expected: `queued.finishAt` ≥ `bestCase.finishAt`, both non-null,
+`leadTimeDays ≥ 1`. Delete the script afterwards.
+
+**Out of scope:** persisting anything; `scenarioId`; changing `runExpediteWhatIf`.
+
+---
+
+## Task 5: ERP route, validator and path
+
+**Depends on:** Task 4
+**Files:**
+- Modify: `apps/erp/app/modules/sales/sales.models.ts` — add `quoteLeadTimeValidator`
+- Modify: `apps/erp/app/utils/path.ts` — add `quoteLineLeadTime` next to `quoteLineRecalculatePrice` (L1973)
+- Create: `apps/erp/app/routes/x+/quote+/$quoteId.$lineId.lead-time.tsx`
+- Copy from (precedent): `apps/erp/app/routes/x+/job+/$jobId.expedite.tsx` (whole file); `apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx` for the quote-scoped reads
+
+**Steps:**
+1. `sales.models.ts`, near `selectedLineSchema` (L1058):
+ ```ts
+ export const quoteLeadTimeValidator = z.object({
+ quantities: z.array(z.number().positive()).min(1),
+ dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable()
+ });
+ ```
+ Export it through the module barrel like the neighbours.
+2. `path.ts`: `quoteLineLeadTime: (quoteId: string, lineId: string) => generatePath(`${x}/quote/${quoteId}/${lineId}/lead-time`)`.
+3. Route action (POST only, JSON body — the modal submits `fetcher.submit(payload, { method: "post", encType: "application/json" })`):
+ - `requirePermissions(request, { view: "sales" })` → `companyId, userId, client`.
+ - Parse `quoteLeadTimeValidator.safeParse(await request.json())`; on failure return
+ `data({ forecast: null, error: "Invalid request" }, { status: 400 })`.
+ - Read the quote under the company: `client.from("quote").select("locationId").eq("id", quoteId).eq("companyId", companyId).single()`; 404 via `throw new Response(null, { status: 404 })` on a miss (the record-id rule from `.claude/rules/workflow-edge-function.md` §5 applies to routes too).
+ - Read the line: `client.from("quoteLine").select("id").eq("id", lineId).eq("quoteId", quoteId).eq("companyId", companyId).single()`; 404 on miss.
+ - `locationId = quote.locationId ?? (await getUserDefaults(client, userId, companyId)).data?.locationId`
+ (`~/modules/users/users.server`); if still null return
+ `data({ forecast: null, error: "Set a location on the quote to predict lead time" })`.
+ - `const { runQuoteLeadTimeWhatIf } = await import("@carbon/planning")` (routes may
+ import it statically too — `kanban.$id.tsx` does; use a static import).
+ - Call with `db: getDatabaseClient()` (`~/services/database.server`),
+ `client: getCarbonServiceRole()`, the ids and the validated body.
+ - Return `data({ forecast, error: null })`; on throw, `console.error` and return
+ `data({ forecast: null, error: "Failed to predict lead time" })`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+```
+With `crbn up` running and an authenticated browser session, from the devtools console on
+a quote line page:
+```js
+fetch(location.pathname.replace(/\/details$/, "") + "/lead-time", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ quantities: [1, 10] }) }).then(r => r.json()).then(console.log)
+```
+Expected: `{ forecast: { quantities: [ { quantity: 1, queued: {...}, bestCase: {...} }, ... ] } }`.
+
+**Out of scope:** writing `leadTime` from this route.
+
+---
+
+## Task 6: `QuoteLeadTimeModal` + button on the pricing grid
+
+**Depends on:** Task 5
+**Files:**
+- Create: `apps/erp/app/modules/sales/ui/Quotes/QuoteLeadTimeModal.tsx`
+- Modify: `apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx` — button on the Lead Time row (L749-753), modal mount, fetcher
+- Copy from (precedent): `JobExpediteModal` in `apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx` (L1163-1260) for the modal shell, loading state, "Bottleneck" alert; the pricing table itself (`QuoteLinePricing.tsx` L738-746) for the quantity-column table; `apps/erp/app/modules/production/ui/Schedule/People/TimeOffDialog.tsx` for a `DatePicker` from `@carbon/react` inside a dialog
+
+**Steps:**
+1. Modal props:
+ ```ts
+ {
+ quoteId: string; lineId: string; quantities: number[]; isEditable: boolean;
+ onApply: (leadTimeByQuantity: Record<number, number>) => Promise<void>;
+ onClose: () => void;
+ }
+ ```
+ Inside: `useFetcher<typeof action>()` (import the action type from the route file);
+ on mount `fetcher.submit({ quantities }, { method: "post", encType: "application/json", action: path.to.quoteLineLeadTime(quoteId, lineId) })`.
+ Local state `constraint: "queued" | "bestCase" | "target"` (default `"queued"`) and
+ `targetDate: CalendarDate | null`. Changing the target date resubmits with
+ `dueDate: date.toString()`; the forecast for the other two constraints is already in
+ the same response, so switching between them re-renders without a request.
+2. Header: the constraint picker is `Tabs` / `TabsList` / `TabsTrigger` from
+ `@carbon/react`, copied from the view switcher in
+ `apps/erp/app/modules/production/ui/Schedule/People/PeopleHeader.tsx` (L16-18, L107)
+ but bound to local state instead of `?view=` (three triggers: "End of queue",
+ "Best case", "Target date"). When "Target date" is
+ selected, a `DatePicker` from `@carbon/react` (precedent `TimeOffDialog.tsx`) appears
+ beside it.
+3. Body while loading: spinner + "Predicting lead time…" (copy the expedite modal's
+ 118px block). On `error`: the message in an `Alert`. On `forecast === null` without
+ error: "This line has no routing to schedule." Otherwise ONE `Table` whose rows are
+ the quantity breaks and whose columns depend on the constraint:
+ - queued / bestCase: Quantity · Materials ("N days" or "—") · Finish
+ (`formatDate(finishAt.slice(0,10))`) · Lead time ("N days", the value that will be
+ written) · Bottleneck (`cause`, or "—").
+ - target: Quantity · Materials · Queued finish · Best-case finish · Verdict (a
+ `Badge`: `variant="green"` "On time", `variant="orange"` "Needs expedite",
+ `variant="red"` "Not feasible", with "N days of slack" / "N days short" beneath) ·
+ Lead time ("N days" = `parseDate(targetDate).compare(today)`, identical on every row).
+ Under the table: the `assumptions` as a muted `<ul>`; when
+ `zeroStandardOperationCount > 0` an extra muted line "N operations have no time
+ standards". Numbers are shown plainly, never in parentheses.
+4. Footer: "Apply to all quantities" (`isEditable` only; disabled while loading, while
+ no forecast, under "target" with no date, or under "target" while any row's verdict is
+ `"late"` — with a `Tooltip` "One or more quantities cannot meet this date") and
+ "Close". Apply builds `{ [quantity]: leadTimeDays }` for every row from the selected
+ constraint, awaits `onApply(map)`, then calls `onClose()`.
+5. `QuoteLinePricing.tsx`: add `onUpdateLeadTimes` next to `onUpdatePrice` (L495). It
+ must NOT loop over `onUpdatePrice` — that callback snapshots `editableFields.prices`
+ per call and replaces the whole map in `setEditableFields`, so a loop would keep only
+ the last quantity's value in state. Implementation:
+ ```ts
+ const onUpdateLeadTimes = useCallback(
+ async (leadTimeByQuantity: Record<number, number>) => {
+ const prices = { ...editableFields.prices };
+ const missing: number[] = [];
+ for (const [key, days] of Object.entries(leadTimeByQuantity)) {
+ const quantity = Number(key);
+ if (prices[quantity]) {
+ prices[quantity] = { ...prices[quantity], leadTime: days };
+ } else {
+ missing.push(quantity);
+ prices[quantity] = { /* the same blank row onUpdatePrice builds, leadTime: days */ } as unknown as QuotationPrice;
+ }
+ }
+ setEditableFields((prev) => ({ ...prev, prices }));
+ const writes = Object.entries(leadTimeByQuantity).map(([key, days]) => {
+ const quantity = Number(key);
+ return missing.includes(quantity)
+ ? carbon?.from("quoteLinePrice").insert({ ...prices[quantity], quoteLineId: lineId, quantity })
+ : carbon?.from("quoteLinePrice").update({ leadTime: days, quoteLineId: lineId, quantity }).eq("quoteLineId", lineId).eq("quantity", quantity);
+ });
+ const results = await Promise.all(writes);
+ if (results.some((r) => r?.error)) {
+ logger.error("Failed to update quote line lead times", { errors: results.map((r) => r?.error).filter(Boolean) });
+ toast.error(t`Failed to update lead times`);
+ }
+ },
+ [editableFields.prices, carbon, lineId, quoteId, exchangeRate, userId, t]
+ );
+ ```
+ Then add `const [leadTimeModalOpen, setLeadTimeModalOpen] = useState(false)`; on the
+ Lead Time row header `HStack` (L750-753) render, when `isEmployee && hasCalculatedCost`,
+ an `IconButton` `aria-label="Predict lead time"` `icon={<LuCalendarClock />}`
+ `variant="ghost"` `size="sm"` that opens the modal. Mount
+ `<QuoteLeadTimeModal … onApply={onUpdateLeadTimes} />` when open, passing
+ `quantities` and `isEditable`. Every string goes through Lingui
+ (`<Trans>` / `t\`…\``).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no errors
+pnpm run lint
+# Expected: no new Biome findings
+```
+
+**Out of scope:** the share page, the PDF, `QuoteToOrderDrawer`.
+
+---
+
+## Task 7: Translations, docs
+
+**Depends on:** Task 6
+**Files:**
+- Modify: `packages/locale/locales/*/*.po` via `/translate`
+- Modify: `.claude/rules/scheduling-data-structures.md` — under "Where it lives" add `finite-context.ts` and `quote-lead-time.ts` (`runQuoteLeadTimeWhatIf`: synthetic ops through the pure selector; two contexts, queued vs front-of-queue; `materialReadyAt` floor, unset for jobs); under "Gotchas" note the selector's reservation arrays must be cloned per simulation
+- Modify: `packages/planning/AGENTS.md` — list the new entry point next to `runExpediteWhatIf`
+- Modify: `apps/erp/app/modules/sales/AGENTS.md` — Quote Line Pricing concept: lead time can be predicted from the schedule (`QuoteLeadTimeModal`, route `$quoteId.$lineId.lead-time.tsx`); the write goes through `onUpdateLeadTimes`
+
+**Steps:**
+1. Run `pnpm lingui:extract` (or the command `.claude/rules/i18n-lingui-system.md` names), then `/translate`.
+2. Make the three doc edits above; keep each under ten lines.
+
+**Verify:**
+```bash
+git diff --stat packages/locale .claude/rules packages/planning/AGENTS.md apps/erp/app/modules/sales/AGENTS.md
+# Expected: .po files gain the new msgids with non-empty msgstr; three doc files touched
+```
+
+**Out of scope:** the public docs site.
+
+---
+
+## Task 8: Browser verification
+
+**Depends on:** Task 7
+**Files:** none
+
+**Steps:**
+1. `crbn up`; `pnpm --filter @carbon/jobs dev:jobs` is not needed (no Inngest path).
+2. `/auth`, open a satellite-dataset quote with a Make to Order line that has a routing
+ (any line with operations in its Bill of Process) → Pricing card.
+3. Click the calendar icon on the Lead Time row. Expected: modal with "End of queue"
+ selected, a row per quantity break with a finish date and "N days"; switch to
+ "Best case" → every finish is the same day or earlier, no request is made
+ (network tab); a bottleneck sentence appears when the shop has open jobs on the
+ same work centers.
+4. Switch to "Target date": with no date the Apply button is disabled. A date earlier
+ than the best case → every row "Not feasible" and Apply stays disabled with the
+ tooltip; a date between the two → "Needs expedite", Apply enabled; a date after the
+ queued finish → "On time".
+5. Back on "End of queue", click "Apply to all quantities" → the modal closes and EVERY
+ Lead Time cell in the grid shows its row's value (not only the last quantity); a
+ reload shows them persisted. Click the markup "Recalculate" → the values survive
+ (`resolvePreservedQuoteLinePriceFields`).
+6. Screenshot the modal for the PR.
+
+**Verify:** `/test` playbook cached at `.ai/playbooks/quote-lead-time-prediction.md`; the
+five expectations above hold.
+
+**Out of scope:** load testing.
diff --git a/.ai/research/quote-lead-time-prediction.md b/.ai/research/quote-lead-time-prediction.md
new file mode 100644
index 0000000000..9c93d547db
--- /dev/null
+++ b/.ai/research/quote-lead-time-prediction.md
@@ -0,0 +1,157 @@
+# Quote Lead Time Prediction (Capable-to-Promise) Research: Best Practices Survey
+
+## Summary
+
+Surveyed how SAP (ATP, MATP, CTP/SBC), Oracle Global Order Promising, Microsoft D365 SCM and Business Central, job-shop ERPs (Epicor Kinetic, Infor SyteLine and VISUAL, JobBOSS², ProShop, Cetec), Odoo, and modern quoting tools (Fulcrum, MRPeasy, Katana, Paperless Parts, Xometry, Protolabs) compute a promised lead time for a make-to-order line. Three tiers exist: **policy lead time** (a typed days value, optionally with priced expedite tiers — Odoo, Paperless Parts, marketplaces); **material-driven ATP** (stock plus replenishment/BOM lead time, infinite capacity — SAP classic ATP and MATP, Oracle lead-time mode, BC CTP, D365 ATP); and **capacity-driven CTP** (a temporary order is exploded and finitely scheduled into the live plan and the earliest feasible finish returned — SAP CTP/SBC, Oracle Make-CTP, D365 CTP, Epicor, SyteLine, Fulcrum, ProShop). Every CTP product runs it on **sales orders**; only SyteLine, VISUAL and Cetec expose it on a quote/estimate line, and then as a date only. No vendor holds capacity for a quote. Lead time is universally counted in **working days to ship**, with pick/pack/transit added separately, and purchased-material lead time and capacity are two constraints of which the later wins.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA / APO** — the reference: classic ATP with replenishment-lead-time fallback, MATP, finite CTP/SBC, backward-then-forward delivery scheduling.
+- **Oracle Fusion GOP / EBS ASCP** — three promising modes; Make-CTP with resource capacity; non-committal Check Availability vs committing Schedule.
+- **Microsoft D365 SCM / Business Central** — the delivery-date-control ladder; BC's what-if CTP with accept-to-reserve.
+- **Epicor Kinetic, Infor SyteLine/VISUAL, JobBOSS², ProShop, Cetec** — job-shop CTP as a temp-job simulation the estimator accepts.
+- **Odoo 17** — pure lead-time policy; the counter-example.
+- **Fulcrum, MRPeasy, Katana, Paperless Parts, Xometry, Protolabs** — one-click finite simulation vs customer-selected expedite tiers.
+
+## Key Consensus Patterns
+
+### 1. A ladder of promising modes, chosen per item and per line
+- **D365**: `Delivery date control` = None / Sales lead time / ATP / ATP + Issue margin / CTP / Batch CTP — global default, per-product override, per-line override. "At a minimum, CTP offsets delivery dates to the sales lead time."
+- **Oracle**: ATP-rule promising mode = Infinite / Lead time based / Supply chain availability search, plus a "Search components and resources" flag that turns on Make-CTP.
+- **SAP**: classic ATP (stock + receipts inside the replenishment lead time; beyond RLT everything is assumed available) → MATP → CTP.
+- **Rationale**: CTP is slow ("the CTP calculation isn't as fast as the ATP calculation") and only pays off for make/assemble-to-order items.
+
+### 2. CTP = explode a temporary order and finitely schedule it into the live plan
+- **SAP**: "Temporary planned orders are created … Capacities are then taken into account. A feasible availability date is determined in PP/DS from the result of scheduling these planned orders." PP/DS modes: *find slot* (first gap in the planning direction), *insert*, *squeeze in*, *infinite*.
+- **D365**: "CTP functionality is based on the explosion function" — BOM + route through the dynamic plan, finite capacity inside the capacity time fence, purchase lead times, transport days, safety margins.
+- **Epicor**: `CalculateCTP` builds an unfirm job and rough-cut finite-schedules it, honouring production buffers, queue/move, Receive Time, planning time fence and constrained-material lead times; "runs against the actual schedule and drops in the operations where it can and then returns a date."
+- **SyteLine**: Get ATP/CTP inserts the demand "into a temporary copy of the APS plan" at the due date; finite APS gives a "worst case … against an already loaded schedule."
+- **Fulcrum**: "simulates when a job would get finished if scheduled at that moment … based on the priority level of the job."
+
+### 3. Backward from the requested date; forward from today when infeasible
+- **SAP SD**: requested delivery − transit − loading − transportation lead time − pick/pack = material availability date; if that is in the past or unconfirmable, forward-schedule from the earliest ATP date and re-add the four times, each rounded on its own factory calendar.
+- **BC**: "requested delivery date − shipping time = planned shipment date; − outbound whse. handling time = shipment date"; if unavailable, calculate forward and write the earliest `Shipment Date`.
+- **D365**: the `Available ship and receipt dates` dialog pops when the requested date cannot be met and the user picks.
+- **Rationale**: "can we hit this date?" and "earliest feasible date" are one engine run in two directions.
+
+### 4. Requested vs confirmed; the system writes the confirmed date, the user may only loosen it
+- **SAP**: confirmed schedule lines; the user may push the date later or reduce quantity, never earlier or larger.
+- **Oracle**: Requested vs Scheduled (GOP output) vs Promised (tracking) dates; EBS `Promise Date` modes include "First Schedule Date" (frozen) and "Dependent on Schedule Date" (recomputed).
+- **D365**: `Confirmed ship/receipt date` set on every save of a CTP line, but re-promised **only when the existing promise can no longer be met** — a smaller quantity keeps the original date.
+- **SyteLine**: Projected date is recomputed every APS run; the due date is never overwritten; a Late Alert compares the two.
+
+### 5. Temporary supply becomes real only on save/accept; quotes never hold capacity
+- **SAP**: CTP temporary orders "exist only in the check session; converted to permanent on save, deleted otherwise." Quotation schedule line BN "No MRP" transfers nothing; BP does, and the valid-to date does **not** release it — a known trap.
+- **BC**: accepting CTP dates creates "a planning line and a reservation entry"; declining leaves nothing.
+- **D365**: CTP writes planned orders and capacity reservations, but plan runs historically replanned them — hence "Keep supply for confirmed demand" (10.0.48) and "Protect confirmed CTP dates" (GA Sep 2026). "Delivery date control method is not supported for a sales quotation line."
+- **Epicor**: `ConfirmCTP` firms the job; cancel discards it; "quotes are not associated with a job." **SyteLine**: an accepted CO line is incrementally planned, but "estimate lines are not incrementally planned." **Oracle EBS**: scheduling level "ATP Only" for inquiry-type transactions.
+- **Rationale**: quote win rates are well below 100 %; holding capacity per quote starves real orders. Quote expiry is cosmetic everywhere (Odoo: a ribbon; Hubs: price "valid for 30 days").
+
+### 6. Material lead time and capacity are separate constraints; the later wins
+- **SAP MATP**: each component checks against its own rule (a bought part with no stock confirms at the end of its RLT); the header is forward-scheduled from the latest component date.
+- **Oracle**: Buy-CTP applies supplier lead times as a hard constraint; Make-CTP checks resources; the promise is the max.
+- **Odoo 17**: `days_to_prepare_mo` = Compute → "the longest lead time among all the components listed on the BoM."
+- **Cetec** / **VISUAL** / **Fulcrum**: material availability gates operation start inside the finite engine.
+
+### 7. Working days, calendars, and a post-production buffer
+- **SAP**: scheduling-margin-key floats (before/after production, opening period) in workdays; safety time in working days.
+- **D365**: receipt / issue / reorder margins on working-day calendars; issue margin = ship-prep buffer; transport days by mode of delivery.
+- **BC**: `Offset (Time)` + inbound/outbound warehouse handling + shipping time. **Oracle**: a non-business-day result moves to the previous working day.
+- **Odoo**: the outlier — "lead times are based on calendar days … do not consider weekends, holidays, or work center capacity."
+- **Protolabs / Xometry**: lead times in business days **to ship**; shipping assumed separately (1-day expedite / 2-day standard).
+
+### 8. Expedite is a priority, priced as tiers
+- **Paperless Parts**: standard lead time plus "Days Faster" options each with a % markup, "expressed as relative days and percentage markup"; the customer picks; leaving standard blank gives each quantity break its own lead time.
+- **Xometry**: Economy / Standard / Expedited — "expedited orders receive prioritization in all aspects of order fulfillment." **SyteLine**: Expedited Fixed/Variable lead times feed Get CTP.
+- **SAP / Oracle / D365**: no named expedite mode; forward scheduling from today *is* the fastest date, and priority reallocation happens later (aATP backorder processing).
+
+## Answers to Research Questions
+
+1. **Inputs** — Routing standard times via work-center formulas (SAP, D365, Epicor, SyteLine, Fulcrum); the live finite load (all CTP products); component supply and supplier lead time (SAP MATP/RLT, Oracle Buy-CTP, Odoo `days_to_prepare_mo`, Epicor, Cetec); factory/shift calendars (all but Odoo); buffers (SAP floats + safety time, D365 margins, Odoo security leads, BC handling times, Epicor production buffers); a policy floor (D365 sales lead time, SAP RLT with no explosion, Protolabs per-process standard, SyteLine Fixed + Variable + Paperwork + Dock-to-Stock).
+2. **Modes** — Infinite (SAP classic ATP, Oracle Infinite/Lead-time, D365 Sales lead time/ATP, SyteLine infinite APS); finite earliest feasible (SAP CTP, Oracle supply-chain search + resources, D365 CTP, Epicor, SyteLine finite, Fulcrum, Cetec); "can we hit this date" (SAP backward scheduling, BC backward verify, D365 dialog on miss, SyteLine check-mark if projected ≤ due, ProShop phantom order); best case (job priority in Fulcrum; priced tiers in Paperless Parts/Xometry/Protolabs; Cetec conservative/optimistic; no ERP names a first-in-queue mode).
+3. **Surfacing** — A system-written confirmed/projected date beside the requested one, accepted or loosened (SAP, Oracle, D365, BC, SyteLine); a suggestion the estimator types over (MRPeasy "Estimate costs and dates", Katana auto deadline, Odoo read-only `expected_date` + editable `commitment_date`, Epicor's manual quote Lead Time field). Per quantity break only in Paperless Parts; Protolabs gives "the same quoted lead time" regardless of quantity. Recompute: D365 only when infeasible; SyteLine every APS run (reference only); Oracle frozen or live by mode; the rest on demand.
+4. **Quote-time reservation** — None. Temporary supply materialises on order save/accept (SAP, BC, D365, Oracle Schedule, Epicor `ConfirmCTP`, SyteLine CO line). SyteLine and Cetec answer on an estimate line but plan nothing; VISUAL loads quotes only as explicit what-if orders. Expiry releases nothing anywhere, and SAP BP quotes are a cautionary tale.
+5. **Materials vs capacity, rounding, shipping** — Promise = max(material date, capacity date), header forward-scheduled from the later (SAP MATP two-step, Oracle, Epicor). Working-day rounding on the factory/shift calendar (SAP, D365, BC, Oracle, SyteLine M-days); Odoo is calendar-day. Ship vs delivery separated by pick/pack + loading + transit (SAP), outbound handling + shipping time (BC), issue margin + transport days (D365); marketplaces quote days to ship.
+
+## Competitor-Specific Details
+
+**SAP** — Classic ATP never reads routing. MATP stores an "ATP tree", not a receipt. CTP is incompatible with safety stock, period lot sizes and backorder processing. S/4HANA SBC (2022+, aATP + ePP/DS licences) recreates supply on every MTO recheck.
+
+**Oracle** — Infinite-availability time fence (beyond it, promise on request date) and ATP time fence (inside it, search existing supply before CTP). Resource need = qty × usage / (yield × efficiency × utilization). Fusion 25D pulls scheduled dates earlier when supply arrives early, gated by an `Override Schedule` flag.
+
+**Microsoft** — D365 "Near real-time CTP" (10.0.41+) computes in the background per line save; "Batch CTP" every N minutes with a Not ready/Ready status. BC CTP applies only to the uncovered remainder ("10 ordered, 6 available → CTP on 4") and requires the item flagged `Critical`.
+
+**Job shops** — SyteLine: lead-time start = due − FLT − int(VLT × qty / hrs per day + .499). VISUAL: the one scheduler that natively loads "planned orders and quotes." JobBOSS²: "auto-default the promise date to lead times" is still a user idea. ProShop: lead time typed; capacity checked by phantom job placement. Cetec Build Estimate: start + ship date from on-hand, component lead times and labour, view-only.
+
+**Odoo** — `expected_date = date_order + customer_lead`, nothing else; MO/PO dates back-schedule from it; the MO Plan button forward-schedules work orders on work-center calendars but never moves the SO date.
+
+## Recommended Approach for Carbon
+
+Carbon already has the hard part: a forward-ASAP finite scheduler over `capacityReservation` (`packages/planning/src/scheduling/run-schedule.ts`; `runExpediteWhatIf` with `persist:false` returning `{ projectedCompletionAt, cause }`), `quoteOperation` rows carrying setup/labor/machine times and work centers column-for-column with `jobOperation`, `itemReplenishment.leadTime` for purchased parts, and an unused `capacityReservation.scenarioId`. What is missing is the glue.
+
+1. **A mode ladder per line, not a replacement (D365).** Keep the typed `quoteLinePrice.leadTime` as the policy mode and add a computed suggestion beside it, floored at an item/company minimum lead time.
+2. **CTP = a what-if run of the existing engine seeded from `quoteOperation`, not a job (SAP temporary planned order; SyteLine "temporary copy of the plan"; Fulcrum).** Generalise `runExpediteWhatIf` to take a synthetic operation set (quote make method × quantity) placed at end of queue over the live reservation snapshot, `persist:false`. Return `{ promiseDate, confidence, cause }` — the `getJobPromiseDate` contract already exists with no caller.
+3. **Two modes from one engine.** *Earliest feasible* = end of queue; *best case* = the synthetic job ordered first (what the expedite what-if already does). "Can we hit this date?" = feasible ≤ requested, reporting `cause` (bottleneck work center vs material) — no surveyed vendor computes "what would have to move" for a quote, and neither should Carbon in v1.
+4. **Material-driven floor (SAP MATP; Odoo `days_to_prepare_mo`).** Take max over `quoteMaterial` Buy lines of `itemReplenishment.leadTime` net of on-hand at the quote location, start the synthetic operations no earlier than that, and say which constraint won.
+5. **Per quantity break, on demand, frozen (Paperless Parts; Oracle "First Schedule Date").** Run per pricing-grid row when the estimator asks, write the accepted value into `leadTime`, and record `leadTimeSource: 'system' | 'manual'` next to the existing `priceSource`. Never auto-recompute a sent quote; on reopen offer "recalculate" with the delta.
+6. **No quote-time reservation.** Unanimous. Do not write `scenarioId` rows for quotes; a soft booking, if ever wanted, is a sales-order feature (D365 "Keep supply for confirmed demand").
+7. **Working days plus a ship buffer.** Convert the engine's completion timestamp to whole business days on the location shifts (`need-by-calculator.ts` `workingDayTest`), add a location `shippingBufferDays` (D365 issue margin; BC outbound handling), and fix `convert/index.ts`, which sets `promisedDate = now + leadTime × 86 400 000` on calendar days. Prior art: `quoteShipment.leadTime` (migration `20260206061346`) was reverted three days later — the quote header was the wrong grain; the per-quantity-break line is right.
+
+## Sources
+
+- https://help.sap.com/doc/saphelp_scm700_ehp02/7.0.2/en-US/4c/56297de7c33a0de10000000a42189c/content.htm?no_cache=true
+- https://help.sap.com/saphelp_SCM700_ehp01/helpdata/en/a9/27c95360267614e10000000a174cb4/content.htm?no_cache=true
+- https://help.sap.com/saphelp_SCM700_ehp02/helpdata/en/4c/4e5b37eb096ad8e10000000a42189c/content.htm?no_cache=true
+- https://help.sap.com/saphelp_SCM700_ehp02/helpdata/en/f0/40c95360267614e10000000a174cb4/content.htm?no_cache=true
+- https://help.sap.com/doc/saphelp_snc70/7.0/en-US/21/7acc37d2fee941e10000009b38f8cf/content.htm?no_cache=true
+- https://help.freedsap.com/ENHELPhtml/PPMRP/AvailabilityCheckWithorWithoutRe.html
+- https://learning.sap.com/courses/exploring-aatp-in-sap-s-4hana/outlining-supply-based-confirmation-sbc-
+- https://learning.sap.com/courses/exploring-advanced-production-planning-with-sap-s-4hana-pp-ds/exploring-concepts-and-principles-of-detailed-scheduling
+- https://blog.sap-press.com/delivery-scheduling-and-transportation-scheduling-in-sap-s4hana
+- https://blog.sap-press.com/atp-checks-in-s4hana-sales
+- https://www.stechies.com/where-the-schedule-margin-key-is-customized/
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/atp-at-quotation/qaq-p/8699789
+- https://community.sap.com/t5/enterprise-resource-planning-q-a/quotation-appearing-on-md04-list-instead-of-sales-order/qaq-p/7654130
+- https://thesdvault.com/sap-advanced-atp-s4hana
+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/24c/fascp/atp-rule-promising-modes.html
+- https://docs.oracle.com/en/cloud/saas/supply-chain-management/21d/fascp/order-promising-rules.html
+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25c/fascp/check-availability.html
+- https://docs.oracle.com/en/cloud/saas/supply-chain-and-manufacturing/25d/faiom/set-promised-ship-and-arrival-dates-on-fulfillment-lines.html
+- https://docs.oracle.com/cd/E18727_01/doc.121/e13378/T474179T474185.htm
+- https://docs.oracle.com/cd/E18727_01/doc.121/e13406/T373258T377249.htm
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/planning-optimization/calculate-delivery-dates-using-ctp
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/sales-marketing/delivery-dates-available-promise-calculations
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/sales-marketing/delivery-alternatives
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/planning-optimization/safety-margins
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/master-planning/planning-optimization/keep-supply-for-confirmed-demand
+- https://learn.microsoft.com/en-us/dynamics365/release-plan/2026wave1/enterprise-resource-planning/dynamics365-supply-chain-management/protect-confirmed-ctp-dates-planning-optimization
+- https://community.dynamics.com/forums/thread/details/?threadid=a72157a6-6faa-4dda-bc77-d071835535d1
+- https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-to-calculate-order-promising-dates
+- https://learn.microsoft.com/en-us/dynamics365/business-central/purchasing-date-calculation-for-purchases
+- https://probitas.co.uk/2022/01/14/available-and-capable-to-promise-in-business-central-part-two/
+- https://www.epiusers.help/t/capable-to-promise/89981
+- https://www.epiusers.help/t/quote-entry-lead-time-field/48890
+- https://www.epiusers.help/t/promise-dates-vs-running-balance-vs-aps-ctp/104057
+- https://www.epiusers.help/t/dating-orders-dare-i-open-the-ctp-can-of-worms/125533
+- https://erp.smcusa.com/SyteLine/Language/en-US/mergedProjects/sl_invprod/buttons/g/get_atp_ctp_button.htm
+- https://docs.infor.com/csi/2026.x/en-us/csbiolh/inventory_user_cl_sl/mergedprojects/sl_invprod/forms/system/availability_results.html
+- https://docs.infor.com/csi/9.01.x/en-us/csbiolh/mergedprojects/sl_invprod/fields/p/projected_order_line_maintenance.htm
+- https://wm-synergy.com/products/infor-visual-erp-scheduling/
+- https://www.ecisolutions.com/products/jobboss2/features/scheduling/
+- https://proshoperp.com/product/estimating-quoting/
+- https://proshoperp.com/blog/better-shop-floor-scheduling/
+- https://cetecerp.com/blog/using-cetec-erp-build-estimates-for-accurate-quotes-and-delivery-dates/
+- https://fulcrumpro.com/manufacturing-software/quoting-software-for-manufacturing
+- https://fulcrumpro.com/workflows/cnc-machine-shop
+- https://www.mrpeasy.com/resources/user-manual/crm/customer-orders/details/
+- https://support.katanamrp.com/en/articles/5914341-how-to-manage-production-deadlines
+- https://support.katanamrp.com/en/articles/5914243-managing-quotes
+- https://help.paperlessparts.com/s/article/dynamic-lead-times-guide
+- https://www.paperlessparts.com/blog/can-we-get-the-parts-sooner-sure/
+- https://www.xometry.com/resources/blog/lead-time-options/
+- https://www.protolabs.com/help-center/lead-times/
+- https://www.hubs.com/help-center/how-to-get-a-quote/
+- https://www.odoo.com/documentation/17.0/applications/inventory_and_mrp/inventory/warehouses_storage/replenishment/lead_times.html
+- https://raw.githubusercontent.com/odoo/odoo/17.0/addons/sale/models/sale_order_line.py
+- https://raw.githubusercontent.com/odoo/odoo/17.0/addons/mrp/models/mrp_bom.py
+- https://www.odoo.com/forum/help-1/how-to-deal-with-maximum-manufacturing-capacity-per-day-when-planning-203797
diff --git a/.ai/specs/2026-09-22-quote-lead-time-prediction.md b/.ai/specs/2026-09-22-quote-lead-time-prediction.md
new file mode 100644
index 0000000000..3fa6cf344d
--- /dev/null
+++ b/.ai/specs/2026-09-22-quote-lead-time-prediction.md
@@ -0,0 +1,204 @@
+# Quote line lead time prediction (capable-to-promise)
+
+**Status:** design resolved, awaiting veto
+**Research:** `.ai/research/quote-lead-time-prediction.md`
+**Plan:** `.ai/plans/2026-09-22-quote-lead-time-prediction.md`
+**Related:** `.ai/specs/implemented/2026-08-12-forecast-first-finite-scheduling.md` §7
+(names "capable-to-promise on a quote — inject a shadow job, run the sim, don't
+persist" as the v1.x candidate); `.ai/specs/2026-08-22-mrp-v2-planned-order-generation.md`
+§4 (the rough-cut, plan-based what-if — a different, later layer).
+
+## Problem
+
+`quoteLinePrice.leadTime` (days, per quantity break) is typed by hand. Every
+system-priced row seeds it at 0 (`sales.service.ts:4590/4684/4783`,
+`functions/lib/methods.ts:861`), the finalize gate only warns when it is still 0
+(`QuoteFinalizeModal.tsx:121-138`), and on conversion it becomes
+`salesOrderLine.promisedDate = today + leadTime` (`convert/index.ts:696-701`),
+which then becomes the job's due date. So the number that drives the customer
+promise, the job deadline and MRP's demand date is a guess, made without looking
+at the shop.
+
+The shop's state is already known: the finite scheduler holds every open job's
+`capacityReservation` rows, the work-center calendars, the manning board, and a
+proven simulate-without-persist seam (`runExpediteWhatIf`). A quote line carries
+a full routing (`quoteOperation` has the same time model as `jobOperation`) and
+BOM (`quoteMakeMethod` / `quoteMaterial`). Nothing joins the two.
+
+## Goal
+
+From the quote line pricing grid, the estimator picks ONE constraint, sees the
+answer it gives for every quantity break, and applies it to all of them at once.
+A quote never mixes constraints across its breaks — a customer reading "10 pcs
+in 12 days, 50 pcs in 9 days" would be looking at one row promised as best case
+and another as queued. The three constraints:
+
+| Answer | Question it answers | How |
+|---|---|---|
+| **End of queue** | If we order this today and it waits its turn behind everything already released, when is it done? | Forward-ASAP finite placement of the quote's routing against the LIVE reservation snapshot (`excludeJobIds: []`) |
+| **Best case** | If we put it at the front of the line? | Same placement with the location's open jobs excluded from the snapshot (exactly what `runExpediteWhatIf` does for a job) |
+| **Target date** | Can we hit the customer's date? | Compare both finishes with the entered date: on time as queued / only by expediting / not even then, with the days of slack or shortfall |
+
+Every answer carries the bottleneck sentence the engine already composes
+(conflict reason or the largest wait attribution), and the materials floor
+(the longest purchased-material lead time that gates an operation) is reported
+separately so an estimator can see whether the number is capacity-bound or
+material-bound.
+
+Nothing is persisted by the simulation. Applying writes `quoteLinePrice.leadTime`
+for every quantity break in one state update plus one write per row (a new
+`onUpdateLeadTimes` beside the grid's `onUpdatePrice`, which is single-cell and
+snapshots state per call), so the preservation contract
+(`resolvePreservedQuoteLinePriceFields`) and every downstream reader are untouched.
+Under the target-date constraint the value written is the same for every break
+(days from today to the date); the per-row verdict says whether the shop can
+actually meet it, and applying is blocked while any break is not feasible.
+
+## Design
+
+### The simulation is the finite scheduler's pure core, fed synthetic operations
+
+`SchedulingEngine.initialize()` reads a job by id and cannot take operations in.
+But the placement core is already pure and test-driven with hand-built inputs:
+`WorkCenterSelector.selectWorkCentersForOperations(operations, { jobDueDate })`
+over an injected `FiniteSchedulingContext` (`determinism.test.ts`,
+`envelope.test.ts`). The feature drives that seam:
+
+1. **Load the quote line's routing** (`quoteMakeMethod`, `quoteMaterial`,
+ `quoteOperation` for the line, under `companyId`) with Kysely.
+2. **Build synthetic `BaseOperation`s per quantity break.** `operationQuantity` =
+ quantity × the product of `quoteMaterial.quantity` down the make-method chain
+ (the same walk `buildCostEffects` does for costing). `quantityComplete = 0`,
+ `jobId = "quote:<quoteLineId>:<quantity>"`, ids are the `quoteOperation` ids.
+ Durations then come from the engine's own `calculateDurationHours`
+ (`setup + max(labor, machine)`, per-piece units scaled by quantity, `Total
+ Hours` fixed per run) — one duration model for jobs and quotes.
+3. **Build dependencies** exactly as `createDependencies` does for a job:
+ `buildOperationDependencies` inside each make method ("After Previous" /
+ "With Previous"), plus the assembly edge from a child method's last operation
+ to the parent's consuming operation (`quoteMaterial.quoteOperationId` of the
+ material whose id is the child's `parentMaterialId`, else the parent's first
+ operation).
+4. **Build the finite context once per scenario** from the location-wide reads
+ (`buildFiniteContext`, lifted out of the engine into a shared module so the
+ engine and the quote what-if cannot drift). Two scenarios: live snapshot
+ (`excludeJobIds: []`) and front-of-queue (`excludeJobIds` = the location's
+ ordered open-job batch, mirroring `runExpediteWhatIf`). Released batches keep
+ their reservations in both, as they do for the expedite what-if.
+5. **Place, once per (quantity, scenario)**, on a cloned context — the selector
+ mutates reservation arrays as it places, so every run gets fresh copies.
+ Projected finish = the max placed end. Lead time = calendar days from today
+ to the finish, both in the location's timezone, minimum 1.
+6. **Report**, never persist.
+
+### Material readiness is a per-operation floor, not a separate number
+
+A purchased part gates the operation that consumes it, and only that operation:
+downstream ops shift, parallel branches do not. The engine has no such floor
+today (jobs assume material is on hand). This spec adds an **optional**
+`materialReadyAt` (epoch ms) on `BaseOperation`, honored at the two
+earliest-start sites in `work-center-selector.ts` as
+`earliestMs = max(earliestMs, op.materialReadyAt)`. The job path never sets it,
+so live scheduling is byte-identical (pinned by the determinism suite).
+
+For the quote: a `Purchase to Order` material floors its consuming op at
+`now + itemReplenishment.leadTime` days (default 7, the same fallback MRP uses);
+a `Pull from Inventory` material floors it only when `itemStockQuantities`
+on-hand at the location is below the required quantity (the same aggregate
+`runMrp` reads at `mrp.ts:277`); a `Make to Order` material is a child make
+method and is scheduled, not floored. `materialReadyDays` in the result is the
+largest floor, so the modal can say "materials gate this at N days" next to
+the capacity answer.
+
+### Where it lives
+
+- `packages/planning/src/scheduling/finite-context.ts` — `buildFiniteContext`
+ and `loadAvailabilityWindows` extracted from `scheduling-engine.ts` into a
+ standalone function the engine delegates to. Refactor only; no behavior change.
+- `packages/planning/src/scheduling/quote-lead-time.ts` — the pure builders
+ (`buildQuoteSimulation`: quote rows → operations + dependencies + material
+ floors per quantity), `cloneFiniteContext`, and the orchestrator
+ `runQuoteLeadTimeWhatIf`. Exported from `@carbon/planning` next to
+ `runExpediteWhatIf`.
+- `apps/erp/app/routes/x+/quote+/$quoteId.$lineId.lead-time.tsx` — POST action,
+ `view: "sales"` (read-only what-if, same reasoning as `$jobId.expedite.tsx`),
+ re-reads the quote under `companyId`, resolves the location, calls the
+ what-if, returns `{ forecast }`.
+- `apps/erp/app/modules/sales/ui/Quotes/QuoteLeadTimeModal.tsx` — precedent
+ `JobExpediteModal` in `JobHeader.tsx`; opened from a button on the "Lead Time"
+ row of `QuoteLinePricing.tsx`; applies the chosen constraint to every
+ quantity break through `onUpdateLeadTimes` (one state update, one write per row).
+
+### Result shape
+
+```ts
+type QuoteLeadTimeScenario = {
+ finishAt: string | null; // ISO instant of the last placed end
+ leadTimeDays: number | null; // calendar days from today (location tz), min 1
+ cause: string | null; // first conflict, else the longest wait's note
+};
+type QuoteLeadTimeForecast = {
+ quoteLineId: string;
+ locationId: string;
+ computedAt: string;
+ quantities: Array<{
+ quantity: number;
+ materialReadyDays: number; // 0 when nothing gates
+ queued: QuoteLeadTimeScenario; // end of queue
+ bestCase: QuoteLeadTimeScenario; // front of queue
+ target: { // present only when a dueDate was sent
+ date: string; // YYYY-MM-DD
+ verdict: "on-time" | "expedite" | "late";
+ slackDays: number; // negative = short, vs the queued finish
+ } | null;
+ }>;
+ assumptions: string[]; // rendered verbatim in the modal
+};
+```
+
+`assumptions` is fixed copy from the engine, e.g. "Placed after every job
+already released at {location}", "Purchased material is available after its
+item lead time; stock is netted at {location} only", "No shipping buffer is
+added" — the number must not silently become a guarantee (the same rule the
+MRP v2 spec applies to its plan-based promise).
+
+## Decisions (recommendations applied; veto any)
+
+| Decision | Choice | Why |
+|---|---|---|
+| Engine seam | Drive `WorkCenterSelector` directly with synthetic ops; do not teach `SchedulingEngine` to accept a fake job | `initialize`/`assignMaterials`/`createDependencies` read job tables with raw Kysely; faking a job means faking four tables. The selector is already the pure, tested unit. |
+| Shared context builder | Extract `buildFiniteContext` from the engine into `finite-context.ts` | Two copies of a 220-line loader would drift on the next people-board or calendar change; the determinism suite pins the extraction. |
+| Material floor | Optional per-op `materialReadyAt` in the selector, unset for jobs | Floors belong on the consuming op, and the change is invisible to live scheduling. A separate "max material lead time" number would be wrong for any routing with work before the purchased part is needed. |
+| Unit of the answer | Calendar days from today, location timezone, minimum 1 | `convert` turns `leadTime` into `promisedDate = today + N`, so calendar days is the only unit that round-trips; finalize treats 0 as unfilled. |
+| Modes | End of queue + best case, plus a target-date verdict; no "infinite capacity" mode | Infinite capacity is what the manual guess already is. Best case is the expedite what-if the shop already trusts. |
+| Persistence | None from the sim; accept writes `leadTime` via `onUpdateLeadTimes` | Zero migration, zero new preservation cases. A `leadTimeSource` column (mirroring `priceSource`) is a follow-up if provenance is wanted. |
+| Apply granularity | One constraint, applied to every quantity break together; no per-cell accept | A quote's breaks must be promised on the same basis. Per-cell buttons invite mixing best case on one row with queued on another. (Brad, 2026-09-22) |
+| Trigger | Manual button on the Lead Time row, not auto-fill on price recalc | Recalc runs on every markup change; a sim per recalc would be wasted work and a moving number under the estimator's cursor. |
+| Location | `quote.locationId`, else the user's default location, else a clear error | The reservation snapshot, calendars and stock are per location; there is no company-wide answer. |
+| Shipping / safety buffer | None in v1 | No company setting exists for it; adding one is a separate decision. The modal says so in `assumptions`. |
+| Scope of routing | Every make method in the quote line's tree, including sub-assemblies | Sub-assembly edges are the same as the job engine's; omitting them would under-promise every assembly. |
+| Outside processing | Placed as the engine places it (calendar time from `operationLeadTime`) | Same code path, no special case. |
+| Scenario reservations | Not written (`capacityReservation.scenarioId` stays unused) | Nothing reads scenarios yet; writing them buys a Gantt overlay nobody asked for. |
+
+## Out of scope
+
+- Auto-filling `leadTime` on quote creation or price recalculation.
+- Quote-time capacity reservations (soft booking) and their expiry.
+- A `leadTimeSource` / provenance column on `quoteLinePrice`.
+- Customer share page or PDF changes — they already render `leadTime`.
+- Working-day (vs calendar-day) conversion of the customer-facing number.
+- The MRP v2 plan-based what-if (`runPlanningWhatIf`) — a different layer.
+- Ability-gated labor for the quote's ops beyond what the context already
+ models (the sim uses the same gating the job engine does; no extra work).
+
+## Risks
+
+- **Quotes with no times.** An operation with zero time standards places
+ instantly; a routing of only zeros yields "1 day". The modal shows the
+ operation count with zero standards so the estimator knows the number is
+ hollow. (Task 5 renders `assumptions` and the zero-standard count.)
+- **Quote location without calendars.** The ladder falls back to the stock
+ Mon–Fri 8h week, as it does for jobs.
+- **Cost.** One context build per scenario (two per request) plus one pure
+ placement per (quantity × scenario); the envelope test places 2000 ops in
+ under 10 s, a quote routing is tens of ops.
diff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.md
index 30311191ff..2825dec7b2 100644
--- a/.claude/rules/scheduling-data-structures.md
+++ b/.claude/rules/scheduling-data-structures.md
@@ -25,6 +25,17 @@ many times — read the newest, not the first match.
Spec/plan: `.ai/specs/2026-08-19-schedule-in-process-node.md` +
`.ai/plans/2026-08-19-schedule-in-process-node.md`.
+**Capable-to-promise on a quote** (`quote-lead-time.ts`,
+`runQuoteLeadTimeWhatIf`): the pure `WorkCenterSelector` is driven with SYNTHETIC
+ops built from a quote line's routing/BOM (`buildQuoteSimulation`), placed per
+quantity against TWO `buildFiniteContext` snapshots — queued (`excludeJobIds:
+[]`) and front-of-queue (whole batch excluded, like the expedite what-if). A
+purchased/short-stock material sets the optional `materialReadyAt` floor on its
+consuming op (never set on jobs, so live scheduling is unchanged). Persists
+nothing; `buildFiniteContext` + `loadAvailabilityWindows` were lifted out of the
+engine into `finite-context.ts` so the engine and this what-if cannot drift.
+Spec/plan: `.ai/specs/2026-09-22-quote-lead-time-prediction.md`.
+
## Where it lives
- **Orchestration:** `packages/planning/src/scheduling/run-schedule.ts`
@@ -531,3 +542,8 @@ capacity-planning migration and drive the dates board's forecast/stale surfaces.
not even notify — it only re-sequences `workCenterId` + `priority`. The dates board
notifies (`notifyScheduleInputsChanged`), and the debounced wave regenerates the whole
location. The MES board is display/drag-only.
+- The selector MUTATES each context's reservation arrays as it places, so the quote
+ what-if runs every simulation on a `cloneFiniteContext` copy (`quote-lead-time.ts`) —
+ reusing one context across quantities/scenarios would let earlier runs' placements
+ bleed into later ones. One `WorkCenterSelector` instance is fine (it resets
+ `plannedReservations` per call), but the CONTEXT must be cloned per run.
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index 18155074ee..4060c27acb 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -7,7 +7,7 @@ Quotes (with cost rollup and pricing), sales orders, sales RFQs, customer manage
- **Opportunity** — deal container linking RFQs, quotes, and sales orders for one customer engagement.
- **Quote** — detailed cost estimate with line items, each having a make method (BOM + routing) and quantity-break pricing. Statuses: Draft → Pending → Sent → Ordered / Lost / Cancelled.
- **Quote Revision** — `quote.revisionId`. Unlike a PO (amended in place), a quote revision is a **new `quote` row** created by `copyQuote` → the `get-method` edge function (`quoteToQuote`, `asRevision: true`), keeping the same `quoteId` with `revisionId = max + 1`, sharing the source `opportunityId`. Each revision gets its **own `externalLink`** row, whose `documentId` is revision-qualified (`Q000001-1`) because `externalLink` is UNIQUE on `(documentId, documentType, companyId)` — an unqualified id collides with the original's link. `deleteQuote` does not remove the link row, so that insert uses `onConflict … doUpdateSet` to reuse the orphan a deleted revision left behind. Displayed as `Q000001-1` when > 0 via `getQuoteDisplayId` (`@carbon/documents/utils`) on the PDF, email, share page, and filenames; two-tone in-app rendering uses `<RevisionSuffix>` (`~/components`).
-- **Quote Line Pricing** — per-quantity-break pricing. PK is `(quoteLineId, quantity)` — no `id` column. `discountPercent` is a **fraction 0–1** (not 0–100). Generated columns compute net/converted prices.
+- **Quote Line Pricing** — per-quantity-break pricing. PK is `(quoteLineId, quantity)` — no `id` column. `discountPercent` is a **fraction 0–1** (not 0–100). Generated columns compute net/converted prices. **Lead time can be PREDICTED from the shop schedule** rather than typed: the calendar-clock button on the Lead Time row opens `QuoteLeadTimeModal`, which POSTs `$quoteId.$lineId.lead-time.tsx` → `runQuoteLeadTimeWhatIf` (`@carbon/planning`) and applies one constraint's value to every break at once. The write goes through the grid's `onUpdateLeadTimes` (`quoteLinePrice.leadTime`, one state update for every break — never a loop over `onUpdatePrice`, which snapshots state per call; a failed row is rolled back and the modal stays open) — no new persistence, so `resolvePreservedQuoteLinePriceFields` is untouched.
- **Pricing Rules** — company-scoped Discount/Markup rules. Discounts are non-stacking (highest-priority wins); Markups stack and compound in priority order.
- **Price Overrides** — customer-specific or type-specific price overrides with quantity breaks via `customerItemPriceOverride` / `customerItemPriceOverrideBreak`. Precedence: customer > customer-type > all-customers > base price.
- **Sales Order** — confirmed order from a quote. Lines carry `methodType` (Make to Order, Make to Stock, etc.) that determines production handling.
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index b40a7cbf98..02d93a96b1 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -1070,6 +1070,17 @@ export const selectedLineSchema = z.object({
export const selectedLinesValidator = z.record(z.string(), selectedLineSchema);
+// Quote lead-time prediction — a JSON body (not FormData), so plain zod.
+export const quoteLeadTimeValidator = z.object({
+ // Each quantity runs two full scheduling simulations; cap the per-request work.
+ quantities: z.array(z.number().positive()).min(1).max(50),
+ dueDate: z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
+ .optional()
+ .nullable()
+});
+
// Sales Order Locked Status
export const SALES_ORDER_LOCKED_STATUSES = [
"To Ship and Invoice",
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLeadTimeModal.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLeadTimeModal.tsx
new file mode 100644
index 0000000000..b6bd7cca3d
--- /dev/null
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLeadTimeModal.tsx
@@ -0,0 +1,483 @@
+import {
+ Badge,
+ Button,
+ cn,
+ DatePicker,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Spinner,
+ Tabs,
+ TabsList,
+ TabsTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import {
+ type CalendarDate,
+ getLocalTimeZone,
+ today
+} from "@internationalized/date";
+import { Plural, Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useState } from "react";
+import { LuTriangleAlert } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import type { action } from "~/routes/x+/quote+/$quoteId.$lineId.lead-time";
+import { path } from "~/utils/path";
+
+type Constraint = "queued" | "bestCase" | "target";
+
+// Plural via <Plural> so "day"/"days" is translated, not interpolated as a
+// runtime English literal.
+const Days = ({ value }: { value: number }) => (
+ <Plural value={value} one="# day" other="# days" />
+);
+
+const HEAD_CELL = "whitespace-nowrap py-2 pr-6 text-left font-medium";
+const CELL = "py-3 pr-6 align-top";
+
+type QuoteLeadTimeModalProps = {
+ quoteId: string;
+ lineId: string;
+ quantities: number[];
+ isEditable: boolean;
+ onApply: (leadTimeByQuantity: Record<number, number>) => Promise<void>;
+ onClose: () => void;
+};
+
+const QuoteLeadTimeModal = ({
+ quoteId,
+ lineId,
+ quantities,
+ isEditable,
+ onApply,
+ onClose
+}: QuoteLeadTimeModalProps) => {
+ const { t } = useLingui();
+ const fetcher = useFetcher<typeof action>();
+
+ const [constraint, setConstraint] = useState<Constraint>("queued");
+ const [targetDate, setTargetDate] = useState<CalendarDate | null>(null);
+ const [applying, setApplying] = useState(false);
+
+ const leadTimeAction = path.to.quoteLineLeadTime(quoteId, lineId);
+
+ // Predict on mount (queued + best case). The target verdict needs a due date,
+ // so it is only requested when the estimator picks one.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: run once on mount
+ useEffect(() => {
+ fetcher.submit(
+ { quantities },
+ { method: "post", encType: "application/json", action: leadTimeAction }
+ );
+ }, []);
+
+ const onTargetDateChange = (date: CalendarDate | null) => {
+ setTargetDate(date);
+ if (date) {
+ fetcher.submit(
+ { quantities, dueDate: date.toString() },
+ { method: "post", encType: "application/json", action: leadTimeAction }
+ );
+ }
+ };
+
+ const loading = fetcher.state !== "idle";
+ const forecast = fetcher.data?.forecast ?? null;
+ const error = fetcher.data?.error ?? null;
+
+ const localToday = today(getLocalTimeZone());
+ const targetLeadTime = targetDate ? targetDate.compare(localToday) : null;
+
+ const rows = forecast?.quantities ?? [];
+ const anyLate =
+ constraint === "target" &&
+ rows.some((row) => row.target?.verdict === "late");
+
+ // A break the scheduler could not place has no estimate; applying would
+ // silently update only the others.
+ const anyUnestimated =
+ constraint !== "target" &&
+ rows.some((row) => row[constraint].leadTimeDays === null);
+
+ const applyDisabled =
+ !isEditable ||
+ loading ||
+ !forecast ||
+ anyUnestimated ||
+ (constraint === "target" && (!targetDate || anyLate));
+
+ const handleApply = async () => {
+ if (!forecast) return;
+ const map: Record<number, number> = {};
+ for (const row of rows) {
+ if (constraint === "target") {
+ if (targetLeadTime !== null) map[row.quantity] = targetLeadTime;
+ } else {
+ const days = row[constraint].leadTimeDays;
+ if (days !== null) map[row.quantity] = days;
+ }
+ }
+ setApplying(true);
+ try {
+ await onApply(map);
+ onClose();
+ } catch {
+ // onApply already reported the failure; stay open so it can be retried.
+ } finally {
+ setApplying(false);
+ }
+ };
+
+ const constraintHelp =
+ constraint === "queued" ? (
+ <Trans>
+ If ordered today — placed behind everything already released.
+ </Trans>
+ ) : constraint === "bestCase" ? (
+ <Trans>As if it jumped to the front of the shop's queue.</Trans>
+ ) : (
+ <Trans>Both finishes compared against a date you choose.</Trans>
+ );
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent size="xlarge">
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Predict lead time</Trans>
+ </ModalTitle>
+ <ModalDescription>
+ <Trans>
+ Scheduled against your shop's current workload. Nothing is saved
+ until you apply.
+ </Trans>
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-1.5">
+ <Tabs
+ value={constraint}
+ onValueChange={(value) => setConstraint(value as Constraint)}
+ >
+ <TabsList>
+ <TabsTrigger value="queued">
+ <Trans>End of queue</Trans>
+ </TabsTrigger>
+ <TabsTrigger value="bestCase">
+ <Trans>Best case</Trans>
+ </TabsTrigger>
+ <TabsTrigger value="target">
+ <Trans>Target date</Trans>
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ <div className="flex min-h-9 flex-wrap items-center gap-3">
+ <p className="text-sm text-muted-foreground text-pretty">
+ {constraintHelp}
+ </p>
+ {constraint === "target" && (
+ <DatePicker
+ aria-label={t`Target date`}
+ value={targetDate}
+ onChange={onTargetDateChange}
+ minValue={localToday}
+ />
+ )}
+ </div>
+ </div>
+
+ <div className="mt-4">
+ {loading ? (
+ <div className="flex flex-col items-center justify-center gap-3 py-16">
+ <Spinner className="size-6" />
+ <p className="text-sm text-muted-foreground">
+ <Trans>Predicting lead time…</Trans>
+ </p>
+ </div>
+ ) : error ? (
+ <div className="flex items-start gap-2 rounded-lg bg-destructive/10 p-4 text-destructive">
+ <LuTriangleAlert className="mt-0.5 size-4 shrink-0" />
+ <div className="flex flex-col gap-0.5">
+ <p className="text-sm font-medium">
+ <Trans>Could not predict lead time</Trans>
+ </p>
+ <p className="text-sm opacity-90">{error}</p>
+ </div>
+ </div>
+ ) : !forecast ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ <Trans>This line has no routing to schedule.</Trans>
+ </p>
+ ) : constraint === "target" && !targetDate ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ <Trans>Pick a target date to compare.</Trans>
+ </p>
+ ) : (
+ <>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-border text-muted-foreground">
+ <th className={HEAD_CELL}>
+ <Trans>Qty</Trans>
+ </th>
+ <th className={HEAD_CELL}>
+ <Trans>Materials</Trans>
+ </th>
+ {constraint === "target" ? (
+ <>
+ <th className={HEAD_CELL}>
+ <Trans>Queued finish</Trans>
+ </th>
+ <th className={HEAD_CELL}>
+ <Trans>Best-case finish</Trans>
+ </th>
+ <th className={HEAD_CELL}>
+ <Trans>Verdict</Trans>
+ </th>
+ <th className={cn(HEAD_CELL, "pr-0")}>
+ <Trans>Lead time</Trans>
+ </th>
+ </>
+ ) : (
+ <>
+ <th className={HEAD_CELL}>
+ <Trans>Finish</Trans>
+ </th>
+ <th className={HEAD_CELL}>
+ <Trans>Lead time</Trans>
+ </th>
+ <th className={cn(HEAD_CELL, "pr-0")}>
+ <Trans>Bottleneck</Trans>
+ </th>
+ </>
+ )}
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-border">
+ {rows.map((row) => {
+ const materials =
+ row.materialReadyDays > 0 ? (
+ <Days value={row.materialReadyDays} />
+ ) : (
+ "—"
+ );
+ if (constraint === "target") {
+ const target = row.target;
+ return (
+ <tr key={row.quantity}>
+ <td
+ className={cn(
+ CELL,
+ "font-medium tabular-nums text-foreground"
+ )}
+ >
+ {row.quantity}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "tabular-nums text-muted-foreground"
+ )}
+ >
+ {materials}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "whitespace-nowrap tabular-nums"
+ )}
+ >
+ {row.queued.finishAt
+ ? formatDate(row.queued.finishAt.slice(0, 10))
+ : "—"}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "whitespace-nowrap tabular-nums"
+ )}
+ >
+ {row.bestCase.finishAt
+ ? formatDate(
+ row.bestCase.finishAt.slice(0, 10)
+ )
+ : "—"}
+ </td>
+ <td className={CELL}>
+ {target ? (
+ <div className="flex flex-col items-start gap-1">
+ {target.verdict === "on-time" ? (
+ <Badge variant="green">
+ <Trans>On time</Trans>
+ </Badge>
+ ) : target.verdict === "expedite" ? (
+ <Badge variant="orange">
+ <Trans>Needs expedite</Trans>
+ </Badge>
+ ) : (
+ <Badge variant="red">
+ <Trans>Not feasible</Trans>
+ </Badge>
+ )}
+ <span className="tabular-nums text-muted-foreground">
+ {target.slackDays >= 0 ? (
+ <Plural
+ value={target.slackDays}
+ one="# day of slack"
+ other="# days of slack"
+ />
+ ) : (
+ <Plural
+ value={-target.slackDays}
+ one="# day short"
+ other="# days short"
+ />
+ )}
+ </span>
+ </div>
+ ) : (
+ "—"
+ )}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "pr-0 font-medium tabular-nums text-foreground"
+ )}
+ >
+ {targetLeadTime !== null ? (
+ <Days value={targetLeadTime} />
+ ) : (
+ "—"
+ )}
+ </td>
+ </tr>
+ );
+ }
+ const scenario = row[constraint];
+ return (
+ <tr key={row.quantity}>
+ <td
+ className={cn(
+ CELL,
+ "font-medium tabular-nums text-foreground"
+ )}
+ >
+ {row.quantity}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "tabular-nums text-muted-foreground"
+ )}
+ >
+ {materials}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "whitespace-nowrap tabular-nums"
+ )}
+ >
+ {scenario.finishAt
+ ? formatDate(scenario.finishAt.slice(0, 10))
+ : "—"}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "font-medium tabular-nums text-foreground"
+ )}
+ >
+ {scenario.leadTimeDays !== null ? (
+ <Days value={scenario.leadTimeDays} />
+ ) : (
+ "—"
+ )}
+ </td>
+ <td
+ className={cn(
+ CELL,
+ "pr-0 text-muted-foreground text-pretty"
+ )}
+ >
+ {scenario.cause ?? "—"}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+
+ <div className="mt-5 flex flex-col gap-1 border-t border-border pt-4">
+ <p className="text-xs font-medium text-muted-foreground">
+ <Trans>Assumptions</Trans>
+ </p>
+ <ul className="flex flex-col gap-0.5 text-xs text-muted-foreground">
+ {forecast.assumptions.map((assumption) => (
+ <li key={assumption}>{assumption}</li>
+ ))}
+ {forecast.zeroStandardOperationCount > 0 && (
+ <li>
+ <Plural
+ value={forecast.zeroStandardOperationCount}
+ one="# operation has no time standards"
+ other="# operations have no time standards"
+ />
+ </li>
+ )}
+ </ul>
+ </div>
+ </>
+ )}
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ {isEditable ? (
+ anyLate ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span tabIndex={0}>
+ <Button isDisabled>
+ <Trans>Apply</Trans>
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <Trans>One or more quantities cannot meet this date</Trans>
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <Button
+ isDisabled={applyDisabled}
+ isLoading={applying}
+ onClick={handleApply}
+ >
+ <Trans>Apply</Trans>
+ </Button>
+ )
+ ) : null}
+ <Button variant="secondary" onClick={onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default QuoteLeadTimeModal;
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index af425103cf..a09736fe59 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -114,6 +114,12 @@ const QuoteLineForm = ({
const isEditing = initialValues.id !== undefined;
+ // Quantity breaks are always presented least-to-greatest, regardless of the
+ // order they were entered/stored in.
+ const sortedQuantity = [...(initialValues.quantity ?? [])].sort(
+ (a, b) => a - b
+ );
+
const [itemData, setItemData] = useState<{
customerPartId: string;
customerPartRevision: string;
@@ -306,7 +312,7 @@ const QuoteLineForm = ({
<ModalCardContent size="xxlarge">
<ValidatedForm
fetcher={fetcher}
- defaultValues={initialValues}
+ defaultValues={{ ...initialValues, quantity: sortedQuantity }}
validator={quoteLineValidator}
method="post"
action={
@@ -338,7 +344,7 @@ const QuoteLineForm = ({
className="flex items-center gap-2"
>
<MethodIcon type={itemData.methodType} />
- {initialValues?.quantity.join(", ")}
+ {sortedQuantity.join(", ")}
</Badge>
{initialValues?.taxPercent > 0 ? (
<Badge variant="red">
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index 8aae9df955..e8e2138c0c 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -15,6 +15,7 @@ import {
DropdownMenuRadioItem,
DropdownMenuTrigger,
HStack,
+ IconButton,
Input,
NumberField,
NumberInput,
@@ -36,6 +37,7 @@ import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
+ LuCalendarClock,
LuChevronDown,
LuChevronRight,
LuCirclePlus,
@@ -67,6 +69,7 @@ import type {
QuotationLine,
QuotationPrice
} from "../../types";
+import QuoteLeadTimeModal from "./QuoteLeadTimeModal";
const logger = getLogger("erp", "sales", "quote-line-pricing");
@@ -97,7 +100,9 @@ const QuoteLinePricing = ({
const permissions = usePermissions();
const hasCalculatedCost = line.methodType !== "Pull from Inventory";
- const quantities = line.quantity ?? [1];
+ // Present quantity breaks least-to-greatest; every column loop and the
+ // derived `...ByQuantity` arrays read from this one variable.
+ const quantities = [...(line.quantity ?? [1])].sort((a, b) => a - b);
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
@@ -583,6 +588,76 @@ const QuoteLinePricing = ({
]
);
+ const [leadTimeModalOpen, setLeadTimeModalOpen] = useState(false);
+
+ // Applies one predicted lead time per quantity break in ONE state update:
+ // onUpdatePrice snapshots editableFields.prices per call and replaces the
+ // whole map, so looping it would keep only the last quantity's value.
+ const onUpdateLeadTimes = useCallback(
+ async (leadTimeByQuantity: Record<number, number>) => {
+ const prices = { ...editableFields.prices };
+ const missing: number[] = [];
+ for (const [key, days] of Object.entries(leadTimeByQuantity)) {
+ const quantity = Number(key);
+ if (prices[quantity]) {
+ prices[quantity] = { ...prices[quantity], leadTime: days };
+ } else {
+ missing.push(quantity);
+ prices[quantity] = {
+ quoteId,
+ quoteLineId: lineId,
+ quantity,
+ leadTime: days,
+ unitPrice: 0,
+ discountPercent: 0,
+ exchangeRate: exchangeRate ?? 1,
+ shippingCost: 0,
+ createdBy: userId
+ } as unknown as QuotationPrice;
+ }
+ }
+ setEditableFields((prev) => ({ ...prev, prices }));
+ const writes = Object.entries(leadTimeByQuantity).map(([key, days]) => {
+ const quantity = Number(key);
+ return missing.includes(quantity)
+ ? carbon
+ ?.from("quoteLinePrice")
+ .insert({ ...prices[quantity], quoteLineId: lineId, quantity })
+ : carbon
+ ?.from("quoteLinePrice")
+ .update({ leadTime: days, quoteLineId: lineId, quantity })
+ .eq("quoteLineId", lineId)
+ .eq("quantity", quantity);
+ });
+ const results = await Promise.all(writes);
+ const failed = Object.keys(leadTimeByQuantity)
+ .map(Number)
+ .filter((_, i) => results[i]?.error);
+ if (failed.length > 0) {
+ logger.error("Failed to update quote line lead times", {
+ errors: results.map((r) => r?.error).filter(Boolean)
+ });
+ // Roll back only the rows that did not save, so the state matches the
+ // database and a retry updates saved rows instead of re-inserting them.
+ setEditableFields((prev) => {
+ const reconciled = { ...prev.prices };
+ for (const quantity of failed) {
+ if (editableFields.prices[quantity]) {
+ reconciled[quantity] = editableFields.prices[quantity];
+ } else {
+ delete reconciled[quantity];
+ }
+ }
+ return { ...prev, prices: reconciled };
+ });
+ toast.error(t`Failed to update lead times`);
+ // Reject so the modal stays open instead of closing on a partial save.
+ throw new Error("Failed to update lead times");
+ }
+ },
+ [editableFields.prices, carbon, lineId, quoteId, exchangeRate, userId, t]
+ );
+
return (
<Card>
<HStack className="justify-between">
@@ -750,6 +825,15 @@ const QuoteLinePricing = ({
<Td className="border-r border-border group-hover:bg-muted/50">
<HStack className="w-full justify-between ">
<span>Lead Time</span>
+ {isEmployee && hasCalculatedCost && (
+ <IconButton
+ aria-label={t`Predict lead time`}
+ icon={<LuCalendarClock />}
+ variant="ghost"
+ size="sm"
+ onClick={() => setLeadTimeModalOpen(true)}
+ />
+ )}
</HStack>
</Td>
{quantities.map((quantity) => {
@@ -1361,6 +1445,16 @@ const QuoteLinePricing = ({
</Tbody>
</Table>
</CardContent>
+ {leadTimeModalOpen && (
+ <QuoteLeadTimeModal
+ quoteId={quoteId}
+ lineId={lineId}
+ quantities={quantities}
+ isEditable={isEditable}
+ onApply={onUpdateLeadTimes}
+ onClose={() => setLeadTimeModalOpen(false)}
+ />
+ )}
</Card>
);
};
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index caf57708e9..60a7d3e1fa 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -495,7 +495,7 @@ export default function AuthenticatedRoute() {
<TooltipProvider>
<div className="flex h-screen">
<PrimaryNavigation />
- <div className="flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border relative z-10">
+ <div className="flex flex-1 flex-col min-w-0 overflow-hidden bg-card md:mt-2 md:mr-2 md:mb-2 md:rounded-2xl md:border md:border-border shadow-md relative z-10">
<Topbar />
<main className="flex-1 overflow-y-auto scrollbar-hide relative">
<Outlet />
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index 1461e66447..845950af45 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -146,7 +146,15 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
: null;
return {
- line: line.data,
+ line: {
+ ...line.data,
+ // Present quantity breaks least-to-greatest everywhere they're consumed
+ // (line form, costing grid, pricing grid). Preserve null so the `?? [1]`
+ // fallbacks downstream still apply.
+ quantity: line.data.quantity
+ ? [...line.data.quantity].sort((a, b) => a - b)
+ : line.data.quantity
+ },
operations: operations?.data ?? [],
files: getOpportunityLineDocuments(serviceRole, companyId, lineId, itemId),
pricesByQuantity: (prices?.data ?? []).reduce<
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.lead-time.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.lead-time.tsx
new file mode 100644
index 0000000000..560f181111
--- /dev/null
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.lead-time.tsx
@@ -0,0 +1,80 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
+import { runQuoteLeadTimeWhatIf } from "@carbon/planning";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { quoteLeadTimeValidator } from "~/modules/sales";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
+
+const logger = getLogger("erp", "quoteid-lineid-lead-time");
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ // Read-only capable-to-promise what-if — nothing is persisted, so `view` is
+ // sufficient (same reasoning as $jobId.expedite.tsx).
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "sales"
+ });
+
+ const { quoteId, lineId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const parsed = quoteLeadTimeValidator.safeParse(await request.json());
+ if (!parsed.success) {
+ return data({ forecast: null, error: "Invalid request" }, { status: 400 });
+ }
+
+ // Re-read the quote AND line under companyId before trusting the URL ids —
+ // the record-id rule from workflow-edge-function.md §5 applies to routes too.
+ const quote = await client
+ .from("quote")
+ .select("locationId")
+ .eq("id", quoteId)
+ .eq("companyId", companyId)
+ .single();
+ if (quote.error || !quote.data) {
+ throw new Response(null, { status: 404 });
+ }
+
+ const line = await client
+ .from("quoteLine")
+ .select("id")
+ .eq("id", lineId)
+ .eq("quoteId", quoteId)
+ .eq("companyId", companyId)
+ .single();
+ if (line.error || !line.data) {
+ throw new Response(null, { status: 404 });
+ }
+
+ const locationId =
+ quote.data.locationId ??
+ (await getUserDefaults(client, userId, companyId)).data?.locationId;
+ if (!locationId) {
+ return data({
+ forecast: null,
+ error: "Set a location on the quote to predict lead time"
+ });
+ }
+
+ try {
+ const forecast = await runQuoteLeadTimeWhatIf({
+ db: getDatabaseClient(),
+ client: getCarbonServiceRole(),
+ companyId,
+ userId,
+ locationId,
+ quoteLineId: lineId,
+ quantities: parsed.data.quantities,
+ dueDate: parsed.data.dueDate
+ });
+ return data({ forecast, error: null });
+ } catch (err) {
+ logger.error("Failed to predict quote lead time", { error: err });
+ return data({ forecast: null, error: "Failed to predict lead time" });
+ }
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 0f1b90e0ef..d2caaf32c6 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1961,6 +1961,8 @@ export const path = {
generatePath(`${x}/quote/${quoteId}/${id}/details`),
quoteLineConfigure: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/${quoteId}/${lineId}/configure`),
+ quoteLineLeadTime: (quoteId: string, lineId: string) =>
+ generatePath(`${x}/quote/${quoteId}/${lineId}/lead-time`),
quoteLineMakeMethod: (
quoteId: string,
lineId: string,
diff --git a/packages/documents/src/pdf/QuotePDF.test.ts b/packages/documents/src/pdf/QuotePDF.test.ts
new file mode 100644
index 0000000000..7474ed4595
--- /dev/null
+++ b/packages/documents/src/pdf/QuotePDF.test.ts
@@ -0,0 +1,44 @@
+import { renderToBuffer } from "@react-pdf/renderer";
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import QuotePDF from "./QuotePDF";
+
+const line = {
+ id: "line-1",
+ quoteId: "quote-1",
+ itemId: "item-1",
+ itemReadableId: "SAT-1000",
+ description: "Satellite bus",
+ status: "Complete",
+ quantity: [1],
+ taxPercent: 0,
+ thumbnailPath: "_templates/aerospace_satellite/SAT-1000.svg"
+};
+
+function render(thumbnails: Record<string, string | null>) {
+ return renderToBuffer(
+ createElement(QuotePDF, {
+ company: { name: "Acme", baseCurrencyCode: "USD" },
+ locale: "en-US",
+ exchangeRate: 1,
+ quote: { id: "quote-1", quoteId: "Q000001", currencyCode: "USD" },
+ quoteLines: [line],
+ quoteLinePrices: [],
+ quoteCustomerDetails: {},
+ paymentTerms: [],
+ shippingMethods: [],
+ terms: {},
+ thumbnails
+ } as never) as never
+ );
+}
+
+describe("QuotePDF thumbnails", () => {
+ // The route records a line whose thumbnail could not be downloaded as
+ // `null`; an <Image> with a null src crashes react-pdf's layout with
+ // "Cannot read properties of undefined (reading 'width')".
+ it("renders when a line's thumbnail failed to load", async () => {
+ const pdf = await render({ "line-1": null });
+ expect(pdf.subarray(0, 4).toString()).toBe("%PDF");
+ });
+});
diff --git a/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx
index 7f33638182..8e58b02efe 100644
--- a/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx
@@ -99,232 +99,242 @@ export function LineItemsBlock({
<View key={line.id}>
{line.status !== "No Quote" ? (
<>
- {(line.quantity ?? []).map((quantity, index) => {
- const prices =
- line.id != null ? (pricesByLine[line.id] ?? []) : [];
- const price = prices.find(
- (p: QuoteLinePrice) => p.quantity === quantity
- );
- const unitPrice = price?.convertedUnitPrice ?? 0;
- const netExtendedPrice =
- price?.convertedNetExtendedPrice ?? 0;
- const isEven = rowIndex % 2 === 0;
- rowIndex++;
+ {[...(line.quantity ?? [])]
+ .sort((a, b) => a - b)
+ .map((quantity, index) => {
+ const prices =
+ line.id != null ? (pricesByLine[line.id] ?? []) : [];
+ const price = prices.find(
+ (p: QuoteLinePrice) => p.quantity === quantity
+ );
+ const unitPrice = price?.convertedUnitPrice ?? 0;
+ const netExtendedPrice =
+ price?.convertedNetExtendedPrice ?? 0;
+ const isEven = rowIndex % 2 === 0;
+ rowIndex++;
- const leadTime = price?.leadTime ?? 0;
+ const leadTime = price?.leadTime ?? 0;
- const additionalCharge = Object.values(
- additionalCharges
- ).reduce((acc, charge) => {
- let amount = charge.amounts?.[quantity] ?? 0;
- if (shouldConvertCurrency) amount *= exchangeRate;
- return acc + amount;
- }, 0);
- const taxableAdditionalCharge = Object.values(
- additionalCharges
- ).reduce((acc, charge) => {
- if (charge.taxable === false) return acc;
- let amount = charge.amounts?.[quantity] ?? 0;
- if (shouldConvertCurrency) amount *= exchangeRate;
- return acc + amount;
- }, 0);
- const shippingCost = price?.convertedShippingCost ?? 0;
- const taxPercent = line.taxPercent ?? 0;
- const taxableBeforeTax =
- netExtendedPrice + taxableAdditionalCharge + shippingCost;
- const taxAmount = taxableBeforeTax * taxPercent;
- const totalTaxAndFees =
- additionalCharge + shippingCost + taxAmount;
- const totalPrice = netExtendedPrice + totalTaxAndFees;
+ const additionalCharge = Object.values(
+ additionalCharges
+ ).reduce((acc, charge) => {
+ let amount = charge.amounts?.[quantity] ?? 0;
+ if (shouldConvertCurrency) amount *= exchangeRate;
+ return acc + amount;
+ }, 0);
+ const taxableAdditionalCharge = Object.values(
+ additionalCharges
+ ).reduce((acc, charge) => {
+ if (charge.taxable === false) return acc;
+ let amount = charge.amounts?.[quantity] ?? 0;
+ if (shouldConvertCurrency) amount *= exchangeRate;
+ return acc + amount;
+ }, 0);
+ const shippingCost = price?.convertedShippingCost ?? 0;
+ const taxPercent = line.taxPercent ?? 0;
+ const taxableBeforeTax =
+ netExtendedPrice + taxableAdditionalCharge + shippingCost;
+ const taxAmount = taxableBeforeTax * taxPercent;
+ const totalTaxAndFees =
+ additionalCharge + shippingCost + taxAmount;
+ const totalPrice = netExtendedPrice + totalTaxAndFees;
- return (
- <View
- key={`${line.id}-${quantity}`}
- wrap={false}
- style={[
- tw(
- "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"
- ),
- {
- backgroundColor:
- opts.zebra && !isEven
- ? "rgba(249, 250, 251, 0.6)"
- : "transparent"
- }
- ]}
- >
- <View style={tw("w-1/3 pr-2")}>
- {index === 0 && (
- <>
- <Text
- style={{ ...tw("text-gray-800"), ...overflow }}
- >
- {getLineDescription(line)}
- </Text>
- <Text
- style={{
- ...tw("text-[8px] text-gray-400 mt-0.5"),
- ...overflow
- }}
- >
- {getLineDescriptionDetails(line)}
- </Text>
- {opts.showThumbnails &&
- thumbnails &&
- line.id != null &&
- line.id in thumbnails && (
- <View style={tw("mt-2")}>
- <Image
- src={thumbnails[line.id]!}
- style={{ width: 60, height: 60 }}
- />
- </View>
- )}
- {totalTaxAndFees > 0 && (
- <View style={tw("mt-1")}>
- <Text
- style={tw(
- "text-[8px] text-gray-400 font-bold"
- )}
- >
- Tax & Fees
- </Text>
- {(price?.convertedShippingCost ?? 0) > 0 && (
- <View
- style={tw("flex flex-row justify-between")}
+ return (
+ <View
+ key={`${line.id}-${quantity}`}
+ wrap={false}
+ style={[
+ tw(
+ "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"
+ ),
+ {
+ backgroundColor:
+ opts.zebra && !isEven
+ ? "rgba(249, 250, 251, 0.6)"
+ : "transparent"
+ }
+ ]}
+ >
+ <View style={tw("w-1/3 pr-2")}>
+ {index === 0 && (
+ <>
+ <Text
+ style={{ ...tw("text-gray-800"), ...overflow }}
+ >
+ {getLineDescription(line)}
+ </Text>
+ <Text
+ style={{
+ ...tw("text-[8px] text-gray-400 mt-0.5"),
+ ...overflow
+ }}
+ >
+ {getLineDescriptionDetails(line)}
+ </Text>
+ {opts.showThumbnails &&
+ thumbnails &&
+ line.id != null &&
+ thumbnails[line.id] && (
+ <View style={tw("mt-2")}>
+ <Image
+ src={thumbnails[line.id]!}
+ style={{ width: 60, height: 60 }}
+ />
+ </View>
+ )}
+ {totalTaxAndFees > 0 && (
+ <View style={tw("mt-1")}>
+ <Text
+ style={tw(
+ "text-[8px] text-gray-400 font-bold"
+ )}
>
- <Text
+ Tax & Fees
+ </Text>
+ {(price?.convertedShippingCost ?? 0) > 0 && (
+ <View
style={tw(
- "text-[8px] text-gray-400 flex-1 pr-2"
+ "flex flex-row justify-between"
)}
>
- - Shipping
- </Text>
- <Text
- style={tw("text-[8px] text-gray-400")}
- >
- {numberFormatter.format(
- price?.convertedShippingCost ?? 0
- )}
- </Text>
- </View>
- )}
- {Object.values(additionalCharges)
- .filter(
- (charge) =>
- charge.description &&
- (charge.amounts?.[quantity] ?? 0) > 0
- )
- .sort((a, b) =>
- a.description.localeCompare(b.description)
- )
- .map((charge) => {
- let chargeAmount =
- charge.amounts?.[quantity] ?? 0;
- if (shouldConvertCurrency)
- chargeAmount *= exchangeRate;
- return (
- <View
- key={charge.description}
+ <Text
style={tw(
- "flex flex-row justify-between"
+ "text-[8px] text-gray-400 flex-1 pr-2"
)}
>
- <Text
+ - Shipping
+ </Text>
+ <Text
+ style={tw("text-[8px] text-gray-400")}
+ >
+ {numberFormatter.format(
+ price?.convertedShippingCost ?? 0
+ )}
+ </Text>
+ </View>
+ )}
+ {Object.values(additionalCharges)
+ .filter(
+ (charge) =>
+ charge.description &&
+ (charge.amounts?.[quantity] ?? 0) > 0
+ )
+ .sort((a, b) =>
+ a.description.localeCompare(b.description)
+ )
+ .map((charge) => {
+ let chargeAmount =
+ charge.amounts?.[quantity] ?? 0;
+ if (shouldConvertCurrency)
+ chargeAmount *= exchangeRate;
+ return (
+ <View
+ key={charge.description}
style={tw(
- "text-[8px] text-gray-400 flex-1 pr-2"
+ "flex flex-row justify-between"
)}
>
- - {charge.description}
- </Text>
- <Text
- style={tw("text-[8px] text-gray-400")}
- >
- {numberFormatter.format(chargeAmount)}
- </Text>
- </View>
- );
- })}
- {taxPercent > 0 && (
- <View
- style={tw("flex flex-row justify-between")}
- >
- <Text
+ <Text
+ style={tw(
+ "text-[8px] text-gray-400 flex-1 pr-2"
+ )}
+ >
+ - {charge.description}
+ </Text>
+ <Text
+ style={tw(
+ "text-[8px] text-gray-400"
+ )}
+ >
+ {numberFormatter.format(
+ chargeAmount
+ )}
+ </Text>
+ </View>
+ );
+ })}
+ {taxPercent > 0 && (
+ <View
style={tw(
- "text-[8px] text-gray-400 flex-1 pr-2"
+ "flex flex-row justify-between"
)}
>
- - Tax ({formatPercent(taxPercent, locale)}
- )
- </Text>
- <Text
- style={tw("text-[8px] text-gray-400")}
- >
- {numberFormatter.format(taxAmount)}
- </Text>
- </View>
- )}
- </View>
- )}
- </>
- )}
- </View>
- <View style={tw("w-2/3 flex flex-row")}>
- <Text
- style={tw(
- `${colWidth} text-center text-gray-600 pr-3`
- )}
- >
- {quantity} EA
- </Text>
- <Text
- style={tw(
- `${colWidth} text-center text-gray-600 pr-3`
+ <Text
+ style={tw(
+ "text-[8px] text-gray-400 flex-1 pr-2"
+ )}
+ >
+ - Tax (
+ {formatPercent(taxPercent, locale)})
+ </Text>
+ <Text
+ style={tw("text-[8px] text-gray-400")}
+ >
+ {numberFormatter.format(taxAmount)}
+ </Text>
+ </View>
+ )}
+ </View>
+ )}
+ </>
)}
- >
- {unitPrice
- ? unitPriceNumberFormatter.format(unitPrice)
- : "-"}
- </Text>
- {!hasSinglePricePerLine && (
+ </View>
+ <View style={tw("w-2/3 flex flex-row")}>
<Text
style={tw(
`${colWidth} text-center text-gray-600 pr-3`
)}
>
- {totalTaxAndFees > 0
- ? numberFormatter.format(totalTaxAndFees)
- : "-"}
+ {quantity} EA
</Text>
- )}
- {hasAnyLeadTime && (
<Text
style={tw(
`${colWidth} text-center text-gray-600 pr-3`
)}
>
- {leadTime > 0
- ? `${leadTime} ${pluralize(leadTime, "day")}`
+ {unitPrice
+ ? unitPriceNumberFormatter.format(unitPrice)
: "-"}
</Text>
- )}
- <Text
- style={tw(
- `${colWidth} text-center text-gray-800 font-medium`
+ {!hasSinglePricePerLine && (
+ <Text
+ style={tw(
+ `${colWidth} text-center text-gray-600 pr-3`
+ )}
+ >
+ {totalTaxAndFees > 0
+ ? numberFormatter.format(totalTaxAndFees)
+ : "-"}
+ </Text>
)}
- >
- {hasSinglePricePerLine
- ? netExtendedPrice > 0
- ? numberFormatter.format(netExtendedPrice)
- : "-"
- : totalPrice > 0
- ? numberFormatter.format(totalPrice)
- : "-"}
- </Text>
+ {hasAnyLeadTime && (
+ <Text
+ style={tw(
+ `${colWidth} text-center text-gray-600 pr-3`
+ )}
+ >
+ {leadTime > 0
+ ? `${leadTime} ${pluralize(leadTime, "day")}`
+ : "-"}
+ </Text>
+ )}
+ <Text
+ style={tw(
+ `${colWidth} text-center text-gray-800 font-medium`
+ )}
+ >
+ {hasSinglePricePerLine
+ ? netExtendedPrice > 0
+ ? numberFormatter.format(netExtendedPrice)
+ : "-"
+ : totalPrice > 0
+ ? numberFormatter.format(totalPrice)
+ : "-"}
+ </Text>
+ </View>
</View>
- </View>
- );
- })}
+ );
+ })}
{Object.keys(line.externalNotes ?? {}).length > 0 && (
<View style={tw("px-3 py-2 border-b border-gray-200")}>
<Note
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 72718ff21f..17a4322448 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -48,6 +48,18 @@ msgstr "„{taskName}\" ist erledigt – alle {0} seiner Setup-Map-Elemente sind
msgid "(excluded for this customer)"
msgstr "(für diesen Kunden ausgeschlossen)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# Tag Puffer} other {# Tage Puffer}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# Tag zu kurz} other {# Tage zu kurz}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# Arbeitsgang hat keine Zeitstandards} other {# Arbeitsgänge haben keine Zeitstandards}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# Zeile verweist auf Daten außerhalb dieses Unternehmens, daher kann keine Sicherungskopie Ihrer aktuellen Daten erstellt werden.} other {# Zeilen verweisen auf Daten außerhalb dieses Unternehmens, daher kann keine Sicherungskopie Ihrer aktuellen Daten erstellt werden.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} Fertigungsaufträge aktualisiert"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} hochgeladen — Felder wurden aus dem Dokument ausgefüllt."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# Tag} other {# Tage}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# Position unterscheidet sich von der erwarteten Menge} other {# Positionen unterscheiden sich von der erwarteten Menge}}"
@@ -2545,6 +2560,9 @@ msgstr "Sind Sie sicher, dass Sie diese Lieferung stornieren möchten? Diese Akt
msgid "Are you sure?"
msgstr "Sind Sie sicher?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Als würde es vor die Werkstattschlange springen."
+
msgid "As needed"
msgstr "Nach Bedarf"
@@ -2668,6 +2686,9 @@ msgstr "Weist diese Lagereinheit einem Arbeitsplatz (Linienlager) zu"
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Weist diese Einheit einem Arbeitsplatz zum Linienlager zu, sodass Werker sie in der Produktionsansicht sehen; wird von der übergeordneten Einheit geerbt, sofern dort festgelegt."
+msgid "Assumptions"
+msgstr "Annahmen"
+
msgid "At each gate"
msgstr "Bei jedem Gate"
@@ -2994,6 +3015,9 @@ msgstr "Prognose für den besten Fall"
msgid "Best case…"
msgstr "Bester Fall…"
+msgid "Best-case finish"
+msgstr "Best-Case-Fertigstellung"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Büchersperrungsdatum (manuell)"
msgid "Both"
msgstr "Beide"
+msgid "Both finishes compared against a date you choose."
+msgstr "Beide Fertigstellungen gegen ein Datum Ihrer Wahl verglichen."
+
msgid "Bottleneck"
msgstr "Engpass"
@@ -4473,6 +4500,9 @@ msgstr "PDF konnte nicht erstellt werden. Versuchen Sie es erneut."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Konnte {0} nicht auflösen: {1} — Produktion bereits erfasst"
+msgid "Could not predict lead time"
+msgstr "Beschaffungszeit konnte nicht vorhergesagt werden"
+
msgid "Could not prepare region image for analysis"
msgstr "Konnte Regionsbild nicht für die Analyse vorbereiten"
@@ -6807,6 +6837,9 @@ msgstr "Ende des letzten Monats"
msgid "End of Last Quarter"
msgstr "Ende des letzten Quartals"
+msgid "End of queue"
+msgstr "Ende der Warteschlange"
+
msgid "End Time"
msgstr "Endzeit"
@@ -7626,6 +7659,9 @@ msgstr "Fehler beim Aktualisieren der Inventur"
msgid "Failed to update item cost"
msgstr "Fehler beim Aktualisieren der Artikelkosten"
+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"
@@ -8616,6 +8652,9 @@ msgstr "Wenn es blockiert oder ein Termin gefährdet ist, erhält es einen Veran
msgid "If items already exist"
msgstr "Wenn Artikel bereits vorhanden sind"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Falls heute bestellt – wird es hinter alles bereits Freigegebene eingereiht."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Falls bestellt, ist kein Fehlbestand in den nächsten 48 Wochen geplant"
@@ -10641,6 +10680,9 @@ msgstr "Erforderlich sind die für diesen Tag fälligen Arbeitsstunden dividiert
msgid "Needs a Business or Partner plan."
msgstr "Benötigt einen Business- oder Partner-Plan."
+msgid "Needs expedite"
+msgstr "Benötigt Expedite"
+
msgid "Needs fixing"
msgstr "Muss behoben werden"
@@ -11618,6 +11660,9 @@ msgstr "Nicht konfiguriert"
msgid "Not enough jobs to cover quantity"
msgstr "Nicht genug Fertigungsaufträge zur Abdeckung der Menge"
+msgid "Not feasible"
+msgstr "Nicht machbar"
+
msgid "Not reached"
msgstr "Nicht erreicht"
@@ -11803,6 +11848,9 @@ msgstr "Auf Lagereinheit"
msgid "On this operation"
msgstr "Bei diesem Arbeitsgang"
+msgid "On time"
+msgstr "Pünktlich"
+
msgid "On-account credit available"
msgstr "Verfügbarer Kontokorrentkreditrahmen"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} entspricht wie vielen {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Ein Workflow-Durchlauf, aufgezeichnet Schritt für Schritt mit den Werten, die jeder Schritt verwendet und erzeugt, ausgeführt mit den Berechtigungen des Verantwortlichen des Workflows."
+msgid "One or more quantities cannot meet this date"
+msgstr "Eine oder mehrere Mengen können diesen Termin nicht erfüllen"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Eine Serieneinheit oder eine Partie, die Carbon einzeln verfolgt und ihre eigenen Status und Attribute wie ein Verfallsdatum trägt."
@@ -12646,6 +12697,9 @@ msgstr "Wählen Sie zuerst eine Eigenschaft"
msgid "Pick a record type…"
msgstr "Wählen Sie einen Datensatztyp…"
+msgid "Pick a target date to compare."
+msgstr "Wählen Sie ein Zieldatum zum Vergleich."
+
msgid "Pick a value from an earlier step"
msgstr "Wählen Sie einen Wert aus einem früheren Schritt"
@@ -12906,6 +12960,12 @@ msgstr "Möglicher Datenverlust"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Wird für einen neuen Artikel vorausgefüllt, wenn die Verfallszeit auf Feste Dauer eingestellt ist."
+msgid "Predict lead time"
+msgstr "Beschaffungszeit vorhersagen"
+
+msgid "Predicting lead time…"
+msgstr "Beschaffungszeit wird vorhergesagt…"
+
msgid "Preferred Supplier"
msgstr "Bevorzugter Lieferant"
@@ -13585,6 +13645,9 @@ msgstr "Frage"
msgid "Queued"
msgstr "In Warteschlange"
+msgid "Queued finish"
+msgstr "Fertigstellung in Warteschlange"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Ruhig auf der Fertigung heute Nacht, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Terminplan regeneriert"
msgid "Scheduled"
msgstr "Geplant"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Geplant gegen die aktuelle Arbeitslast Ihrer Werkstatt. Nichts wird gespeichert, bis Sie anwenden."
+
msgid "Scheduled Maintenance"
msgstr "Geplante Instandhaltung"
@@ -16866,6 +16932,9 @@ msgstr "Zielunternehmen"
msgid "Target customers by type."
msgstr "Zielen Sie auf Kunden nach Typ ab."
+msgid "Target date"
+msgstr "Zieldatum"
+
msgid "Target disposition row"
msgstr "Verwendungsentscheid-Position"
@@ -18007,6 +18076,9 @@ msgstr "Dieser Auftrag ist auf der Werkstatt nicht mehr verfügbar."
msgid "This job's own required quantity for the material."
msgstr "Die für dieses Material benötigte Menge dieses Auftrags."
+msgid "This line has no routing to schedule."
+msgstr "Diese Position hat keinen Arbeitsplan zum Terminieren."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Dieser Standort plant nur besetzte Arbeitsplätze, aber dies ist eine Lights-out (24×7) Station – sie ist befreit und läuft unbeaufsichtigt."
@@ -19164,6 +19236,9 @@ msgstr "USt-IdNr."
msgid "Vendor Write-Off Income"
msgstr "Ausbuchungserträge von Lieferanten"
+msgid "Verdict"
+msgstr "Ergebnis"
+
msgid "Verification Error"
msgstr "Verifizierungsfehler"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 05705ae887..489ebfabab 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" is done — all {0} of its Setup Map items are configured
msgid "(excluded for this customer)"
msgstr "(excluded for this customer)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# day of slack} other {# days of slack}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# day short} other {# days short}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} jobs updated"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} uploaded — fields filled from the document."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# day} other {# days}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
@@ -2545,6 +2560,9 @@ msgstr "Are you sure you want to void this shipment? This action will reverse al
msgid "Are you sure?"
msgstr "Are you sure?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "As if it jumped to the front of the shop's queue."
+
msgid "As needed"
msgstr "As needed"
@@ -2668,6 +2686,9 @@ msgstr "Assigns this storage unit to a work center (lineside)"
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
+msgid "Assumptions"
+msgstr "Assumptions"
+
msgid "At each gate"
msgstr "At each gate"
@@ -2994,6 +3015,9 @@ msgstr "Best case projection"
msgid "Best case…"
msgstr "Best case…"
+msgid "Best-case finish"
+msgstr "Best-case finish"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Books lock date (manual)"
msgid "Both"
msgstr "Both"
+msgid "Both finishes compared against a date you choose."
+msgstr "Both finishes compared against a date you choose."
+
msgid "Bottleneck"
msgstr "Bottleneck"
@@ -4473,6 +4500,9 @@ msgstr "Could not build PDF. Try again."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Could not dissolve {0}: {1} — production already recorded"
+msgid "Could not predict lead time"
+msgstr "Could not predict lead time"
+
msgid "Could not prepare region image for analysis"
msgstr "Could not prepare region image for analysis"
@@ -6807,6 +6837,9 @@ msgstr "End of Last Month"
msgid "End of Last Quarter"
msgstr "End of Last Quarter"
+msgid "End of queue"
+msgstr "End of queue"
+
msgid "End Time"
msgstr "End Time"
@@ -7626,6 +7659,9 @@ msgstr "Failed to update count"
msgid "Failed to update item cost"
msgstr "Failed to update item cost"
+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"
@@ -8616,6 +8652,9 @@ msgstr "If it's blocking or a date is at risk, it gets an owner and is tracked."
msgid "If items already exist"
msgstr "If items already exist"
+msgid "If ordered today — placed behind everything already released."
+msgstr "If ordered today — placed behind everything already released."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "If ordered, no stockout projected in the next 48 weeks"
@@ -10641,6 +10680,9 @@ msgstr "Needed is the job hours due that day divided by {personDayHours}h, round
msgid "Needs a Business or Partner plan."
msgstr "Needs a Business or Partner plan."
+msgid "Needs expedite"
+msgstr "Needs expedite"
+
msgid "Needs fixing"
msgstr "Needs fixing"
@@ -11618,6 +11660,9 @@ msgstr "Not Configured"
msgid "Not enough jobs to cover quantity"
msgstr "Not enough jobs to cover quantity"
+msgid "Not feasible"
+msgstr "Not feasible"
+
msgid "Not reached"
msgstr "Not reached"
@@ -11803,6 +11848,9 @@ msgstr "On Storage Unit"
msgid "On this operation"
msgstr "On this operation"
+msgid "On time"
+msgstr "On time"
+
msgid "On-account credit available"
msgstr "On-account credit available"
@@ -11838,6 +11886,9 @@ msgstr "One {0} is equal to how many {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
+msgid "One or more quantities cannot meet this date"
+msgstr "One or more quantities cannot meet this date"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
@@ -12646,6 +12697,9 @@ msgstr "Pick a property first"
msgid "Pick a record type…"
msgstr "Pick a record type…"
+msgid "Pick a target date to compare."
+msgstr "Pick a target date to compare."
+
msgid "Pick a value from an earlier step"
msgstr "Pick a value from an earlier step"
@@ -12906,6 +12960,12 @@ msgstr "Potential Data Loss"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Pre-filled for a new item when expiry is Fixed Duration."
+msgid "Predict lead time"
+msgstr "Predict lead time"
+
+msgid "Predicting lead time…"
+msgstr "Predicting lead time…"
+
msgid "Preferred Supplier"
msgstr "Preferred Supplier"
@@ -13585,6 +13645,9 @@ msgstr "Question"
msgid "Queued"
msgstr "Queued"
+msgid "Queued finish"
+msgstr "Queued finish"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Quiet on the floor tonight, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Schedule regenerated"
msgid "Scheduled"
msgstr "Scheduled"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Scheduled against your shop's current workload. Nothing is saved until you apply."
+
msgid "Scheduled Maintenance"
msgstr "Scheduled Maintenance"
@@ -16866,6 +16932,9 @@ msgstr "Target Company"
msgid "Target customers by type."
msgstr "Target customers by type."
+msgid "Target date"
+msgstr "Target date"
+
msgid "Target disposition row"
msgstr "Target disposition row"
@@ -18007,6 +18076,9 @@ msgstr "This job will no longer be available on the shop floor."
msgid "This job's own required quantity for the material."
msgstr "This job's own required quantity for the material."
+msgid "This line has no routing to schedule."
+msgstr "This line has no routing to schedule."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
@@ -19164,6 +19236,9 @@ msgstr "VAT Number"
msgid "Vendor Write-Off Income"
msgstr "Vendor Write-Off Income"
+msgid "Verdict"
+msgstr "Verdict"
+
msgid "Verification Error"
msgstr "Verification Error"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index b14e045fb1..563241a3fa 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" está hecho — todos los {0} elementos de su Mapa de Con
msgid "(excluded for this customer)"
msgstr "(excluido para este cliente)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# día de holgura} other {# días de holgura}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# día de atraso} other {# días de atraso}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# operación no tiene estándares de tiempo} other {# operaciones no tienen estándares de tiempo}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# fila vincula a datos fuera de esta empresa, por lo que no se puede hacer una copia de seguridad de sus datos actuales.} other {# filas vinculan a datos fuera de esta empresa, por lo que no se puede hacer una copia de seguridad de sus datos actuales.}}"
@@ -399,6 +411,9 @@ 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."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# día} other {# días}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# línea difiere de la cantidad esperada} other {# líneas difieren de la cantidad esperada}}"
@@ -2545,6 +2560,9 @@ msgstr "¿Estás seguro de que deseas anular este envío? Esta acción revertir
msgid "Are you sure?"
msgstr "¿Estás seguro?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Como si saltara al frente de la cola de la tienda."
+
msgid "As needed"
msgstr "Según sea necesario"
@@ -2668,6 +2686,9 @@ msgstr "Asigna esta unidad de almacenamiento a un centro de trabajo (pie de lín
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Asigna esta unidad a un centro de trabajo para material de pie de línea, de modo que los operarios la vean en la vista de producción; se hereda de la unidad padre cuando se establece allí."
+msgid "Assumptions"
+msgstr "Supuestos"
+
msgid "At each gate"
msgstr "En cada puerta"
@@ -2994,6 +3015,9 @@ msgstr "Proyección del mejor caso"
msgid "Best case…"
msgstr "Mejor caso…"
+msgid "Best-case finish"
+msgstr "Mejor finalización"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Fecha de bloqueo de libros (manual)"
msgid "Both"
msgstr "Ambos"
+msgid "Both finishes compared against a date you choose."
+msgstr "Ambas fechas de finalización comparadas con la fecha que elijas."
+
msgid "Bottleneck"
msgstr "Cuello de botella"
@@ -4473,6 +4500,9 @@ msgstr "No se pudo crear el PDF. Intenta de nuevo."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "No se pudo disolver {0}: {1} — producción ya registrada"
+msgid "Could not predict lead time"
+msgstr "No se pudo predecir el plazo de entrega"
+
msgid "Could not prepare region image for analysis"
msgstr "No se pudo preparar la imagen de la región para el análisis"
@@ -6807,6 +6837,9 @@ msgstr "Fin del mes anterior"
msgid "End of Last Quarter"
msgstr "Fin del Trimestre Anterior"
+msgid "End of queue"
+msgstr "Final de la cola"
+
msgid "End Time"
msgstr "Hora de Finalización"
@@ -7626,6 +7659,9 @@ 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 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"
@@ -8616,6 +8652,9 @@ msgstr "Si está bloqueando o una fecha está en riesgo, se asigna un propietari
msgid "If items already exist"
msgstr "Si los artículos ya existen"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Si se pide hoy — se coloca detrás de todo lo que ya está liberado."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Si hay un Pedido, ninguna Rotura de stock proyectada en las próximas 48 semanas"
@@ -10641,6 +10680,9 @@ msgstr "Lo necesario son las horas de trabajo vencidas ese día divididas por {p
msgid "Needs a Business or Partner plan."
msgstr "Requiere un plan Business o Partner."
+msgid "Needs expedite"
+msgstr "Requiere agilización"
+
msgid "Needs fixing"
msgstr "Necesita reparación"
@@ -11618,6 +11660,9 @@ msgstr "No configurado"
msgid "Not enough jobs to cover quantity"
msgstr "No hay suficientes órdenes de trabajo para cubrir la cantidad"
+msgid "Not feasible"
+msgstr "No es viable"
+
msgid "Not reached"
msgstr "No alcanzado"
@@ -11803,6 +11848,9 @@ msgstr "En Unidad de Almacenamiento"
msgid "On this operation"
msgstr "En esta operación"
+msgid "On time"
+msgstr "A tiempo"
+
msgid "On-account credit available"
msgstr "Crédito disponible en cuenta"
@@ -11838,6 +11886,9 @@ msgstr "¿A cuántos {1} equivale 1 {0}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Una ejecución de un flujo de trabajo, registrada paso a paso con los valores que cada paso usó y produjo, actuando en todo momento con los permisos del propietario del flujo de trabajo."
+msgid "One or more quantities cannot meet this date"
+msgstr "Una o más cantidades no pueden cumplir esta fecha"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Una unidad serial o un lote de producción que Carbon sigue individualmente, llevando su propio estado y atributos como una fecha de caducidad."
@@ -12646,6 +12697,9 @@ msgstr "Elige una propiedad primero"
msgid "Pick a record type…"
msgstr "Elige un tipo de registro…"
+msgid "Pick a target date to compare."
+msgstr "Selecciona una fecha objetivo para comparar."
+
msgid "Pick a value from an earlier step"
msgstr "Elige un valor de un paso anterior"
@@ -12906,6 +12960,12 @@ msgstr "Pérdida potencial de datos"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Rellenado previamente para un nuevo artículo cuando la caducidad es Duración Fija."
+msgid "Predict lead time"
+msgstr "Predecir plazo de entrega"
+
+msgid "Predicting lead time…"
+msgstr "Prediciendo plazo de entrega…"
+
msgid "Preferred Supplier"
msgstr "Proveedor Preferido"
@@ -13585,6 +13645,9 @@ msgstr "Pregunta"
msgid "Queued"
msgstr "En cola"
+msgid "Queued finish"
+msgstr "Finalización en cola"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Tranquilo en el piso esta noche, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Programa regenerado"
msgid "Scheduled"
msgstr "Programado"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Programado en función de la carga de trabajo actual de su taller. Nada se guarda hasta que lo aplique."
+
msgid "Scheduled Maintenance"
msgstr "Mantenimiento Programado"
@@ -16866,6 +16932,9 @@ msgstr "Empresa Objetivo"
msgid "Target customers by type."
msgstr "Orientar clientes por tipo."
+msgid "Target date"
+msgstr "Fecha objetivo"
+
msgid "Target disposition row"
msgstr "Fila de disposición de destino"
@@ -18007,6 +18076,9 @@ msgstr "Esta orden de trabajo ya no estará disponible en la planta."
msgid "This job's own required quantity for the material."
msgstr "La cantidad propia requerida por este trabajo para el material."
+msgid "This line has no routing to schedule."
+msgstr "Esta línea no tiene una ruta de fabricación para programar."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Esta ubicación solo programa centros de trabajo con personal, pero esta es una estación sin personal (24×7) — está exenta y continúa funcionando sin vigilancia."
@@ -19164,6 +19236,9 @@ msgstr "Número de IVA"
msgid "Vendor Write-Off Income"
msgstr "Ingresos por cancelación contable de proveedor"
+msgid "Verdict"
+msgstr "Veredicto"
+
msgid "Verification Error"
msgstr "Error de verificación"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index a7e17b85c6..c874ce7060 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -48,6 +48,18 @@ msgstr "« {taskName} » est fait – tous les {0} éléments de sa carte de mis
msgid "(excluded for this customer)"
msgstr "(exclu pour ce client)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# jour de marge} other {# jours de marge}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# jour de retard} other {# jours de retard}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# opération n'a pas de normes de temps} other {# opérations n'ont pas de normes de temps}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# ligne se connecte à des données en dehors de cette Société, donc une copie de sécurité de vos données actuelles ne peut pas être créée.} other {# lignes se connectent à des données en dehors de cette Société, donc une copie de sécurité de vos données actuelles ne peut pas être créée.}}"
@@ -399,6 +411,9 @@ 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."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# jour} other {# jours}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# ligne diffère de la quantité attendue} other {# lignes diffèrent de la quantité attendue}}"
@@ -2545,6 +2560,9 @@ msgstr "Êtes-vous sûr de vouloir invalider cette expédition ? Cette action an
msgid "Are you sure?"
msgstr "Êtes-vous sûr ?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Comme s'il avait sauté en avant de la file d'attente de l'atelier."
+
msgid "As needed"
msgstr "Selon les besoins"
@@ -2668,6 +2686,9 @@ msgstr "Attribue cette unité de stockage à un poste de travail (bord de ligne)
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Attribue cette unité à un poste de travail pour les matériaux du bord de ligne, afin que les opérateurs les voient dans la vue de production ; hérité de l'unité parente lorsqu'il est défini là."
+msgid "Assumptions"
+msgstr "Hypothèses"
+
msgid "At each gate"
msgstr "À chaque étape"
@@ -2994,6 +3015,9 @@ msgstr "Projection du meilleur cas"
msgid "Best case…"
msgstr "Meilleur cas…"
+msgid "Best-case finish"
+msgstr "Meilleur cas de fin"
+
msgid "Beta"
msgstr "Bêta"
@@ -3091,6 +3115,9 @@ msgstr "Date de verrouillage des livres (manuel)"
msgid "Both"
msgstr "Les deux"
+msgid "Both finishes compared against a date you choose."
+msgstr "Les deux fins comparées à une date de votre choix."
+
msgid "Bottleneck"
msgstr "Goulot d'étranglement"
@@ -4473,6 +4500,9 @@ msgstr "Impossible de créer le PDF. Réessayez."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Impossible de dissoudre {0}: {1} — production déjà enregistrée"
+msgid "Could not predict lead time"
+msgstr "Impossible de prédire le délai d'approvisionnement"
+
msgid "Could not prepare region image for analysis"
msgstr "Impossible de préparer l'image de la région pour l'analyse"
@@ -6807,6 +6837,9 @@ msgstr "Fin du mois dernier"
msgid "End of Last Quarter"
msgstr "Fin du dernier trimestre"
+msgid "End of queue"
+msgstr "Fin de file d'attente"
+
msgid "End Time"
msgstr "Heure de fin"
@@ -7626,6 +7659,9 @@ 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 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"
@@ -8616,6 +8652,9 @@ msgstr "Si cela bloque ou qu'une date est à risque, cela reçoit un propriétai
msgid "If items already exist"
msgstr "Si des articles existent déjà"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Si commandé aujourd'hui — placé derrière tout ce qui a déjà été lancé."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Si commandé, aucune rupture de stock prévue au cours des 48 prochaines semaines"
@@ -10641,6 +10680,9 @@ msgstr "Ce qui est nécessaire est les heures dues ce jour pour les ordres de fa
msgid "Needs a Business or Partner plan."
msgstr "Nécessite un plan Business ou Partner."
+msgid "Needs expedite"
+msgstr "Doit être accéléré"
+
msgid "Needs fixing"
msgstr "Doit être réparé"
@@ -11618,6 +11660,9 @@ msgstr "Non configuré"
msgid "Not enough jobs to cover quantity"
msgstr "Pas assez d'ordres de fabrication pour couvrir la quantité"
+msgid "Not feasible"
+msgstr "Non réalisable"
+
msgid "Not reached"
msgstr "Non atteint"
@@ -11803,6 +11848,9 @@ msgstr "Sur l'unité de stockage"
msgid "On this operation"
msgstr "Sur cette opération"
+msgid "On time"
+msgstr "À l'heure"
+
msgid "On-account credit available"
msgstr "Crédit en compte disponible"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} équivaut à combien de {1} ?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Une exécution d'un workflow, enregistrée étape par étape avec les valeurs que chaque étape a utilisées et produites, agissant tout au long avec les autorisations du propriétaire du workflow."
+msgid "One or more quantities cannot meet this date"
+msgstr "Une ou plusieurs quantités ne peuvent pas respecter cette date"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Une unité de série ou un lot de production que Carbon suit individuellement, portant son propre statut et attributs tels qu'une date de péremption."
@@ -12646,6 +12697,9 @@ msgstr "Choisir une propriété d'abord"
msgid "Pick a record type…"
msgstr "Choisir un type d'enregistrement…"
+msgid "Pick a target date to compare."
+msgstr "Choisissez une date cible pour la comparer."
+
msgid "Pick a value from an earlier step"
msgstr "Choisir une valeur d'une étape antérieure"
@@ -12906,6 +12960,12 @@ msgstr "Perte de données potentielle"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Pré-rempli pour un nouvel article quand la péremption est Durée fixe."
+msgid "Predict lead time"
+msgstr "Prédire le délai d'approvisionnement"
+
+msgid "Predicting lead time…"
+msgstr "Prédiction du délai d'approvisionnement…"
+
msgid "Preferred Supplier"
msgstr "Fournisseur préféré"
@@ -13585,6 +13645,9 @@ msgstr "Question"
msgid "Queued"
msgstr "En file d'attente"
+msgid "Queued finish"
+msgstr "Fin en file d'attente"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Calme à l'atelier ce soir, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Planning régénéré"
msgid "Scheduled"
msgstr "Planifié"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Programmé en fonction de la charge de travail actuelle de votre atelier. Rien n'est enregistré jusqu'à ce que vous appliquiez."
+
msgid "Scheduled Maintenance"
msgstr "Maintenance Planifiée"
@@ -16866,6 +16932,9 @@ msgstr "Société cible"
msgid "Target customers by type."
msgstr "Cibler les clients par type."
+msgid "Target date"
+msgstr "Date cible"
+
msgid "Target disposition row"
msgstr "Ligne de traitement cible"
@@ -18007,6 +18076,9 @@ msgstr "Ce travail ne sera plus disponible sur l'atelier."
msgid "This job's own required quantity for the material."
msgstr "La quantité propre requise par cette tâche pour le matériau."
+msgid "This line has no routing to schedule."
+msgstr "Cette ligne n'a pas de gamme à planifier."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Ce site ne planifie que les postes de travail dotés en personnel, mais c'est une station sans surveillance (24×7) — elle est exemptée et continue de fonctionner automatiquement."
@@ -19164,6 +19236,9 @@ msgstr "Numéro de TVA"
msgid "Vendor Write-Off Income"
msgstr "Produits de passage en perte fournisseur"
+msgid "Verdict"
+msgstr "Verdict"
+
msgid "Verification Error"
msgstr "Erreur de vérification"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index f31310e88a..178ef1b381 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" पूरा हो गया — इसके सभी
msgid "(excluded for this customer)"
msgstr "(इस ग्राहक के लिए बाहर रखा गया)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# दिन का अतिरिक्त समय} other {# दिन का अतिरिक्त समय}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# दिन की कमी} other {# दिन की कमी}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# ऑपरेशन के लिए कोई समय मानक नहीं है} other {# ऑपरेशन के लिए कोई समय मानक नहीं हैं}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# पंक्ति इस कंपनी के बाहर डेटा से जुड़ी है, इसलिए आपके वर्तमान डेटा की सुरक्षा प्रति नहीं बनाई जा सकती।} other {# पंक्तियाँ इस कंपनी के बाहर डेटा से जुड़ी हैं, इसलिए आपके वर्तमान डेटा की सुरक्षा प्रति नहीं बनाई जा सकती।}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} जॉब अपडेट किए गए"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} अपलोड हो गया — दस्तावेज़ से फ़ील्ड भर दिए गए हैं।"
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# दिन} other {# दिन}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# पंक्ति अपेक्षित मात्रा से भिन्न है} other {# पंक्तियां अपेक्षित मात्रा से भिन्न हैं}}"
@@ -2545,6 +2560,9 @@ msgstr "क्या आप निश्चित हैं कि आप इस
msgid "Are you sure?"
msgstr "क्या आप सुनिश्चित हैं?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "मानो यह कार्यशाला की कतार के आगे कूद गया हो।"
+
msgid "As needed"
msgstr "आवश्यकतानुसार"
@@ -2668,6 +2686,9 @@ msgstr "यह भंडारण इकाई को वर्क सेंट
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "इकाई को लाइनसाइड सामग्री के लिए वर्क सेंटर में असाइन करता है, इसलिए ऑपरेटर इसे उत्पादन दृश्य में देखते हैं; मूल इकाई में सेट किए जाने पर मूल इकाई से विरासत में मिलता है।"
+msgid "Assumptions"
+msgstr "मान्यताएँ"
+
msgid "At each gate"
msgstr "हर गेट पर"
@@ -2994,6 +3015,9 @@ msgstr "सर्वश्रेष्ठ स्थिति प्रक्ष
msgid "Best case…"
msgstr "सर्वश्रेष्ठ स्थिति…"
+msgid "Best-case finish"
+msgstr "सर्वश्रेष्ठ स्थिति में समाप्ति"
+
msgid "Beta"
msgstr "बीटा"
@@ -3091,6 +3115,9 @@ msgstr "पुस्तकें लॉक तारीख (मैनुअल)"
msgid "Both"
msgstr "दोनों"
+msgid "Both finishes compared against a date you choose."
+msgstr "दोनों समाप्तियों की तुलना आपके द्वारा चुनी गई तारीख से की गई है।"
+
msgid "Bottleneck"
msgstr "अड़चन"
@@ -4473,6 +4500,9 @@ msgstr "PDF नहीं बना सके। फिर से कोशिश
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0} को भंग नहीं कर सके: {1} — उत्पादन पहले से दर्ज है"
+msgid "Could not predict lead time"
+msgstr "लीड टाइम की भविष्यवाणी नहीं कर सके"
+
msgid "Could not prepare region image for analysis"
msgstr "विश्लेषण के लिए क्षेत्र छवि तैयार नहीं की जा सकी"
@@ -6807,6 +6837,9 @@ msgstr "पिछले महीने का अंत"
msgid "End of Last Quarter"
msgstr "पिछली तिमाही का अंत"
+msgid "End of queue"
+msgstr "कतार का अंत"
+
msgid "End Time"
msgstr "समाप्ति समय"
@@ -7626,6 +7659,9 @@ msgstr "गणना अपडेट करने में विफल"
msgid "Failed to update item cost"
msgstr "आइटम लागत अपडेट करने में विफल"
+msgid "Failed to update lead times"
+msgstr "लीड टाइम अपडेट करने में विफल"
+
msgid "Failed to update opportunity with purchase order"
msgstr "क्रय आदेश के साथ अवसर अपडेट करने में विफल"
@@ -8616,6 +8652,9 @@ msgstr "यदि यह अवरुद्ध है या एक तारी
msgid "If items already exist"
msgstr "अगर आइटम पहले से मौजूद हैं"
+msgid "If ordered today — placed behind everything already released."
+msgstr "यदि आज ऑर्डर किया गया — सब कुछ पहले से जारी के पीछे रखा जाएगा।"
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "यदि ऑर्डर किया जाता है, तो अगले 48 सप्ताह में कोई स्टॉकआउट प्रक्षेपित नहीं है"
@@ -10641,6 +10680,9 @@ msgstr "आवश्यक उस दिन के कारण काम के
msgid "Needs a Business or Partner plan."
msgstr "एक बिजनेस या पार्टनर प्लान की आवश्यकता है।"
+msgid "Needs expedite"
+msgstr "तेजी की आवश्यकता"
+
msgid "Needs fixing"
msgstr "मरम्मत की आवश्यकता है"
@@ -11618,6 +11660,9 @@ msgstr "कॉन्फ़िगर नहीं किया गया"
msgid "Not enough jobs to cover quantity"
msgstr "मात्रा को कवर करने के लिए पर्याप्त जॉबें नहीं हैं"
+msgid "Not feasible"
+msgstr "संभव नहीं"
+
msgid "Not reached"
msgstr "प्राप्त नहीं"
@@ -11803,6 +11848,9 @@ msgstr "भंडारण इकाई पर"
msgid "On this operation"
msgstr "इस ऑपरेशन पर"
+msgid "On time"
+msgstr "समय पर"
+
msgid "On-account credit available"
msgstr "खाते पर उपलब्ध क्रेडिट"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} कितने {1} के बराबर है?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "एक वर्कफ़्लो का एक निष्पादन, चरण दर चरण रिकॉर्ड किया गया जिसमें प्रत्येक चरण द्वारा उपयोग किए गए और उत्पादित मान शामिल हैं, वर्कफ़्लो के स्वामी की अनुमतियों के साथ पूरे समय कार्य करते हुए।"
+msgid "One or more quantities cannot meet this date"
+msgstr "एक या अधिक मात्रा इस तारीख को पूरी नहीं कर सकती है"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "एक सीरीज यूनिट या एक बैच जो Carbon व्यक्तिगत रूप से अनुसरण करता है, अपनी स्वयं की स्थिति और विशेषताएं जैसे समाप्ति तिथि ले जाता है।"
@@ -12646,6 +12697,9 @@ msgstr "पहले एक प्रॉपर्टी चुनें"
msgid "Pick a record type…"
msgstr "एक रिकॉर्ड प्रकार चुनें…"
+msgid "Pick a target date to compare."
+msgstr "तुलना के लिए एक लक्ष्य तारीख चुनें।"
+
msgid "Pick a value from an earlier step"
msgstr "पहले के एक चरण से मान चुनें"
@@ -12906,6 +12960,12 @@ msgstr "संभावित डेटा हानि"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "समाप्ति Fixed Duration होने पर नई वस्तु के लिए पूर्व-भरी हुई।"
+msgid "Predict lead time"
+msgstr "लीड टाइम की भविष्यवाणी करें"
+
+msgid "Predicting lead time…"
+msgstr "लीड टाइम की भविष्यवाणी जारी है…"
+
msgid "Preferred Supplier"
msgstr "पसंदीदा आपूर्तिकर्ता"
@@ -13585,6 +13645,9 @@ msgstr "प्रश्न"
msgid "Queued"
msgstr "कतार में"
+msgid "Queued finish"
+msgstr "कतार में समाप्ति"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "आज रात फ्लोर पर शांत, {name}।"
@@ -15069,6 +15132,9 @@ msgstr "शेड्यूल पुनर्जनित"
msgid "Scheduled"
msgstr "अनुसूचित"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "आपकी दुकान के वर्तमान कार्यभार के विरुद्ध शेड्यूल किया गया। लागू करने तक कुछ भी सहेजा नहीं जाता है।"
+
msgid "Scheduled Maintenance"
msgstr "अनुसूचित रखरखाव"
@@ -16866,6 +16932,9 @@ msgstr "लक्ष्य कंपनी"
msgid "Target customers by type."
msgstr "ग्राहकों को प्रकार से लक्ष्य करें।"
+msgid "Target date"
+msgstr "लक्ष्य तारीख"
+
msgid "Target disposition row"
msgstr "लक्ष्य निपटान पंक्ति"
@@ -18007,6 +18076,9 @@ msgstr "यह नौकरी अब शॉप फ्लोर पर उपल
msgid "This job's own required quantity for the material."
msgstr "इस सामग्री के लिए इस कार्य की अपनी आवश्यक मात्रा।"
+msgid "This line has no routing to schedule."
+msgstr "इस पंक्ति के पास शेड्यूल करने के लिए कोई रूटिंग नहीं है।"
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "यह स्थान केवल स्टाफ वाले वर्क सेंटर को शेड्यूल करता है, लेकिन यह एक लाइट्स-आउट (24×7) स्टेशन है — यह छूट प्राप्त है और निरीक्षण के बिना चल रहा है।"
@@ -19164,6 +19236,9 @@ msgstr "वैट नंबर"
msgid "Vendor Write-Off Income"
msgstr "विक्रेता बट्टे खाते आय"
+msgid "Verdict"
+msgstr "परिणाम"
+
msgid "Verification Error"
msgstr "सत्यापन त्रुटि"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 06deadcbeb..0e37cd22a5 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" è completato — tutti i {0} articoli della sua Mappa di
msgid "(excluded for this customer)"
msgstr "(escluso per questo cliente)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# giorno di margine} other {# giorni di margine}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# giorno di ritardo} other {# giorni di ritardo}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# operazione senza standard di tempo} other {# operazioni senza standard di tempo}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# riga si collega ai dati al di fuori di questa Azienda, quindi non è possibile fare una copia di sicurezza dei dati attuali.} other {# righe si collegano ai dati al di fuori di questa Azienda, quindi non è possibile fare una copia di sicurezza dei dati attuali.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} ordini di produzione aggiornati"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} caricato — campi compilati dal documento."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# giorno} other {# giorni}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# riga differisce dalla quantità prevista} other {# righe differiscono dalla quantità prevista}}"
@@ -2545,6 +2560,9 @@ msgstr "Sei sicuro di voler stornare questa spedizione? Questa azione annullerà
msgid "Are you sure?"
msgstr "Sei sicuro?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Come se saltasse davanti in coda all'officina."
+
msgid "As needed"
msgstr "Su richiesta"
@@ -2668,6 +2686,9 @@ msgstr "Assegna questa unità di stoccaggio a un centro di lavoro (bordo linea)"
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Assegna questa unità a un centro di lavoro per il materiale a bordo linea, in modo che gli operatori lo vedano nella visualizzazione della produzione; ereditato dall'unità padre se impostato lì."
+msgid "Assumptions"
+msgstr "Presupposti"
+
msgid "At each gate"
msgstr "Ad ogni gate"
@@ -2994,6 +3015,9 @@ msgstr "Proiezione migliore"
msgid "Best case…"
msgstr "Caso migliore…"
+msgid "Best-case finish"
+msgstr "Completamento nel caso migliore"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Data di blocco dei registri (manuale)"
msgid "Both"
msgstr "Entrambi"
+msgid "Both finishes compared against a date you choose."
+msgstr "Entrambi i tempi di fine confrontati con una data a tua scelta."
+
msgid "Bottleneck"
msgstr "Collo di bottiglia"
@@ -4473,6 +4500,9 @@ msgstr "Impossibile creare il PDF. Riprova."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Impossibile dissolvere {0}: {1} — produzione già registrata"
+msgid "Could not predict lead time"
+msgstr "Impossibile prevedere il lead time"
+
msgid "Could not prepare region image for analysis"
msgstr "Impossibile preparare l'immagine della regione per l'analisi"
@@ -6807,6 +6837,9 @@ msgstr "Fine del mese scorso"
msgid "End of Last Quarter"
msgstr "Fine dell'ultimo trimestre"
+msgid "End of queue"
+msgstr "Fine della coda"
+
msgid "End Time"
msgstr "Ora di fine"
@@ -7626,6 +7659,9 @@ msgstr "Impossibile aggiornare il conteggio"
msgid "Failed to update item cost"
msgstr "Impossibile aggiornare il costo dell'articolo"
+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"
@@ -8616,6 +8652,9 @@ msgstr "Se blocca o una data è a rischio, riceve un responsabile ed è tracciat
msgid "If items already exist"
msgstr "Se gli articoli esistono già"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Se ordinato oggi — posizionato dietro tutto ciò che è già Rilasciato."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Se ordinato, nessuna rottura di stock prevista nelle prossime 48 settimane"
@@ -10641,6 +10680,9 @@ msgstr "Necessario sono le ore di lavoro dovute quel giorno divise per {personDa
msgid "Needs a Business or Partner plan."
msgstr "Richiede un piano Business o Partner."
+msgid "Needs expedite"
+msgstr "Richiede urgenza"
+
msgid "Needs fixing"
msgstr "Necessita correzione"
@@ -11618,6 +11660,9 @@ msgstr "Non Configurato"
msgid "Not enough jobs to cover quantity"
msgstr "Non ci sono abbastanza ordini di produzione per coprire la quantità"
+msgid "Not feasible"
+msgstr "Non fattibile"
+
msgid "Not reached"
msgstr "Non raggiunto"
@@ -11803,6 +11848,9 @@ msgstr "Su Unità di Stoccaggio"
msgid "On this operation"
msgstr "Su questa operazione"
+msgid "On time"
+msgstr "Puntuale"
+
msgid "On-account credit available"
msgstr "Credito a conto disponibile"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} equivale a quanti {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Un'esecuzione di un flusso di lavoro, registrata passo dopo passo con i valori che ogni passo ha utilizzato e prodotto, agendo con le autorizzazioni del proprietario del flusso di lavoro."
+msgid "One or more quantities cannot meet this date"
+msgstr "Una o più quantità non possono rispettare questa data"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Un'unità seriale o un lotto che Carbon segue individualmente, portando il suo stato e gli attributi propri come una data di scadenza."
@@ -12646,6 +12697,9 @@ msgstr "Scegli prima una proprietà"
msgid "Pick a record type…"
msgstr "Scegli un tipo di record…"
+msgid "Pick a target date to compare."
+msgstr "Seleziona una data di destinazione da confrontare."
+
msgid "Pick a value from an earlier step"
msgstr "Scegli un valore da un passaggio precedente"
@@ -12906,6 +12960,12 @@ msgstr "Potenziale perdita di dati"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Pre-compilato per un nuovo articolo quando la scadenza è Durata Fissa."
+msgid "Predict lead time"
+msgstr "Prevedi il lead time"
+
+msgid "Predicting lead time…"
+msgstr "Previsione del lead time…"
+
msgid "Preferred Supplier"
msgstr "Fornitore preferenziale"
@@ -13585,6 +13645,9 @@ msgstr "Domanda"
msgid "Queued"
msgstr "In coda"
+msgid "Queued finish"
+msgstr "Completamento in coda"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Tranquillo in officina stasera, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Programma rigenerato"
msgid "Scheduled"
msgstr "Programmato"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Programmato rispetto al carico di lavoro attuale della tua officina. Nulla viene salvato finché non applichi."
+
msgid "Scheduled Maintenance"
msgstr "Manutenzione Programmata"
@@ -16866,6 +16932,9 @@ msgstr "Azienda di Destinazione"
msgid "Target customers by type."
msgstr "Indirizzare clienti per tipo."
+msgid "Target date"
+msgstr "Data di destinazione"
+
msgid "Target disposition row"
msgstr "Riga di disposizione di destinazione"
@@ -18007,6 +18076,9 @@ msgstr "Questo lavoro non sarà più disponibile in officina."
msgid "This job's own required quantity for the material."
msgstr "La quantità richiesta da questo lavoro per il materiale."
+msgid "This line has no routing to schedule."
+msgstr "Questa riga non ha un ciclo di lavorazione da programmare."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Questa ubicazione pianifica solo centri di lavoro con personale assegnato, ma questa è una stazione di lights-out (24×7) — è esente e continua a funzionare senza supervisione."
@@ -19164,6 +19236,9 @@ msgstr "Partita IVA"
msgid "Vendor Write-Off Income"
msgstr "Proventi da Stralcio"
+msgid "Verdict"
+msgstr "Verdetto"
+
msgid "Verification Error"
msgstr "Errore di verifica"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 474e00b2e4..cc0eb09217 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -48,6 +48,18 @@ msgstr "「{taskName}」は完了しました — セットアップマップの
msgid "(excluded for this customer)"
msgstr "(この得意先から除外)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# 日のスラック} other {# 日のスラック}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# 日の不足} other {# 日の不足}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# 工程に標準時間がない} other {# 工程に標準時間がない}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# 行はこの会社の外部のデータにリンクしているため、現在のデータの安全なコピーを作成できません。} other {# 行はこの会社の外部のデータにリンクしているため、現在のデータの安全なコピーを作成できません。}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} 件の製造指図が更新されました"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} がアップロードされました — フィールドは文書から入力されました。"
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# 日} other {# 日}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# 行が予想数量と異なります} other {# 行が予想数量と異なります}}"
@@ -2545,6 +2560,9 @@ msgstr "この出荷を取消してもよろしいですか?この操作はす
msgid "Are you sure?"
msgstr "本当ですか?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "工場の処理待ちキューの最前列に割り込むように。"
+
msgid "As needed"
msgstr "必要に応じて"
@@ -2668,6 +2686,9 @@ msgstr "この保管ユニットを作業区(ラインサイド)に割り当
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "この保管ユニットをラインサイド材料用の作業区に割り当てます。作業者は生産ビューでそれを参照できます。親ユニットで設定されている場合、そこから継承されます。"
+msgid "Assumptions"
+msgstr "前提条件"
+
msgid "At each gate"
msgstr "各ゲートで"
@@ -2994,6 +3015,9 @@ msgstr "最良ケース予測"
msgid "Best case…"
msgstr "最良ケース…"
+msgid "Best-case finish"
+msgstr "ベストケース完了"
+
msgid "Beta"
msgstr "ベータ"
@@ -3091,6 +3115,9 @@ msgstr "帳簿ロック日 (手動)"
msgid "Both"
msgstr "両方"
+msgid "Both finishes compared against a date you choose."
+msgstr "両方の完了予定日を選択した日付と比較。"
+
msgid "Bottleneck"
msgstr "ボトルネック"
@@ -4473,6 +4500,9 @@ msgstr "PDFを作成できませんでした。もう一度お試しください
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0}を解除できません: {1} — 生産がすでに記録されています"
+msgid "Could not predict lead time"
+msgstr "リードタイムを予測できませんでした"
+
msgid "Could not prepare region image for analysis"
msgstr "分析用の領域画像を準備できませんでした"
@@ -6807,6 +6837,9 @@ msgstr "先月末"
msgid "End of Last Quarter"
msgstr "前四半期末"
+msgid "End of queue"
+msgstr "キューの末尾"
+
msgid "End Time"
msgstr "終了時刻"
@@ -7626,6 +7659,9 @@ msgstr "カウントの更新に失敗しました"
msgid "Failed to update item cost"
msgstr "品目の原価を更新できませんでした"
+msgid "Failed to update lead times"
+msgstr "リードタイムの更新に失敗しました"
+
msgid "Failed to update opportunity with purchase order"
msgstr "商談を発注書で更新できませんでした"
@@ -8616,6 +8652,9 @@ msgstr "ブロック状態か期日がリスクの場合は、責任者が割り
msgid "If items already exist"
msgstr "アイテムが既に存在する場合"
+msgid "If ordered today — placed behind everything already released."
+msgstr "今日注文した場合 — すでにリリース済のすべてのジョブの後ろに配置されます。"
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "発注済の場合、今後48週間での欠品は見込まれていません"
@@ -10641,6 +10680,9 @@ msgstr "必要人数は、その日の予定作業時間を{personDayHours}hで
msgid "Needs a Business or Partner plan."
msgstr "ビジネスプランまたはパートナープランが必要です。"
+msgid "Needs expedite"
+msgstr "加速が必要"
+
msgid "Needs fixing"
msgstr "修理が必要です"
@@ -11618,6 +11660,9 @@ msgstr "未設定"
msgid "Not enough jobs to cover quantity"
msgstr "数量をカバーするのに十分な製造指図がありません"
+msgid "Not feasible"
+msgstr "実現不可能"
+
msgid "Not reached"
msgstr "未到達"
@@ -11803,6 +11848,9 @@ msgstr "保管ユニット上"
msgid "On this operation"
msgstr "この操作で"
+msgid "On time"
+msgstr "オンタイム"
+
msgid "On-account credit available"
msgstr "掛け売掛金利用可能"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} は何 {1} に相当しますか?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "ワークフローの1回の実行。各ステップが使用および生成した値を含めてステップバイステップで記録され、全体を通じてワークフロー責任者の権限で実行されます。"
+msgid "One or more quantities cannot meet this date"
+msgstr "1つ以上の数量がこの日付に対応できません"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Carbonが個別に追跡する1個のシリアルユニットまたは1つのバッチ。使用期限などのステータスと属性を独自に保有しています。"
@@ -12646,6 +12697,9 @@ msgstr "まずプロパティを選択"
msgid "Pick a record type…"
msgstr "レコード種類を選択..."
+msgid "Pick a target date to compare."
+msgstr "比較するターゲット日を選択してください。"
+
msgid "Pick a value from an earlier step"
msgstr "前のステップの値を選択"
@@ -12906,6 +12960,12 @@ msgstr "潜在的データ損失"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "使用期限が固定期間の場合、新規品目に対して事前入力されます。"
+msgid "Predict lead time"
+msgstr "リードタイムを予測"
+
+msgid "Predicting lead time…"
+msgstr "リードタイムを予測中…"
+
msgid "Preferred Supplier"
msgstr "優先仕入先"
@@ -13585,6 +13645,9 @@ msgstr "質問"
msgid "Queued"
msgstr "キュー待ち"
+msgid "Queued finish"
+msgstr "キュー待ち完了"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "今夜のフロアは静かですね、{name}さん。"
@@ -15069,6 +15132,9 @@ msgstr "スケジュール再生成完了"
msgid "Scheduled"
msgstr "スケジュール済み"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "現在のショップの作業負荷に基づいてスケジュールされています。適用するまで何も保存されません。"
+
msgid "Scheduled Maintenance"
msgstr "計画保全"
@@ -16866,6 +16932,9 @@ msgstr "対象会社"
msgid "Target customers by type."
msgstr "得意先をタイプ別に絞り込む。"
+msgid "Target date"
+msgstr "目標日"
+
msgid "Target disposition row"
msgstr "対象の処置行"
@@ -18007,6 +18076,9 @@ msgstr "この製造指図は製造現場で利用できなくなります。"
msgid "This job's own required quantity for the material."
msgstr "この材料に対するこのジョブ自体の必要数量。"
+msgid "This line has no routing to schedule."
+msgstr "この明細にはスケジュール対象の工順がありません。"
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "この拠点は人員配置された作業区のみをスケジュールしますが、これは無人(24×7)ステーションです — 適用対象外であり、無人で稼働し続けます。"
@@ -19164,6 +19236,9 @@ msgstr "VAT番号"
msgid "Vendor Write-Off Income"
msgstr "仕入先償却収益"
+msgid "Verdict"
+msgstr "判定"
+
msgid "Verification Error"
msgstr "認証エラー"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index f476d76f6f..525a588233 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" 완료 — 설정 맵 항목 {0}개가 모두 설정되
msgid "(excluded for this customer)"
msgstr "(이 고객에게는 제외됨)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {여유 # 일} other {여유 # 일}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# 일 부족} other {# 일 부족}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# 공정에 표준시간이 없습니다} other {# 공정에 표준시간이 없습니다}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# 행은 이 회사 외부의 데이터에 연결되어 있어서 현재 데이터의 안전한 사본을 만들 수 없습니다.} other {# 행은 이 회사 외부의 데이터에 연결되어 있어서 현재 데이터의 안전한 사본을 만들 수 없습니다.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount}개의 작업 지시 업데이트됨"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} 업로드됨 — 문서에서 필드가 채워졌습니다."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# 일} other {# 일}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# 라인이 예상 수량과 다릅니다} other {# 라인이 예상 수량과 다릅니다}}"
@@ -2545,6 +2560,9 @@ msgstr "이 출하를 무효 처리하시겠습니까? 이 작업은 모든 재
msgid "Are you sure?"
msgstr "확실합니까?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "마치 공장의 대기열 맨 앞으로 뛰어든 것처럼."
+
msgid "As needed"
msgstr "필요 시"
@@ -2668,6 +2686,9 @@ msgstr "이 보관 단위를 작업장(라인사이드)에 할당합니다"
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "라인사이드 자재를 위해 이 보관 단위를 작업장에 할당하므로 작업자들이 생산 화면에서 볼 수 있습니다. 부모 단위에 설정되면 상속됩니다."
+msgid "Assumptions"
+msgstr "가정사항"
+
msgid "At each gate"
msgstr "각 게이트마다"
@@ -2994,6 +3015,9 @@ msgstr "최선의 경우 예측"
msgid "Best case…"
msgstr "최선의 경우…"
+msgid "Best-case finish"
+msgstr "최단 완료"
+
msgid "Beta"
msgstr "베타"
@@ -3091,6 +3115,9 @@ msgstr "장부 잠금 날짜(수동)"
msgid "Both"
msgstr "모두"
+msgid "Both finishes compared against a date you choose."
+msgstr "두 완료 날짜를 선택한 날짜와 비교합니다."
+
msgid "Bottleneck"
msgstr "병목"
@@ -4473,6 +4500,9 @@ msgstr "PDF를 생성할 수 없습니다. 다시 시도하세요."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0}을(를) 해제할 수 없습니다: {1} — 생산이 이미 기록됨"
+msgid "Could not predict lead time"
+msgstr "리드타임을 예측할 수 없습니다"
+
msgid "Could not prepare region image for analysis"
msgstr "분석을 위한 영역 이미지를 준비할 수 없습니다"
@@ -6807,6 +6837,9 @@ msgstr "지난달 말"
msgid "End of Last Quarter"
msgstr "지난 분기 말"
+msgid "End of queue"
+msgstr "대기열 끝"
+
msgid "End Time"
msgstr "종료 시간"
@@ -7626,6 +7659,9 @@ msgstr "카운트를 업데이트하지 못했습니다"
msgid "Failed to update item cost"
msgstr "품목 원가를 업데이트하지 못했습니다"
+msgid "Failed to update lead times"
+msgstr "리드타임 업데이트 실패"
+
msgid "Failed to update opportunity with purchase order"
msgstr "발주서로 영업 기회 업데이트 실패"
@@ -8616,6 +8652,9 @@ msgstr "차단 중이거나 날짜가 위험하면 책임자가 지정되고 추
msgid "If items already exist"
msgstr "품목이 이미 존재하는 경우"
+msgid "If ordered today — placed behind everything already released."
+msgstr "오늘 발주하면 — 이미 릴리스된 모든 작업 뒤에 배치됩니다."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "주문할 경우, 향후 48주간 재고 부족이 예상되지 않습니다"
@@ -10641,6 +10680,9 @@ msgstr "필요한 것은 그 날의 작업 지시 시간을 {personDayHours}h로
msgid "Needs a Business or Partner plan."
msgstr "Business 또는 Partner 요금제가 필요합니다."
+msgid "Needs expedite"
+msgstr "긴급 처리 필요"
+
msgid "Needs fixing"
msgstr "수정 필요"
@@ -11618,6 +11660,9 @@ msgstr "미설정"
msgid "Not enough jobs to cover quantity"
msgstr "수량을 충당하기에 충분한 작업 지시가 없습니다."
+msgid "Not feasible"
+msgstr "불가능"
+
msgid "Not reached"
msgstr "도달하지 않음"
@@ -11803,6 +11848,9 @@ msgstr "보관 단위에"
msgid "On this operation"
msgstr "이 작업 시"
+msgid "On time"
+msgstr "정시"
+
msgid "On-account credit available"
msgstr "계정상 가용 신용"
@@ -11838,6 +11886,9 @@ msgstr "1 {0}은(는) 몇 {1}입니까?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "워크플로의 한 번 실행으로, 각 단계가 사용하고 생성한 값을 단계별로 기록하며 워크플로 책임자의 권한으로 전체적으로 작동합니다."
+msgid "One or more quantities cannot meet this date"
+msgstr "하나 이상의 수량이 이 날짜를 충족할 수 없습니다"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Carbon이 개별적으로 추적하는 하나의 일련 단위 또는 하나의 배치로, 유통기한과 같은 자체 상태와 속성을 가집니다."
@@ -12646,6 +12697,9 @@ msgstr "먼저 속성 선택"
msgid "Pick a record type…"
msgstr "레코드 유형 선택…"
+msgid "Pick a target date to compare."
+msgstr "비교할 목표 날짜를 선택하세요."
+
msgid "Pick a value from an earlier step"
msgstr "이전 단계에서 값 선택"
@@ -12906,6 +12960,12 @@ msgstr "데이터 손실 가능성"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "유통기한이 고정 기간일 때 새 품목에 대해 미리 입력됨."
+msgid "Predict lead time"
+msgstr "리드타임 예측"
+
+msgid "Predicting lead time…"
+msgstr "리드타임 예측 중…"
+
msgid "Preferred Supplier"
msgstr "우선 공급업체"
@@ -13585,6 +13645,9 @@ msgstr "질문"
msgid "Queued"
msgstr "대기열"
+msgid "Queued finish"
+msgstr "대기열 완료"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "{name}님, 오늘 밤 현장이 조용하네요."
@@ -15069,6 +15132,9 @@ msgstr "일정 재생성됨"
msgid "Scheduled"
msgstr "예정됨"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "현재 공장의 작업 부하를 고려하여 일정을 수립했습니다. 적용하기 전까지는 저장되지 않습니다."
+
msgid "Scheduled Maintenance"
msgstr "예정된 유지보수"
@@ -16866,6 +16932,9 @@ msgstr "대상 회사"
msgid "Target customers by type."
msgstr "유형별로 고객을 대상으로 지정합니다."
+msgid "Target date"
+msgstr "목표 날짜"
+
msgid "Target disposition row"
msgstr "처분 결정 대상 행"
@@ -18007,6 +18076,9 @@ msgstr "이 작업 지시는 현장에서 더 이상 가용하지 않을 것입
msgid "This job's own required quantity for the material."
msgstr "이 작업 자체의 자재 소요 수량입니다."
+msgid "This line has no routing to schedule."
+msgstr "이 라인은 일정 계획을 위한 라우팅이 없습니다."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "이 사업장은 인력이 배치된 작업장만 일정을 계획하지만, 이것은 무인(24×7) 작업장입니다 — 면제되며 무인으로 계속 운영됩니다."
@@ -19164,6 +19236,9 @@ msgstr "사업자등록번호"
msgid "Vendor Write-Off Income"
msgstr "공급업체 대손 처리 수익"
+msgid "Verdict"
+msgstr "판정"
+
msgid "Verification Error"
msgstr "확인 오류"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 3b3ab4c2bb..7c116b1677 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -48,6 +48,18 @@ msgstr "„{taskName}\" jest gotowe — wszystkie {0} jego elementów Setup Map
msgid "(excluded for this customer)"
msgstr "(wykluczone dla tego klienta)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# dzień luzu} few {# dni luzu} many {# dni luzu} other {# dni luzu}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# dzień za krótko} few {# dni za krótko} many {# dni za krótko} other {# dni za krótko}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# operacja nie ma standardów czasu} few {# operacje nie mają standardów czasu} many {# operacji nie ma standardów czasu} other {# operacji nie ma standardów czasu}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# wiersz łączy się z danymi spoza tej firmy, dlatego nie można utworzyć kopii bezpieczeństwa bieżących danych.} other {# wierszy łączy się z danymi spoza tej firmy, dlatego nie można utworzyć kopii bezpieczeństwa bieżących danych.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} zleceń produkcyjnych zaktualizowanych"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "Przesłano {uploadedFileName} — pola wypełniono na podstawie dokumentu."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# dzień} few {# dni} many {# dni} other {# dni}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# pozycja różni się od oczekiwanej ilości} other {# pozycje różnią się od oczekiwanej ilości}}"
@@ -2545,6 +2560,9 @@ msgstr "Czy na pewno chcesz unieważnić tę wysyłkę? Ta akcja odwróci wszyst
msgid "Are you sure?"
msgstr "Jesteś pewny?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Jakby wysunęło się na początek kolejki warsztatu."
+
msgid "As needed"
msgstr "W razie potrzeby"
@@ -2668,6 +2686,9 @@ msgstr "Przypisuje tę jednostkę magazynową do stanowiska roboczego (magazyn p
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Przypisuje tę jednostkę do stanowiska roboczego dla materiału magazynu przyliniowego, aby operatorzy widzieli ją w widoku produkcji; odziedziczone z jednostki nadrzędnej, jeśli tam zostały ustawione."
+msgid "Assumptions"
+msgstr "Założenia"
+
msgid "At each gate"
msgstr "Na każdej bramce"
@@ -2994,6 +3015,9 @@ msgstr "Projekcja najlepszego scenariusza"
msgid "Best case…"
msgstr "Najlepszy scenariusz…"
+msgid "Best-case finish"
+msgstr "Koniec w najlepszym scenariuszu"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Data zablokowania ksiąg (ręczna)"
msgid "Both"
msgstr "Oba"
+msgid "Both finishes compared against a date you choose."
+msgstr "Oba scenariusze porównane względem wybranej daty."
+
msgid "Bottleneck"
msgstr "Wąskie gardło"
@@ -4473,6 +4500,9 @@ msgstr "Nie można było zbudować pliku PDF. Spróbuj ponownie."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Nie można rozwiązać {0}: {1} — produkcja już zapisana"
+msgid "Could not predict lead time"
+msgstr "Nie można było przewidzieć czasu realizacji"
+
msgid "Could not prepare region image for analysis"
msgstr "Nie można przygotować obrazu regionu do analizy"
@@ -6807,6 +6837,9 @@ msgstr "Koniec ostatniego miesiąca"
msgid "End of Last Quarter"
msgstr "Koniec ostatniego kwartału"
+msgid "End of queue"
+msgstr "Koniec kolejki"
+
msgid "End Time"
msgstr "Czas zakończenia"
@@ -7626,6 +7659,9 @@ 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 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"
@@ -8616,6 +8652,9 @@ msgstr "Jeśli coś blokuje lub data jest zagrożona, zostaje przypisane właśc
msgid "If items already exist"
msgstr "Jeśli elementy już istnieją"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Jeśli zamówiono dzisiaj — umieszczone za wszystkim już zwolnionym."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Jeśli zamówione, brak prognozowanego braku zapasów w ciągu następnych 48 tygodni"
@@ -10641,6 +10680,9 @@ msgstr "Potrzebne = godziny pracy przypadające tego dnia podzielone przez {pers
msgid "Needs a Business or Partner plan."
msgstr "Wymaga planu Business lub Partner."
+msgid "Needs expedite"
+msgstr "Wymaga przyspieszenia"
+
msgid "Needs fixing"
msgstr "Wymaga naprawy"
@@ -11618,6 +11660,9 @@ msgstr "Nie skonfigurowane"
msgid "Not enough jobs to cover quantity"
msgstr "Niewystarczająco zleceń produkcyjnych aby pokryć ilość"
+msgid "Not feasible"
+msgstr "Niemożliwe do wykonania"
+
msgid "Not reached"
msgstr "Nieosiągnięty"
@@ -11803,6 +11848,9 @@ msgstr "Na jednostce magazynowej"
msgid "On this operation"
msgstr "Na tej operacji"
+msgid "On time"
+msgstr "Na czas"
+
msgid "On-account credit available"
msgstr "Dostępny kredyt na koncie"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} to ile {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Jedno wykonanie przepływu pracy, zarejestrowane krok po kroku z wartościami, które każdy krok użył i wygenerował, działając z uprawnieniami właściciela przepływu pracy."
+msgid "One or more quantities cannot meet this date"
+msgstr "Jedna lub więcej ilości nie może spełnić tego terminu"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Jedna jednostka o numerze seryjnym lub jedna partia produkcyjna, którą Carbon śledzi indywidualnie, posiadająca własny status i atrybuty takie jak termin ważności."
@@ -12646,6 +12697,9 @@ msgstr "Najpierw wybierz właściwość"
msgid "Pick a record type…"
msgstr "Wybierz typ rekordu…"
+msgid "Pick a target date to compare."
+msgstr "Wybierz docelowy termin do porównania."
+
msgid "Pick a value from an earlier step"
msgstr "Wybierz wartość z wcześniejszego kroku"
@@ -12906,6 +12960,12 @@ msgstr "Potencjalna utrata danych"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Wstępnie wypełnione dla nowego artykułu, gdy termin ważności to Stały okres."
+msgid "Predict lead time"
+msgstr "Przewidź czas realizacji"
+
+msgid "Predicting lead time…"
+msgstr "Prognozowanie czasu realizacji…"
+
msgid "Preferred Supplier"
msgstr "Preferowany dostawca"
@@ -13585,6 +13645,9 @@ msgstr "Pytanie"
msgid "Queued"
msgstr "W kolejce"
+msgid "Queued finish"
+msgstr "Ukończenie w kolejce"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Cicho na hali dzisiaj wieczorem, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Harmonogram wygenerowany"
msgid "Scheduled"
msgstr "Zaplanowano"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Zaplanowany względem obecnego obciążenia Twojego warsztatu. Nic nie będzie zapisane do czasu zastosowania."
+
msgid "Scheduled Maintenance"
msgstr "Zaplanowane utrzymanie ruchu"
@@ -16866,6 +16932,9 @@ msgstr "Firma Docelowa"
msgid "Target customers by type."
msgstr "Kieruj się na klientów według typu."
+msgid "Target date"
+msgstr "Data docelowa"
+
msgid "Target disposition row"
msgstr "Docelowy wiersz dyspozycji"
@@ -18007,6 +18076,9 @@ msgstr "To zlecenie produkcyjne nie będzie już dostępne na hali produkcyjnej.
msgid "This job's own required quantity for the material."
msgstr "Własna wymagana ilość materiału dla tego zadania."
+msgid "This line has no routing to schedule."
+msgstr "Ta pozycja nie ma przypisanej marszruty do zaplanowania."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Ta lokalizacja planuje tylko stanowiska robocze z obsadą personelu, ale to stanowisko pracuje w trybie lights-out (24×7) — jest zwolnione z planowania i pracuje bez nadzoru."
@@ -19164,6 +19236,9 @@ msgstr "NIP"
msgid "Vendor Write-Off Income"
msgstr "Przychody ze spisania od dostawcy"
+msgid "Verdict"
+msgstr "Werdykt"
+
msgid "Verification Error"
msgstr "Błąd weryfikacji"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index bc28d61e68..18c2e3ba9d 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" está feito — todos os {0} itens do seu Mapa de Setup e
msgid "(excluded for this customer)"
msgstr "(excluído para este cliente)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# dia de folga} other {# dias de folga}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# dia de falta} other {# dias de falta}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# operação não tem padrões de tempo} other {# operações não têm padrões de tempo}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# linha vincula dados fora desta empresa, portanto uma cópia de segurança de seus dados atuais não pode ser feita.} other {# linhas vinculam dados fora desta empresa, portanto uma cópia de segurança de seus dados atuais não pode ser feita.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} ordens de produção atualizadas"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} enviado — campos preenchidos a partir do documento."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# dia} other {# dias}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# linha difere da quantidade esperada} other {# linhas diferem da quantidade esperada}}"
@@ -2545,6 +2560,9 @@ msgstr "Tem certeza de que deseja anular esta remessa? Esta ação reverterá to
msgid "Are you sure?"
msgstr "Tem a certeza?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Como se pulasse para o topo da fila da oficina."
+
msgid "As needed"
msgstr "Conforme necessário"
@@ -2668,6 +2686,9 @@ msgstr "Atribui esta unidade de armazenamento a um centro de trabalho (borda de
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Atribui esta unidade a um centro de trabalho para material de borda de linha, para que os operadores a vejam na visualização de produção; herdada da unidade pai quando configurada lá."
+msgid "Assumptions"
+msgstr "Premissas"
+
msgid "At each gate"
msgstr "Em cada etapa"
@@ -2994,6 +3015,9 @@ msgstr "Projeção do melhor caso"
msgid "Best case…"
msgstr "Melhor caso…"
+msgid "Best-case finish"
+msgstr "Melhor caso de conclusão"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Data de bloqueio de livros (manual)"
msgid "Both"
msgstr "Ambos"
+msgid "Both finishes compared against a date you choose."
+msgstr "Ambas as datas de conclusão comparadas com a data que você escolher."
+
msgid "Bottleneck"
msgstr "Gargalo"
@@ -4473,6 +4500,9 @@ msgstr "Não foi possível criar o PDF. Tente novamente."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Não foi possível dissolver {0}: {1} — produção já registrada"
+msgid "Could not predict lead time"
+msgstr "Não foi possível prever o Lead time"
+
msgid "Could not prepare region image for analysis"
msgstr "Não foi possível preparar a imagem da região para análise"
@@ -6807,6 +6837,9 @@ msgstr "Fim do Mês Anterior"
msgid "End of Last Quarter"
msgstr "Fim do Trimestre Anterior"
+msgid "End of queue"
+msgstr "Fim da fila"
+
msgid "End Time"
msgstr "Hora de Término"
@@ -7626,6 +7659,9 @@ msgstr "Falha ao atualizar contagem"
msgid "Failed to update item cost"
msgstr "Falha ao atualizar custo do item"
+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"
@@ -8616,6 +8652,9 @@ msgstr "Se está bloqueando ou uma data está em risco, recebe um responsável e
msgid "If items already exist"
msgstr "Se os itens já existem"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Se encomendado hoje — colocado atrás de tudo já liberado."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Se houver pedido emitido, nenhuma ruptura de estoque projetada nas próximas 48 semanas"
@@ -10641,6 +10680,9 @@ msgstr "Necessário é as horas de trabalho devidas naquele dia divididas por {p
msgid "Needs a Business or Partner plan."
msgstr "Requer um plano Business ou Partner."
+msgid "Needs expedite"
+msgstr "Requer aceleração"
+
msgid "Needs fixing"
msgstr "Precisa de reparo"
@@ -11618,6 +11660,9 @@ msgstr "Não Configurado"
msgid "Not enough jobs to cover quantity"
msgstr "Não há ordens de produção suficientes para cobrir a quantidade"
+msgid "Not feasible"
+msgstr "Não é viável"
+
msgid "Not reached"
msgstr "Não atingido"
@@ -11803,6 +11848,9 @@ msgstr "Na Unidade de Armazenamento"
msgid "On this operation"
msgstr "Nesta operação"
+msgid "On time"
+msgstr "No prazo"
+
msgid "On-account credit available"
msgstr "Crédito em conta disponível"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} equivale a quantos {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Uma execução de um fluxo de trabalho, registrada passo a passo com os valores que cada etapa usou e produziu, agindo sempre com as permissões do proprietário do fluxo de trabalho."
+msgid "One or more quantities cannot meet this date"
+msgstr "Uma ou mais quantidades não podem atender esta data"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Uma unidade serial ou um lote que Carbon acompanha individualmente, carregando seu próprio status e atributos como data de validade."
@@ -12646,6 +12697,9 @@ msgstr "Escolha uma propriedade primeiro"
msgid "Pick a record type…"
msgstr "Escolha um tipo de registro…"
+msgid "Pick a target date to compare."
+msgstr "Escolha uma data de destino para comparar."
+
msgid "Pick a value from an earlier step"
msgstr "Escolha um valor de uma etapa anterior"
@@ -12906,6 +12960,12 @@ msgstr "Possível Perda de Dados"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Pré-preenchido para um novo item quando a validade é Duração Fixa."
+msgid "Predict lead time"
+msgstr "Prever Lead time"
+
+msgid "Predicting lead time…"
+msgstr "Prevendo Lead time…"
+
msgid "Preferred Supplier"
msgstr "Fornecedor preferencial"
@@ -13585,6 +13645,9 @@ msgstr "Pergunta"
msgid "Queued"
msgstr "Na fila"
+msgid "Queued finish"
+msgstr "Conclusão na fila"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Tranquilo no piso esta noite, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Programação regenerada"
msgid "Scheduled"
msgstr "Agendado"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Programado contra a carga de trabalho atual da sua oficina. Nada é salvo até que você aplique."
+
msgid "Scheduled Maintenance"
msgstr "Manutenção Agendada"
@@ -16866,6 +16932,9 @@ msgstr "Empresa Alvo"
msgid "Target customers by type."
msgstr "Segmentar clientes por tipo."
+msgid "Target date"
+msgstr "Data de destino"
+
msgid "Target disposition row"
msgstr "Linha de disposição de destino"
@@ -18007,6 +18076,9 @@ msgstr "Este trabalho não estará mais disponível no chão de fábrica."
msgid "This job's own required quantity for the material."
msgstr "A quantidade própria exigida por este trabalho para o material."
+msgid "This line has no routing to schedule."
+msgstr "Esta Linha não possui Roteiro de produção para programar."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Este local programa apenas centros de trabalho com escalação, mas esta é uma estação sem pessoal (24×7) — ela está isenta e continua funcionando sem supervisão."
@@ -19164,6 +19236,9 @@ msgstr "Número de IVA"
msgid "Vendor Write-Off Income"
msgstr "Receitas de baixa contábil de fornecedor"
+msgid "Verdict"
+msgstr "Resultado"
+
msgid "Verification Error"
msgstr "Erro de Verificação"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index f1abf487b1..cf096bc426 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -48,6 +48,18 @@ msgstr "«{taskName}» готово — все {0} позиций графика
msgid "(excluded for this customer)"
msgstr "(исключено для этого покупателя)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# день страхового запаса} few {# дня страхового запаса} many {# дней страхового запаса} other {# дней страхового запаса}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# день недостатка} few {# дня недостатка} many {# дней недостатка} other {# дней недостатка}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# операция не имеет временных нормативов} few {# операции не имеют временных нормативов} many {# операций не имеют временных нормативов} other {# операций не имеют временных нормативов}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# строка связана с данными вне этой организации, поэтому резервная копия ваших текущих данных не может быть создана.} other {# строк связаны с данными вне этой организации, поэтому резервная копия ваших текущих данных не может быть создана.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} производственных заказов обн
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "Файл {uploadedFileName} загружен — поля заполнены из документа."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# день} few {# дня} many {# дней} other {# дней}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# строка отличается от ожидаемого количества} other {# строк отличаются от ожидаемого количества}}"
@@ -2545,6 +2560,9 @@ msgstr "Вы уверены, что хотите аннулировать эту
msgid "Are you sure?"
msgstr "Вы уверены?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Как будто прыгнула в начало цеховой очереди"
+
msgid "As needed"
msgstr "По мере необходимости"
@@ -2668,6 +2686,9 @@ msgstr "Назначает данную единицу хранения рабо
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Назначает данную единицу рабочему центру для прилинейного запаса материала, чтобы операторы видели его в представлении производства; наследуется от родительской единицы, если установлено там."
+msgid "Assumptions"
+msgstr "Предположения"
+
msgid "At each gate"
msgstr "На каждом этапе"
@@ -2994,6 +3015,9 @@ msgstr "Прогноз лучшего случая"
msgid "Best case…"
msgstr "Лучший случай…"
+msgid "Best-case finish"
+msgstr "Оптимальное завершение"
+
msgid "Beta"
msgstr "Бета"
@@ -3091,6 +3115,9 @@ msgstr "Дата блокировки книг (вручную)"
msgid "Both"
msgstr "Оба"
+msgid "Both finishes compared against a date you choose."
+msgstr "Оба варианта завершения сравниваются с выбранной вами датой"
+
msgid "Bottleneck"
msgstr "Узкое место"
@@ -4473,6 +4500,9 @@ msgstr "Не удалось создать PDF. Попробуйте еще ра
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Не удалось растворить {0}: {1} — производство уже записано"
+msgid "Could not predict lead time"
+msgstr "Не удалось предсказать срок поставки"
+
msgid "Could not prepare region image for analysis"
msgstr "Не удалось подготовить изображение региона для анализа"
@@ -6807,6 +6837,9 @@ msgstr "Конец последнего месяца"
msgid "End of Last Quarter"
msgstr "Конец последнего квартала"
+msgid "End of queue"
+msgstr "Конец очереди"
+
msgid "End Time"
msgstr "Время окончания"
@@ -7626,6 +7659,9 @@ msgstr "Ошибка обновления подсчета"
msgid "Failed to update item cost"
msgstr "Не удалось обновить себестоимость номенклатуры"
+msgid "Failed to update lead times"
+msgstr "Не удалось обновить сроки поставки"
+
msgid "Failed to update opportunity with purchase order"
msgstr "Не удалось обновить сделку заказом поставщику"
@@ -8616,6 +8652,9 @@ msgstr "Если это блокирует или есть риск по дат
msgid "If items already exist"
msgstr "Если элементы уже существуют"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Если заказано сегодня — будет размещено позади уже запущенного"
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Если заказано, дефицит не прогнозируется в течение следующих 48 недель"
@@ -10641,6 +10680,9 @@ msgstr "Необходимо - это рабочие часы, приходящ
msgid "Needs a Business or Partner plan."
msgstr "Требуется план Business или Partner."
+msgid "Needs expedite"
+msgstr "Требует ускорения"
+
msgid "Needs fixing"
msgstr "Требуется исправление"
@@ -11618,6 +11660,9 @@ msgstr "Не настроено"
msgid "Not enough jobs to cover quantity"
msgstr "Недостаточно производственных заказов для покрытия количества"
+msgid "Not feasible"
+msgstr "Невозможно выполнить"
+
msgid "Not reached"
msgstr "Не достигнуто"
@@ -11803,6 +11848,9 @@ msgstr "На единице хранения"
msgid "On this operation"
msgstr "На эту операцию"
+msgid "On time"
+msgstr "Вовремя"
+
msgid "On-account credit available"
msgstr "Доступный кредит на счете"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} — это сколько {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Одно выполнение рабочего процесса, записанное пошагово со значениями, использованными и созданными каждым шагом, выполняющееся с правами доступа владельца рабочего процесса."
+msgid "One or more quantities cannot meet this date"
+msgstr "Одно или несколько количеств не могут соответствовать этой дате"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Одна серийная единица или одна серия, которую Carbon отслеживает отдельно, со своим статусом и атрибутами, такими как срок годности."
@@ -12646,6 +12697,9 @@ msgstr "Сначала выберите свойство"
msgid "Pick a record type…"
msgstr "Выберите тип записи…"
+msgid "Pick a target date to compare."
+msgstr "Выберите целевую дату для сравнения."
+
msgid "Pick a value from an earlier step"
msgstr "Выберите значение из предыдущего шага"
@@ -12906,6 +12960,12 @@ msgstr "Потенциальная потеря данных"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Предзаполнено для новой номенклатуры, если срок годности установлен на фиксированную продолжительность."
+msgid "Predict lead time"
+msgstr "Предсказать срок поставки"
+
+msgid "Predicting lead time…"
+msgstr "Прогнозирование сроков поставки…"
+
msgid "Preferred Supplier"
msgstr "Основной поставщик"
@@ -13585,6 +13645,9 @@ msgstr "Вопрос"
msgid "Queued"
msgstr "В очереди"
+msgid "Queued finish"
+msgstr "Завершение в очереди"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Тихо на цехе сегодня ночью, {name}."
@@ -15069,6 +15132,9 @@ msgstr "График пересчитан"
msgid "Scheduled"
msgstr "Запланировано"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Запланировано с учетом текущей нагрузки вашего цеха. Ничего не сохраняется до применения."
+
msgid "Scheduled Maintenance"
msgstr "Запланированное техобслуживание"
@@ -16866,6 +16932,9 @@ msgstr "Целевая организация"
msgid "Target customers by type."
msgstr "Выберите покупателей по типу."
+msgid "Target date"
+msgstr "Целевая дата"
+
msgid "Target disposition row"
msgstr "Целевая строка решения"
@@ -18007,6 +18076,9 @@ msgstr "Этот производственный заказ больше не
msgid "This job's own required quantity for the material."
msgstr "Собственное требуемое количество материала для этого задания."
+msgid "This line has no routing to schedule."
+msgstr "На этой строке нет маршрута для планирования."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Эта площадка планирует только укомплектованные рабочие центры, но эта станция работает без персонала (24×7) — она исключена и продолжает работать без присмотра."
@@ -19164,6 +19236,9 @@ msgstr "ИНН"
msgid "Vendor Write-Off Income"
msgstr "Доход от списания задолженности перед поставщиком"
+msgid "Verdict"
+msgstr "Вывод"
+
msgid "Verification Error"
msgstr "Ошибка проверки"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index a5f23b2c8c..602a664d1b 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\" bitti — tüm {0} Kurulum Haritası öğesi yapılandır
msgid "(excluded for this customer)"
msgstr "(bu müşteri için hariç tutulmuş)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# gün esneklik payı} other {# gün esneklik payı}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {# gün gecikme} other {# gün gecikme}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# operasyon için zaman standardı yok} other {# operasyon için zaman standardı yok}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# satır bu şirketin dışındaki verilere bağlantı kuruyor, bu nedenle mevcut verilerinizin güvenli bir kopyası oluşturulamıyor.} other {# satır bu şirketin dışındaki verilere bağlantı kuruyor, bu nedenle mevcut verilerinizin güvenli bir kopyası oluşturulamıyor.}}"
@@ -399,6 +411,9 @@ msgstr "{updatedJobCount} İş emirleri güncellendi"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "{uploadedFileName} yüklendi — alanlar belgeden dolduruldu."
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# gün} other {# gün}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {# satır beklenen miktardan farklıdır} other {# satır beklenen miktardan farklıdır}}"
@@ -2545,6 +2560,9 @@ msgstr "Bu sevkiyatı hükümsüz kılmak istediğinizden emin misiniz? Bu işle
msgid "Are you sure?"
msgstr "Emin misiniz?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "Sanki atölyenin kuyruğunun başına geçmiş gibi."
+
msgid "As needed"
msgstr "Gerektiğinde"
@@ -2668,6 +2686,9 @@ msgstr "Bu depolama birimini bir iş merkezine atar (hat yanı)"
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "Bu birimi hat yanı malzemesi için bir iş merkezine atar; böylece operatörler bunu üretim görünümünde görürler; orada ayarlandığında ana birimden devralınır."
+msgid "Assumptions"
+msgstr "Varsayımlar"
+
msgid "At each gate"
msgstr "Her kapıda"
@@ -2994,6 +3015,9 @@ msgstr "En iyi durum projeksiyonu"
msgid "Best case…"
msgstr "En iyi durum…"
+msgid "Best-case finish"
+msgstr "En iyi ihtimalde bitiş"
+
msgid "Beta"
msgstr "Beta"
@@ -3091,6 +3115,9 @@ msgstr "Defterlerin kilitlenme tarihi (manuel)"
msgid "Both"
msgstr "Her ikisi"
+msgid "Both finishes compared against a date you choose."
+msgstr "Her iki bitişin seçtiğiniz tarihle karşılaştırılması."
+
msgid "Bottleneck"
msgstr "Darboğaz"
@@ -4473,6 +4500,9 @@ msgstr "PDF oluşturulamadı. Lütfen tekrar deneyin."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0} çözülemedi: {1} — üretim zaten kaydedildi"
+msgid "Could not predict lead time"
+msgstr "Tedarik süresi tahmin edilemedi"
+
msgid "Could not prepare region image for analysis"
msgstr "Bölge görüntüsü analiz için hazırlanamadı"
@@ -6807,6 +6837,9 @@ msgstr "Geçen Ayın Sonu"
msgid "End of Last Quarter"
msgstr "Son Çeyreğin Sonu"
+msgid "End of queue"
+msgstr "Kuyruğun sonu"
+
msgid "End Time"
msgstr "Bitiş Saati"
@@ -7626,6 +7659,9 @@ msgstr "Sayı güncelleme başarısız"
msgid "Failed to update item cost"
msgstr "Ürün maliyeti 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"
@@ -8616,6 +8652,9 @@ msgstr "Eğer engel oluşturuyorsa veya bir tarih risk altındaysa, bir sahibi a
msgid "If items already exist"
msgstr "Eğer öğeler zaten varsa"
+msgid "If ordered today — placed behind everything already released."
+msgstr "Bugün sipariş edilirse — zaten serbest bırakılmış tüm işlerin arkasına alınır."
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "Sipariş edildiyse, sonraki 48 haftada stoksuzluk projeksiyonu yoktur"
@@ -10641,6 +10680,9 @@ msgstr "Gerekli olan, o gün vadesi gelen iş saatleri {personDayHours}s'ye böl
msgid "Needs a Business or Partner plan."
msgstr "Business veya Partner planı gereklidir."
+msgid "Needs expedite"
+msgstr "Hızlandırılması gerekli"
+
msgid "Needs fixing"
msgstr "Onarılması gerekir"
@@ -11618,6 +11660,9 @@ msgstr "Yapılandırılmadı"
msgid "Not enough jobs to cover quantity"
msgstr "Miktarı karşılamak için yeterli İş emri yok"
+msgid "Not feasible"
+msgstr "Gerçekleştirilemez"
+
msgid "Not reached"
msgstr "Ulaşılmadı"
@@ -11803,6 +11848,9 @@ msgstr "Depolama biriminde"
msgid "On this operation"
msgstr "Bu operasyonda"
+msgid "On time"
+msgstr "Zamanında"
+
msgid "On-account credit available"
msgstr "Hesap kredisi kullanılabilir"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} kaç {1} eder?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "Bir iş akışının bir kez çalıştırılması, her adımın kullandığı ve ürettiği değerlerle adım adım kaydedilmiş, iş akışının sahibinin izinleriyle hareket eder."
+msgid "One or more quantities cannot meet this date"
+msgstr "Bir veya daha fazla miktar bu tarihi karşılayamıyor"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Carbon tarafından bireysel takip edilen bir seri adet veya bir parti, son kullanma tarihi gibi kendi durumu ve öznitelikleri taşıyan."
@@ -12646,6 +12697,9 @@ msgstr "Önce bir özellik seçin"
msgid "Pick a record type…"
msgstr "Bir kayıt türü seçin…"
+msgid "Pick a target date to compare."
+msgstr "Karşılaştırma için hedef bir tarih seçin."
+
msgid "Pick a value from an earlier step"
msgstr "Önceki bir adımdan bir değer seçin"
@@ -12906,6 +12960,12 @@ msgstr "Potansiyel Veri Kaybı"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "Son kullanma tarihi Sabit Süre olduğunda yeni bir ürün için önceden doldurulur."
+msgid "Predict lead time"
+msgstr "Tedarik süresini tahmin et"
+
+msgid "Predicting lead time…"
+msgstr "Tedarik süresi tahmin ediliyor…"
+
msgid "Preferred Supplier"
msgstr "Tercih Edilen Tedarikçi"
@@ -13585,6 +13645,9 @@ msgstr "Soru"
msgid "Queued"
msgstr "Kuyrukta"
+msgid "Queued finish"
+msgstr "Kuyrukta bitiş"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "Atölyede bu gece sessiz, {name}."
@@ -15069,6 +15132,9 @@ msgstr "Çizelge yeniden oluşturuldu"
msgid "Scheduled"
msgstr "Zamanlandı"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "Atölyenizin mevcut iş yüküne göre planlandı. Uygulayıncaya kadar hiçbir şey kaydedilmez."
+
msgid "Scheduled Maintenance"
msgstr "Planlanmış Bakım"
@@ -16866,6 +16932,9 @@ msgstr "Hedef Şirket"
msgid "Target customers by type."
msgstr "Müşterileri türlerine göre hedefleyin."
+msgid "Target date"
+msgstr "Hedef tarih"
+
msgid "Target disposition row"
msgstr "Hedef karar satırı"
@@ -18007,6 +18076,9 @@ msgstr "Bu iş emri atölye'de artık kullanılamayacaktır."
msgid "This job's own required quantity for the material."
msgstr "Bu işin malzeme için kendi gerekli miktarı."
+msgid "This line has no routing to schedule."
+msgstr "Bu satırın zamanlama için bir rotası yok."
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "Bu lokasyon yalnızca personel atanmış iş merkezlerini çizelgelendirir, ancak bu otomatik (24×7) istasyondur — muaf tutulur ve gözetimsiz çalışmaya devam eder."
@@ -19164,6 +19236,9 @@ msgstr "Vergi numarası"
msgid "Vendor Write-Off Income"
msgstr "Tedarikçi Kayıttan Düşme Geliri"
+msgid "Verdict"
+msgstr "Sonuç"
+
msgid "Verification Error"
msgstr "Doğrulama Hatası"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 338bfc0c32..1f22a0d6ad 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -48,6 +48,18 @@ msgstr "\"{taskName}\"已完成——其所有{0}个设置映射项都已配置
msgid "(excluded for this customer)"
msgstr "(已为此客户排除)"
+#. placeholder {0}: target.slackDays
+msgid "{0, plural, one {# day of slack} other {# days of slack}}"
+msgstr "{0, plural, one {# 天的松弛} other {# 天的松弛}}"
+
+#. placeholder {0}: -target.slackDays
+msgid "{0, plural, one {# day short} other {# days short}}"
+msgstr "{0, plural, one {缺# 天} other {缺# 天}}"
+
+#. placeholder {0}: forecast.zeroStandardOperationCount
+msgid "{0, plural, one {# operation has no time standards} other {# operations have no time standards}}"
+msgstr "{0, plural, one {# 道工序无工时定额} other {# 道工序无工时定额}}"
+
#. placeholder {0}: totalScopeRows(run.violationRowsByTable)
msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"
msgstr "{0, plural, one {# 行链接到该公司外的数据,无法制作当前数据的安全副本。} other {# 行链接到该公司外的数据,无法制作当前数据的安全副本。}}"
@@ -399,6 +411,9 @@ msgstr "已更新{updatedJobCount}个工单"
msgid "{uploadedFileName} uploaded — fields filled from the document."
msgstr "已上传{uploadedFileName}——字段从文件填充。"
+msgid "{value, plural, one {# day} other {# days}}"
+msgstr "{value, plural, one {# 天} other {# 天}}"
+
msgid "{variances, plural, one {# line differs from the expected quantity} other {# lines differ from the expected quantity}}"
msgstr "{variances, plural, one {#行与预期数量不同} other {#行与预期数量不同}}"
@@ -2545,6 +2560,9 @@ msgstr "您确定要作废此发货吗?此操作将反转所有库存交易,
msgid "Are you sure?"
msgstr "你确定吗?"
+msgid "As if it jumped to the front of the shop's queue."
+msgstr "就像它跳到了车间队列的最前面。"
+
msgid "As needed"
msgstr "按需"
@@ -2668,6 +2686,9 @@ msgstr "将此存储单元分配给工作中心(线边)"
msgid "Assigns this unit to a work center for lineside material, so operators see it on the production view; inherited from the parent unit when set there."
msgstr "将此库位分配给工作中心以进行线边物料管理,使操作员能在生产视图上看到;从父库位继承该设置。"
+msgid "Assumptions"
+msgstr "假设"
+
msgid "At each gate"
msgstr "在每个关卡"
@@ -2994,6 +3015,9 @@ msgstr "最佳情况预测"
msgid "Best case…"
msgstr "最佳情况…"
+msgid "Best-case finish"
+msgstr "最佳情况完成日期"
+
msgid "Beta"
msgstr "测试版"
@@ -3091,6 +3115,9 @@ msgstr "账册锁定日期(手动)"
msgid "Both"
msgstr "两者"
+msgid "Both finishes compared against a date you choose."
+msgstr "将两个交期与您选择的日期进行对比。"
+
msgid "Bottleneck"
msgstr "瓶颈"
@@ -4473,6 +4500,9 @@ msgstr "无法生成 PDF。请重试。"
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "无法解散 {0}: {1} — 生产已记录"
+msgid "Could not predict lead time"
+msgstr "无法预测提前期"
+
msgid "Could not prepare region image for analysis"
msgstr "无法准备区域图像以进行分析"
@@ -6807,6 +6837,9 @@ msgstr "上月末"
msgid "End of Last Quarter"
msgstr "上一季度末"
+msgid "End of queue"
+msgstr "队列末尾"
+
msgid "End Time"
msgstr "结束时间"
@@ -7626,6 +7659,9 @@ msgstr "更新计数失败"
msgid "Failed to update item cost"
msgstr "更新项目成本失败"
+msgid "Failed to update lead times"
+msgstr "无法更新提前期"
+
msgid "Failed to update opportunity with purchase order"
msgstr "未能使用采购订单更新商机"
@@ -8616,6 +8652,9 @@ msgstr "如果它正在阻塞或日期处于风险中,它会获得一个负责
msgid "If items already exist"
msgstr "如果物料已经存在"
+msgid "If ordered today — placed behind everything already released."
+msgstr "如果今日订购——将排在所有已下达工作之后。"
+
msgid "If ordered, no stockout projected in the next 48 weeks"
msgstr "如果已订购,未来48周内无缺货预测"
@@ -10641,6 +10680,9 @@ msgstr "需要的是该天的工作小时数除以 {personDayHours} 小时,向
msgid "Needs a Business or Partner plan."
msgstr "需要业务或合作伙伴计划。"
+msgid "Needs expedite"
+msgstr "需要加急"
+
msgid "Needs fixing"
msgstr "需要修复"
@@ -11618,6 +11660,9 @@ msgstr "未配置"
msgid "Not enough jobs to cover quantity"
msgstr "工单数量不足以覆盖所需数量"
+msgid "Not feasible"
+msgstr "不可行"
+
msgid "Not reached"
msgstr "未到达"
@@ -11803,6 +11848,9 @@ msgstr "在存储单元上"
msgid "On this operation"
msgstr "在此工序上"
+msgid "On time"
+msgstr "准时"
+
msgid "On-account credit available"
msgstr "可用账户贷方"
@@ -11838,6 +11886,9 @@ msgstr "1 {0} 等于多少 {1}?"
msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."
msgstr "一次工作流执行,逐步记录每个步骤使用和产生的值,始终以工作流负责人的权限行动。"
+msgid "One or more quantities cannot meet this date"
+msgstr "一个或多个数量无法满足此日期"
+
msgid "One serial unit or one batch that Carbon follows individually, carrying its own status and attributes such as an expiry date."
msgstr "Carbon单独跟踪的一个编号件或一个生产批次,具有自己的状态和属性,例如有效期。"
@@ -12646,6 +12697,9 @@ msgstr "先选择属性"
msgid "Pick a record type…"
msgstr "选择记录类型…"
+msgid "Pick a target date to compare."
+msgstr "选择一个目标日期进行比较。"
+
msgid "Pick a value from an earlier step"
msgstr "从早期步骤选择一个值"
@@ -12906,6 +12960,12 @@ msgstr "潜在数据丢失"
msgid "Pre-filled for a new item when expiry is Fixed Duration."
msgstr "当有效期为固定期间时,为新物料预填充。"
+msgid "Predict lead time"
+msgstr "预测提前期"
+
+msgid "Predicting lead time…"
+msgstr "正在预测提前期…"
+
msgid "Preferred Supplier"
msgstr "首选供应商"
@@ -13585,6 +13645,9 @@ msgstr "问题"
msgid "Queued"
msgstr "排队中"
+msgid "Queued finish"
+msgstr "排队完成日期"
+
msgid "Quiet on the floor tonight, {name}."
msgstr "今晚车间很安静,{name}。"
@@ -15069,6 +15132,9 @@ msgstr "排程已重新生成"
msgid "Scheduled"
msgstr "已计划"
+msgid "Scheduled against your shop's current workload. Nothing is saved until you apply."
+msgstr "根据您车间当前工作负荷进行排程。在您应用前,不会保存任何内容。"
+
msgid "Scheduled Maintenance"
msgstr "定期维护"
@@ -16866,6 +16932,9 @@ msgstr "目标公司"
msgid "Target customers by type."
msgstr "按类型定位客户。"
+msgid "Target date"
+msgstr "目标日期"
+
msgid "Target disposition row"
msgstr "目标处置行"
@@ -18007,6 +18076,9 @@ msgstr "此工作将不再在车间可用。"
msgid "This job's own required quantity for the material."
msgstr "这个工单所需的原材料数量。"
+msgid "This line has no routing to schedule."
+msgstr "此行没有要排程的工艺路线。"
+
msgid "This location only schedules staffed work centers, but this is a lights-out (24×7) station — it is exempt and keeps running unattended."
msgstr "此地点仅排程有人值守的工作中心,但这是一个无人值守工作站(24×7)— 它被豁免并保持无人运行。"
@@ -19164,6 +19236,9 @@ msgstr "增值税号"
msgid "Vendor Write-Off Income"
msgstr "供应商核销收益"
+msgid "Verdict"
+msgstr "结果"
+
msgid "Verification Error"
msgstr "验证错误"
diff --git a/packages/planning/AGENTS.md b/packages/planning/AGENTS.md
index 88501ebb3b..bf51c6e52e 100644
--- a/packages/planning/AGENTS.md
+++ b/packages/planning/AGENTS.md
@@ -40,6 +40,7 @@ Single subpath `@carbon/planning` (`./src/index.ts`):
|--------|----------|
| `runMrp(client, db, payload)` | Material Requirements Planning (`src/mrp/mrp.ts`; formerly the `mrp` edge function) |
| `runLocationSchedule` / `runExpediteWhatIf` | Finite scheduling — regenerate a whole location, or a simulate-only expedite what-if (`src/scheduling/run-schedule.ts`) |
+| `runQuoteLeadTimeWhatIf(params)` | Capable-to-promise for a quote line — drives the pure `WorkCenterSelector` with synthetic ops (queued vs front-of-queue contexts) per quantity, returns `QuoteLeadTimeForecast`; persists nothing (`src/scheduling/quote-lead-time.ts`) |
| `resolveLocationWindows` / `resolveWorkCenterWindows` / `subtractIntervals` | Machine/work-center availability window resolvers (`src/scheduling/`) |
| types (`LadderShiftRow`, `MrpPayload`, `MrpResult`, `LocationScheduleResult`, `ExpediteWhatIfResult`, `NewlyLateJob`, …) | Engine type surface |
diff --git a/packages/planning/src/index.ts b/packages/planning/src/index.ts
index 3922031bee..5c9711b28f 100644
--- a/packages/planning/src/index.ts
+++ b/packages/planning/src/index.ts
@@ -18,6 +18,11 @@ export {
resolveWorkCenterWindows,
type WorkCenterAvailabilityInput
} from "./scheduling/machine-availability.ts";
+export {
+ type QuoteLeadTimeForecast,
+ type QuoteLeadTimeScenario,
+ runQuoteLeadTimeWhatIf
+} from "./scheduling/quote-lead-time.ts";
export {
type ExpediteWhatIfResult,
type LocationScheduleResult,
diff --git a/packages/planning/src/scheduling/determinism.test.ts b/packages/planning/src/scheduling/determinism.test.ts
index 83e0a39931..1e9219c404 100644
--- a/packages/planning/src/scheduling/determinism.test.ts
+++ b/packages/planning/src/scheduling/determinism.test.ts
@@ -5,7 +5,7 @@ import {
parseDate,
toCalendarDate
} from "@internationalized/date";
-import { it } from "vitest";
+import { it, vi } from "vitest";
/**
* Determinism proof for the finite placement engine.
@@ -58,6 +58,11 @@ import {
WorkCenterSelector
} from "./work-center-selector.ts";
+// Each test runs the full ~120-operation placement two or more times: ~100ms
+// on a workstation, but 2-6s under CI's parallel turbo test run, which
+// overruns vitest's 5s default without anything being wrong.
+vi.setConfig({ testTimeout: 30_000 });
+
const utc = (iso: string) => parseAbsolute(iso, "UTC").toDate().getTime();
const iso = (ms: number) => fromAbsolute(ms, "UTC").toAbsoluteString();
diff --git a/packages/planning/src/scheduling/finite-context.ts b/packages/planning/src/scheduling/finite-context.ts
new file mode 100644
index 0000000000..9b82cef317
--- /dev/null
+++ b/packages/planning/src/scheduling/finite-context.ts
@@ -0,0 +1,328 @@
+import {
+ type CalendarShiftRow,
+ type CalendarWindow,
+ expandCalendar,
+ unionWindows
+} from "./calendar-utils.ts";
+import type { MasterDataProvider } from "./master-data-provider.ts";
+import {
+ buildAbsencesByEmployee,
+ buildAssignmentsByEmployee,
+ buildOvertimeByEmployee,
+ buildPeopleBudgets,
+ buildPeopleByWorkCenter,
+ extendWindowsByOvertime,
+ subtractAbsences
+} from "./people-utils.ts";
+import type { ResourceCapacityData } from "./slot-allocator.ts";
+import type { JobOperationDependency, ScheduledOperation } from "./types.ts";
+import type {
+ FiniteSchedulingContext,
+ PoolEmployee,
+ WorkCenterSelector
+} from "./work-center-selector.ts";
+
+export const SCHEDULING_HORIZON_DAYS = 365;
+
+export type AvailabilityWindows = {
+ workCenterIds: Set<string>;
+ workCenterAvailability: Map<string, CalendarWindow[]>;
+ locationDefaultWindows: CalendarWindow[];
+ rangeStart: number;
+ rangeEnd: number;
+};
+
+/**
+ * The ONE availability-windows fetch for a scheduling run — work-center windows
+ * (selection candidates + current assignments) plus the location's default
+ * calendar. The caller (the engine, the quote what-if) memoizes it so the
+ * backward need-by pass and buildFiniteContext share the same load instead of
+ * reading the provider twice.
+ */
+export async function loadAvailabilityWindows(args: {
+ provider: MasterDataProvider;
+ workCenterSelector: WorkCenterSelector | null;
+ operations: ScheduledOperation[];
+ locationId: string | null;
+ now: number;
+}): Promise<AvailabilityWindows> {
+ const { provider, workCenterSelector, operations, locationId, now } = args;
+
+ const processIds = Array.from(
+ new Set(operations.map((op) => op.processId).filter(Boolean))
+ ) as string[];
+
+ // Candidates for selection + current assignments (assigned work centers
+ // stay in play via the sticky/fallback rules).
+ const workCenterIds = new Set(
+ workCenterSelector?.getAllCandidateWorkCenterIds(processIds) ?? []
+ );
+ for (const op of operations) {
+ if (op.workCenterId) {
+ workCenterIds.add(op.workCenterId);
+ }
+ }
+
+ const rangeStart = now;
+ const rangeEnd = now + (SCHEDULING_HORIZON_DAYS + 7) * 24 * 3_600_000;
+
+ const [workCenterAvailability, locationDefaultWindows] = await Promise.all([
+ provider.getWorkCenterAvailability(
+ [...workCenterIds],
+ rangeStart,
+ rangeEnd
+ ),
+ // People with no employeeShift rows default to the job location's calendar
+ // (plant hours), not 24×7 — matching the default machine window so
+ // unconfigured labor is non-constraining within plant hours.
+ locationId
+ ? provider.getLocationCalendarWindows(locationId, rangeStart, rangeEnd)
+ : Promise.resolve<CalendarWindow[]>([
+ { start: rangeStart, end: rangeEnd }
+ ]) // rangeStart/rangeEnd are epoch-ms
+ ]);
+
+ return {
+ workCenterIds,
+ workCenterAvailability,
+ locationDefaultWindows,
+ rangeStart,
+ rangeEnd
+ };
+}
+
+/**
+ * Build the finite-capacity context: live reservations, per-process ability
+ * requirements, and qualified-operator availability. Work centers are
+ * finite (capacity 1 — one operation at a time, gated by actual
+ * reservations); ability-gated operations additionally wait for a
+ * qualified person to be on shift and unreserved. Runs just before
+ * selection so the rebuilt dependency DAG is final.
+ */
+export async function buildFiniteContext(args: {
+ provider: MasterDataProvider;
+ operations: ScheduledOperation[];
+ dependencies: JobOperationDependency[];
+ availability: AvailabilityWindows;
+ locationId: string | null;
+ timeZone: string;
+ now: number;
+ excludeJobIds: string[];
+}): Promise<FiniteSchedulingContext> {
+ const {
+ provider,
+ operations,
+ dependencies,
+ availability,
+ locationId,
+ timeZone,
+ now,
+ excludeJobIds
+ } = args;
+
+ const processIds = Array.from(
+ new Set(operations.map((op) => op.processId).filter(Boolean))
+ ) as string[];
+
+ // One shared windows fetch per run (also used by the need-by pass).
+ const {
+ workCenterIds,
+ workCenterAvailability,
+ locationDefaultWindows,
+ rangeStart,
+ rangeEnd
+ } = availability;
+
+ const operationIds = operations
+ .map((op) => op.id)
+ .filter((id): id is string => Boolean(id));
+
+ const [
+ liveReservations,
+ processRequirements,
+ peopleRows,
+ absenceRows,
+ operationsWithEvents
+ ] = await Promise.all([
+ provider.getLiveReservations(now, excludeJobIds),
+ provider.getProcessRequirements(processIds),
+ provider.getPeopleAssignments(rangeStart, rangeEnd, timeZone),
+ provider.getPeopleAbsences(rangeStart, rangeEnd, timeZone),
+ provider.getOperationsWithEvents(operationIds)
+ ]);
+
+ const abilityIds = Array.from(
+ new Set(processRequirements.map((r) => r.abilityId))
+ );
+ const employees = await provider.getQualifiedEmployees(abilityIds);
+ // People members at ungated stations need real availability windows too, so
+ // shift rows are loaded for the union of qualified + assigned people
+ const employeeIds = Array.from(
+ new Set([
+ ...employees.map((e) => e.employeeId),
+ ...peopleRows.map((r) => r.employeeId)
+ ])
+ );
+ const shiftRows = await provider.getEmployeeShiftWindows(employeeIds);
+
+ // Work centers: capacity 1, open per the availability ladder (explicit
+ // workCenterShift rows → location shifts → stock Mon–Fri 8h, or one open
+ // window for an alwaysOn machine). Reservations GATE placement (one op at a
+ // time) and feed attribution. A WC with no resolved windows (e.g. deleted)
+ // schedules nothing and surfaces a conflict.
+ // Require-staffing policy (per-location) + which stations are lights-out —
+ // both feed the selector's fallback gates. One cached read each per batch.
+ const [requiresStaffing, alwaysOnWorkCenterIds] = await Promise.all([
+ locationId
+ ? provider.getLocationRequiresStaffing(locationId)
+ : Promise.resolve(false),
+ provider.getAlwaysOnWorkCenterIds(Array.from(workCenterIds))
+ ]);
+
+ const capacityByWorkCenter = new Map<string, ResourceCapacityData>();
+ for (const wcId of workCenterIds) {
+ capacityByWorkCenter.set(wcId, {
+ workCenter: { id: wcId, alwaysOn: alwaysOnWorkCenterIds.has(wcId) },
+ windows: workCenterAvailability.get(wcId) ?? [],
+ reservations: liveReservations
+ .filter((r) => r.resourceKind === "WorkCenter" && r.resourceId === wcId)
+ .map((r) => ({
+ startAt: r.startAt,
+ endAt: r.endAt,
+ readableJobId: r.readableJobId
+ }))
+ });
+ }
+
+ const requirementByProcess = new Map(
+ processRequirements.map((r) => [
+ r.processId,
+ { abilityId: r.abilityId, abilityName: r.abilityName }
+ ])
+ );
+
+ // Each qualified person's availability = their assigned shifts expanded
+ // over the horizon (grouped by timezone, unioned). No shift assignment
+ // => always available.
+ const shiftPatternsByEmployee = new Map<
+ string,
+ Map<string, CalendarShiftRow[]>
+ >();
+ for (const row of shiftRows) {
+ let byTz = shiftPatternsByEmployee.get(row.employeeId);
+ if (!byTz) {
+ byTz = new Map();
+ shiftPatternsByEmployee.set(row.employeeId, byTz);
+ }
+ const list = byTz.get(row.timezone) ?? [];
+ list.push({
+ dayOfWeek: row.dayOfWeek,
+ startTime: row.startTime,
+ endTime: row.endTime
+ });
+ byTz.set(row.timezone, list);
+ }
+ const windowsByEmployee = new Map<string, CalendarWindow[]>();
+ for (const [employeeId, byTz] of shiftPatternsByEmployee) {
+ const lists = Array.from(byTz.entries()).map(([tz, shifts]) =>
+ expandCalendar(shifts, rangeStart, rangeEnd, tz)
+ );
+ windowsByEmployee.set(employeeId, unionWindows(lists));
+ }
+
+ // People with no shift assignment default to the job location's calendar
+ // (plant hours, matching the default machine window) — not 24×7 — so
+ // unconfigured labor degrades to non-constraining within plant hours.
+ // Materialized here so absences/overtime can adjust it too.
+ for (const employeeId of employeeIds) {
+ if (!windowsByEmployee.has(employeeId)) {
+ windowsByEmployee.set(employeeId, locationDefaultWindows);
+ }
+ }
+
+ // Absences subtract the person's availability on those dates everywhere —
+ // people-preferred and qualified-fallback paths alike
+ const absentByEmployee = buildAbsencesByEmployee(absenceRows);
+ for (const [employeeId, absentDates] of absentByEmployee) {
+ const windows = windowsByEmployee.get(employeeId);
+ if (windows) {
+ windowsByEmployee.set(
+ employeeId,
+ subtractAbsences(windows, absentDates, timeZone)
+ );
+ }
+ }
+
+ // An absent person is never that day's people
+ const presentPeopleRows = peopleRows.filter(
+ (row) => !absentByEmployee.get(row.employeeId)?.has(row.date)
+ );
+ const peopleByWorkCenter = buildPeopleByWorkCenter(presentPeopleRows);
+ // Inverted board (employee -> date -> stations) so the any-qualified
+ // fallback can tell a manned person is committed elsewhere that day.
+ const assignmentsByEmployee = buildAssignmentsByEmployee(peopleByWorkCenter);
+
+ // Authorized overtime = a longer day: extend the person's last window on
+ // each overtime date so the allocator can pack work into the extra hours
+ const overtimeByEmployee = buildOvertimeByEmployee(presentPeopleRows);
+ for (const [employeeId, overtimeByDate] of overtimeByEmployee) {
+ const windows = windowsByEmployee.get(employeeId);
+ if (windows) {
+ windowsByEmployee.set(
+ employeeId,
+ extendWindowsByOvertime(windows, overtimeByDate, timeZone)
+ );
+ }
+ }
+
+ // Split days: each station only gets its budgeted share of the person
+ const peopleBudgets = buildPeopleBudgets(presentPeopleRows);
+
+ const employeesByAbility = new Map<string, PoolEmployee[]>();
+ for (const e of employees) {
+ const list = employeesByAbility.get(e.abilityId) ?? [];
+ list.push({
+ employeeId: e.employeeId,
+ expiresAt: e.expiresAt,
+ windows: windowsByEmployee.get(e.employeeId) ?? locationDefaultWindows
+ });
+ employeesByAbility.set(e.abilityId, list);
+ }
+
+ // Named-person bookings across ALL abilities, keyed by employee id.
+ // Legacy OperatorPool rows are ignored deliberately: they can't be
+ // attributed to a person, and they stop existing after each job's next
+ // replan (the reactive stale-wave refreshes everything).
+ const reservationsByEmployee = new Map<
+ string,
+ { startAt: number; endAt: number; readableJobId?: string }[]
+ >();
+ for (const r of liveReservations) {
+ if (r.resourceKind !== "Employee") continue;
+ const list = reservationsByEmployee.get(r.resourceId) ?? [];
+ list.push({
+ startAt: r.startAt,
+ endAt: r.endAt,
+ readableJobId: r.readableJobId
+ });
+ reservationsByEmployee.set(r.resourceId, list);
+ }
+
+ return {
+ capacityByWorkCenter,
+ requirementByProcess,
+ employeesByAbility,
+ reservationsByEmployee,
+ peopleByWorkCenter,
+ assignmentsByEmployee,
+ requiresStaffing,
+ peopleBudgets,
+ windowsByEmployee,
+ dependencies,
+ now,
+ horizonDays: SCHEDULING_HORIZON_DAYS,
+ windowsEnd: rangeEnd,
+ timeZone,
+ operationsWithEvents
+ };
+}
diff --git a/packages/planning/src/scheduling/quote-lead-time.test.ts b/packages/planning/src/scheduling/quote-lead-time.test.ts
new file mode 100644
index 0000000000..45372f03f6
--- /dev/null
+++ b/packages/planning/src/scheduling/quote-lead-time.test.ts
@@ -0,0 +1,381 @@
+import { parseAbsolute } from "@internationalized/date";
+import { it } from "vitest";
+import {
+ buildQuoteSimulation,
+ calendarDaysFromNow,
+ cloneFiniteContext,
+ composeQuoteCause,
+ type MaterialAvailability,
+ type QuoteMakeMethodRow,
+ type QuoteMaterialRow,
+ type QuoteOperationRow,
+ type QuoteScenarioSignals
+} from "./quote-lead-time.ts";
+import { assert, assertEquals } from "./test-helpers.ts";
+import type { FiniteSchedulingContext } from "./work-center-selector.ts";
+
+const ms = (iso: string) => parseAbsolute(iso, "UTC").toDate().getTime();
+const DAY_MS = 24 * 3_600_000;
+
+function makeQuoteOp(
+ o: Partial<QuoteOperationRow> & {
+ id: string;
+ quoteMakeMethodId: string;
+ order: number;
+ }
+): QuoteOperationRow {
+ return {
+ processId: "proc-1",
+ workCenterId: null,
+ operationOrder: "After Previous",
+ operationType: null,
+ description: null,
+ setupTime: 1,
+ setupUnit: "Total Hours",
+ laborTime: 1,
+ laborUnit: "Total Hours",
+ machineTime: 0,
+ machineUnit: "Total Hours",
+ operationLeadTime: 0,
+ ...o
+ };
+}
+
+const emptyAvailability = (): MaterialAvailability => ({
+ leadTimeDaysByItem: new Map(),
+ onHandByItem: new Map()
+});
+
+it("a root method with two After Previous ops yields one edge and unscaled quantities", () => {
+ const makeMethods: QuoteMakeMethodRow[] = [
+ { id: "mm-root", parentMaterialId: null }
+ ];
+ const operations: QuoteOperationRow[] = [
+ makeQuoteOp({ id: "op-1", quoteMakeMethodId: "mm-root", order: 1 }),
+ makeQuoteOp({ id: "op-2", quoteMakeMethodId: "mm-root", order: 2 })
+ ];
+
+ const sim = buildQuoteSimulation({
+ quoteLineId: "ql1",
+ quantity: 5,
+ makeMethods,
+ materials: [],
+ operations,
+ availability: emptyAvailability(),
+ now: 0
+ });
+
+ assertEquals(sim.jobId, "quote:ql1:5");
+ assertEquals(sim.operations.length, 2);
+ for (const op of sim.operations) {
+ assertEquals(op.operationQuantity, 5);
+ }
+ assertEquals(sim.dependencies.length, 1);
+ assertEquals(sim.dependencies[0]?.operationId, "op-2");
+ assertEquals(sim.dependencies[0]?.dependsOnId, "op-1");
+});
+
+it("a sub-assembly scales child quantities and links to the consuming op", () => {
+ const makeMethods: QuoteMakeMethodRow[] = [
+ { id: "mm-root", parentMaterialId: null },
+ { id: "mm-child", parentMaterialId: "mat-sub" }
+ ];
+ const materials: QuoteMaterialRow[] = [
+ {
+ id: "mat-sub",
+ quoteMakeMethodId: "mm-root",
+ itemId: "item-sub",
+ itemReadableId: "SUB-1",
+ methodType: "Make to Order",
+ quantity: 2,
+ quoteOperationId: "op-root-2"
+ }
+ ];
+ const operations: QuoteOperationRow[] = [
+ makeQuoteOp({ id: "op-root-1", quoteMakeMethodId: "mm-root", order: 1 }),
+ makeQuoteOp({ id: "op-root-2", quoteMakeMethodId: "mm-root", order: 2 }),
+ makeQuoteOp({ id: "op-child-1", quoteMakeMethodId: "mm-child", order: 1 }),
+ makeQuoteOp({ id: "op-child-2", quoteMakeMethodId: "mm-child", order: 2 })
+ ];
+
+ const sim = buildQuoteSimulation({
+ quoteLineId: "ql1",
+ quantity: 5,
+ makeMethods,
+ materials,
+ operations,
+ availability: emptyAvailability(),
+ now: 0
+ });
+
+ const byId = new Map(sim.operations.map((op) => [op.id, op]));
+ assertEquals(byId.get("op-root-1")?.operationQuantity, 5);
+ assertEquals(byId.get("op-child-1")?.operationQuantity, 10);
+ assertEquals(byId.get("op-child-2")?.operationQuantity, 10);
+
+ // The consuming op (op-root-2) depends on the child's last op (op-child-2).
+ const assembly = sim.dependencies.find(
+ (d) => d.operationId === "op-root-2" && d.dependsOnId === "op-child-2"
+ );
+ assert(assembly);
+});
+
+it("a sub-assembly material with no consuming op links to the parent's first op", () => {
+ const makeMethods: QuoteMakeMethodRow[] = [
+ { id: "mm-root", parentMaterialId: null },
+ { id: "mm-child", parentMaterialId: "mat-sub" }
+ ];
+ const materials: QuoteMaterialRow[] = [
+ {
+ id: "mat-sub",
+ quoteMakeMethodId: "mm-root",
+ itemId: "item-sub",
+ itemReadableId: "SUB-1",
+ methodType: "Make to Order",
+ quantity: 1,
+ quoteOperationId: null
+ }
+ ];
+ const operations: QuoteOperationRow[] = [
+ makeQuoteOp({ id: "op-root-1", quoteMakeMethodId: "mm-root", order: 1 }),
+ makeQuoteOp({ id: "op-root-2", quoteMakeMethodId: "mm-root", order: 2 }),
+ makeQuoteOp({ id: "op-child-1", quoteMakeMethodId: "mm-child", order: 1 })
+ ];
+
+ const sim = buildQuoteSimulation({
+ quoteLineId: "ql1",
+ quantity: 1,
+ makeMethods,
+ materials,
+ operations,
+ availability: emptyAvailability(),
+ now: 0
+ });
+
+ const assembly = sim.dependencies.find(
+ (d) => d.operationId === "op-root-1" && d.dependsOnId === "op-child-1"
+ );
+ assert(assembly);
+});
+
+it("a Purchase to Order material floors its consuming op at now + lead time", () => {
+ const now = ms("2026-01-05T00:00:00.000Z");
+ const makeMethods: QuoteMakeMethodRow[] = [
+ { id: "mm-root", parentMaterialId: null }
+ ];
+ const materials: QuoteMaterialRow[] = [
+ {
+ id: "mat-p",
+ quoteMakeMethodId: "mm-root",
+ itemId: "item-p",
+ itemReadableId: "PUR-1",
+ methodType: "Purchase to Order",
+ quantity: 1,
+ quoteOperationId: "op-1"
+ }
+ ];
+ const operations: QuoteOperationRow[] = [
+ makeQuoteOp({ id: "op-1", quoteMakeMethodId: "mm-root", order: 1 })
+ ];
+
+ const sim = buildQuoteSimulation({
+ quoteLineId: "ql1",
+ quantity: 1,
+ makeMethods,
+ materials,
+ operations,
+ availability: {
+ leadTimeDaysByItem: new Map([["item-p", 10]]),
+ onHandByItem: new Map()
+ },
+ now
+ });
+
+ assertEquals(sim.materialReadyDays, 10);
+ assertEquals(sim.operations[0]?.materialReadyAt, now + 10 * DAY_MS);
+});
+
+it("a Pull from Inventory material floors only when on-hand is short", () => {
+ const now = ms("2026-01-05T00:00:00.000Z");
+ const makeMethods: QuoteMakeMethodRow[] = [
+ { id: "mm-root", parentMaterialId: null }
+ ];
+ const operations: QuoteOperationRow[] = [
+ makeQuoteOp({ id: "op-1", quoteMakeMethodId: "mm-root", order: 1 })
+ ];
+ const material: QuoteMaterialRow = {
+ id: "mat-s",
+ quoteMakeMethodId: "mm-root",
+ itemId: "item-s",
+ itemReadableId: "STK-1",
+ methodType: "Pull from Inventory",
+ quantity: 1,
+ quoteOperationId: "op-1"
+ };
+
+ // On-hand >= required (1) → no floor.
+ const stocked = buildQuoteSimulation({
+ quoteLineId: "ql1",
+ quantity: 1,
+ makeMethods,
+ materials: [material],
+ operations,
+ availability: {
+ leadTimeDaysByItem: new Map([["item-s", 3]]),
+ onHandByItem: new Map([["item-s", 5]])
+ },
+ now
+ });
+ assertEquals(stocked.materialReadyDays, 0);
+ assertEquals(stocked.operations[0]?.materialReadyAt, undefined);
+
+ // On-hand below required → floor at the item lead time.
+ const short = buildQuoteSimulation({
+ quoteLineId: "ql1",
+ quantity: 1,
+ makeMethods,
+ materials: [material],
+ operations,
+ availability: {
+ leadTimeDaysByItem: new Map([["item-s", 3]]),
+ onHandByItem: new Map([["item-s", 0]])
+ },
+ now
+ });
+ assertEquals(short.materialReadyDays, 3);
+ assertEquals(short.operations[0]?.materialReadyAt, now + 3 * DAY_MS);
+});
+
+it("cloneFiniteContext isolates reservation arrays from the original", () => {
+ const baseCtx: FiniteSchedulingContext = {
+ capacityByWorkCenter: new Map([
+ [
+ "wc1",
+ {
+ workCenter: { id: "wc1" },
+ windows: [],
+ reservations: [{ startAt: 1, endAt: 2 }]
+ }
+ ]
+ ]),
+ requirementByProcess: new Map(),
+ employeesByAbility: new Map(),
+ reservationsByEmployee: new Map([["e1", [{ startAt: 1, endAt: 2 }]]]),
+ dependencies: [],
+ now: 0,
+ horizonDays: 365,
+ windowsEnd: 0,
+ peopleByWorkCenter: new Map(),
+ assignmentsByEmployee: new Map(),
+ requiresStaffing: false,
+ peopleBudgets: new Map(),
+ windowsByEmployee: new Map(),
+ timeZone: "UTC",
+ operationsWithEvents: new Set<string>()
+ };
+
+ const clone = cloneFiniteContext(baseCtx);
+ clone.capacityByWorkCenter.get("wc1")!.reservations.push({
+ startAt: 3,
+ endAt: 4
+ });
+ clone.reservationsByEmployee.get("e1")!.push({ startAt: 3, endAt: 4 });
+
+ assertEquals(baseCtx.capacityByWorkCenter.get("wc1")!.reservations.length, 1);
+ assertEquals(baseCtx.reservationsByEmployee.get("e1")!.length, 1);
+ assertEquals(clone.capacityByWorkCenter.get("wc1")!.reservations.length, 2);
+ assertEquals(clone.reservationsByEmployee.get("e1")!.length, 2);
+});
+
+it("calendarDaysFromNow counts local calendar days, minimum 1", () => {
+ const tz = "America/New_York";
+ // Same local day (both 2026-01-06 in NY, though the finish is the next UTC
+ // day) → 1. Proves the day count resolves in the location tz, not UTC.
+ const nowSame = ms("2026-01-06T13:00:00.000Z"); // 2026-01-06 08:00 NY
+ const finishSame = ms("2026-01-07T01:00:00.000Z"); // 2026-01-06 20:00 NY
+ assertEquals(calendarDaysFromNow(finishSame, nowSame, tz), 1);
+
+ // Two local days ahead → 2.
+ const finishTwo = ms("2026-01-08T13:00:00.000Z"); // 2026-01-08 08:00 NY
+ assertEquals(calendarDaysFromNow(finishTwo, nowSame, tz), 2);
+
+ // Finish 23:30 NY vs now 00:30 the NEXT NY day (finish is earlier) → clamped
+ // to 1, never 0 or negative.
+ const finishLate = ms("2026-01-07T04:30:00.000Z"); // 2026-01-06 23:30 NY
+ const nowNext = ms("2026-01-07T05:30:00.000Z"); // 2026-01-07 00:30 NY
+ assertEquals(calendarDaysFromNow(finishLate, nowNext, tz), 1);
+});
+
+const signals = (
+ o: Partial<QuoteScenarioSignals> = {}
+): QuoteScenarioSignals => ({
+ conflict: null,
+ queueNote: null,
+ bottleneckWorkCenter: null,
+ bottleneckOperationCount: 0,
+ ...o
+});
+
+it("composeQuoteCause: a conflict wins outright", () => {
+ const cause = composeQuoteCause({
+ scenario: "queued",
+ materialDays: 60,
+ materialItem: "GBX-80",
+ ownProductionDays: 150,
+ queueRemovableDays: 0,
+ signals: signals({ conflict: "No qualified operator" })
+ });
+ assertEquals(cause, "No qualified operator");
+});
+
+it("composeQuoteCause: production volume dominates → names the bottleneck WC", () => {
+ // qty 50 shape: 60d material, 300d own work, no removable queue → production.
+ const cause = composeQuoteCause({
+ scenario: "queued",
+ materialDays: 60,
+ materialItem: "GBX-80",
+ ownProductionDays: 300,
+ queueRemovableDays: 0,
+ signals: signals({
+ bottleneckWorkCenter: "5-Axis Mill",
+ bottleneckOperationCount: 8,
+ queueNote: "Waited 2d for the work center"
+ })
+ });
+ assert(cause?.includes("5-Axis Mill"));
+ assert(cause?.includes("8 operations"));
+});
+
+it("composeQuoteCause: material dominates → names the gating item", () => {
+ const cause = composeQuoteCause({
+ scenario: "bestCase",
+ materialDays: 60,
+ materialItem: "GBX-80",
+ ownProductionDays: 5,
+ queueRemovableDays: 0,
+ signals: signals({ bottleneckWorkCenter: "5-Axis Mill" })
+ });
+ assertEquals(cause, "Gated by material — GBX-80 lead time is 60 days");
+});
+
+it("composeQuoteCause: queue dominates only in the queued scenario", () => {
+ const args = {
+ materialDays: 0,
+ materialItem: null,
+ ownProductionDays: 10,
+ queueRemovableDays: 14,
+ signals: signals({
+ queueNote: "Queued behind J000001 (4 ops)",
+ bottleneckWorkCenter: "Lathe",
+ bottleneckOperationCount: 2
+ })
+ };
+ // Queued: removable queue (14) beats own production (10) → the queue note.
+ assertEquals(
+ composeQuoteCause({ scenario: "queued", ...args }),
+ "Queued behind J000001 (4 ops)"
+ );
+ // Best case: no queue component, so production wins instead.
+ const best = composeQuoteCause({ scenario: "bestCase", ...args });
+ assert(best?.includes("Lathe"));
+});
diff --git a/packages/planning/src/scheduling/quote-lead-time.ts b/packages/planning/src/scheduling/quote-lead-time.ts
new file mode 100644
index 0000000000..fc0a784998
--- /dev/null
+++ b/packages/planning/src/scheduling/quote-lead-time.ts
@@ -0,0 +1,926 @@
+import type { Database } from "@carbon/database";
+import type { DB } from "@carbon/database/client";
+import {
+ fromAbsolute,
+ parseDate,
+ toCalendarDate
+} from "@internationalized/date";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { Kysely } from "kysely";
+import {
+ type BatchPlacement,
+ placeReleasedBatches
+} from "./batch-scheduler.ts";
+import { buildScheduledOperations } from "./date-calculator.ts";
+import {
+ businessDayFromMs,
+ msToInstantIso,
+ toInstantMs
+} from "./date-utils.ts";
+import { buildOperationDependencies } from "./dependency-manager.ts";
+import {
+ buildFiniteContext,
+ loadAvailabilityWindows,
+ SCHEDULING_HORIZON_DAYS
+} from "./finite-context.ts";
+import { KyselyMasterDataProvider } from "./master-data-provider.ts";
+import { loadOrderedBatch } from "./run-schedule.ts";
+import type {
+ ReservationInterval,
+ ResourceCapacityData
+} from "./slot-allocator.ts";
+import type {
+ BaseOperation,
+ FactorUnit,
+ JobOperationDependency,
+ OperationType,
+ ScheduledOperation
+} from "./types.ts";
+import {
+ type FiniteSchedulingContext,
+ WorkCenterSelector
+} from "./work-center-selector.ts";
+
+const DAY_MS = 24 * 3_600_000;
+/** Same fallback MRP uses when an item has no itemReplenishment.leadTime. */
+const DEFAULT_ITEM_LEAD_TIME_DAYS = 7;
+
+// A quote line's routing rows, already Number()-coerced by the loader. The
+// engine's SchedulingEngine reads jobOperation/jobMaterial; the quote what-if
+// feeds these hand-loaded quote rows through the same pure placement core.
+export type QuoteMakeMethodRow = {
+ id: string;
+ parentMaterialId: string | null;
+};
+export type QuoteMaterialRow = {
+ id: string;
+ quoteMakeMethodId: string;
+ itemId: string;
+ /** human-readable part id, for the "gated by material — {item}" cause */
+ itemReadableId: string;
+ methodType: "Purchase to Order" | "Pull from Inventory" | "Make to Order";
+ /** per parent unit */
+ quantity: number;
+ /** consuming op */
+ quoteOperationId: string | null;
+};
+export type QuoteOperationRow = {
+ id: string;
+ quoteMakeMethodId: string;
+ processId: string | null;
+ workCenterId: string | null;
+ order: number;
+ operationOrder: "After Previous" | "With Previous";
+ operationType: string | null;
+ description: string | null;
+ setupTime: number;
+ setupUnit: string;
+ laborTime: number;
+ laborUnit: string;
+ machineTime: number;
+ machineUnit: string;
+ operationLeadTime: number;
+};
+export type MaterialAvailability = {
+ /** itemReplenishment.leadTime, default 7 */
+ leadTimeDaysByItem: Map<string, number>;
+ /** itemStockQuantities at the location */
+ onHandByItem: Map<string, number>;
+};
+
+/**
+ * Turn a quote line's routing + BOM into synthetic finite-placement inputs for
+ * one quantity: BaseOperations (quantities scaled down the make-method chain),
+ * the dependency graph (within-method + assembly edges, exactly as the job
+ * engine builds them), and per-operation material floors (materialReadyAt) for
+ * purchased / short-stock parts. Pure — all DB reads happen in the loader.
+ */
+export function buildQuoteSimulation(args: {
+ quoteLineId: string;
+ quantity: number;
+ makeMethods: QuoteMakeMethodRow[];
+ materials: QuoteMaterialRow[];
+ operations: QuoteOperationRow[];
+ availability: MaterialAvailability;
+ /** epoch ms */
+ now: number;
+}): {
+ jobId: string;
+ operations: BaseOperation[];
+ dependencies: JobOperationDependency[];
+ /** max floor in whole days, 0 if none */
+ materialReadyDays: number;
+ /** readable id of the part behind the largest floor, null if none */
+ materialFloorItem: string | null;
+ /** ops whose three times are all 0 */
+ zeroStandardOperationCount: number;
+} {
+ const {
+ quoteLineId,
+ quantity,
+ makeMethods,
+ materials,
+ operations,
+ availability,
+ now
+ } = args;
+ const jobId = `quote:${quoteLineId}:${quantity}`;
+
+ const materialById = new Map(materials.map((m) => [m.id, m]));
+
+ // Multiplier of each make method: the root is 1, every other method is its
+ // parent material's method multiplier × the material's per-parent quantity.
+ // Walk parents-first until no more resolve; a method whose parent never
+ // resolves is dropped (along with its operations).
+ const multiplierByMethod = new Map<string, number>();
+ for (const mm of makeMethods) {
+ if (mm.parentMaterialId === null) {
+ multiplierByMethod.set(mm.id, 1);
+ }
+ }
+ let progress = true;
+ while (progress) {
+ progress = false;
+ for (const mm of makeMethods) {
+ if (multiplierByMethod.has(mm.id)) continue;
+ if (mm.parentMaterialId === null) continue;
+ const parentMaterial = materialById.get(mm.parentMaterialId);
+ if (!parentMaterial) continue;
+ const parentMultiplier = multiplierByMethod.get(
+ parentMaterial.quoteMakeMethodId
+ );
+ if (parentMultiplier === undefined) continue;
+ multiplierByMethod.set(mm.id, parentMultiplier * parentMaterial.quantity);
+ progress = true;
+ }
+ }
+
+ // Build the operations for every resolved method.
+ const builtOps: BaseOperation[] = [];
+ const opById = new Map<string, BaseOperation>();
+ const opsByMethod = new Map<string, BaseOperation[]>();
+ for (const op of operations) {
+ const multiplier = multiplierByMethod.get(op.quoteMakeMethodId);
+ if (multiplier === undefined) continue;
+ const built: BaseOperation = {
+ id: op.id,
+ jobId,
+ jobMakeMethodId: op.quoteMakeMethodId,
+ processId: op.processId,
+ workCenterId: op.workCenterId,
+ order: op.order,
+ operationOrder: op.operationOrder,
+ operationType: (op.operationType ?? undefined) as
+ | OperationType
+ | undefined,
+ description: op.description,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit as FactorUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit as FactorUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit as FactorUnit,
+ operationLeadTime: op.operationLeadTime,
+ operationQuantity: quantity * multiplier,
+ quantityComplete: 0,
+ status: "Todo"
+ };
+ builtOps.push(built);
+ opById.set(op.id, built);
+ const list = opsByMethod.get(op.quoteMakeMethodId) ?? [];
+ list.push(built);
+ opsByMethod.set(op.quoteMakeMethodId, list);
+ }
+
+ // Dependencies: within each method, plus one assembly edge per non-root
+ // method from the child's last op to the parent's consuming op.
+ const depMap = new Map<string, Set<string>>();
+ for (const op of builtOps) {
+ depMap.set(op.id!, new Set<string>());
+ }
+ for (const [, methodOps] of opsByMethod) {
+ for (const [opId, deps] of buildOperationDependencies(methodOps)) {
+ const existing = depMap.get(opId);
+ if (existing) {
+ for (const depId of deps) existing.add(depId);
+ }
+ }
+ }
+ for (const mm of makeMethods) {
+ if (mm.parentMaterialId === null) continue;
+ if (!multiplierByMethod.has(mm.id)) continue;
+ const childOps = opsByMethod.get(mm.id) ?? [];
+ if (childOps.length === 0) continue;
+ const lastOpOfChild = [...childOps].sort(
+ (a, b) => (a.order ?? 0) - (b.order ?? 0)
+ )[childOps.length - 1];
+ const parentMaterial = materialById.get(mm.parentMaterialId);
+ if (!parentMaterial) continue;
+ let consumingOpId = parentMaterial.quoteOperationId;
+ if (!consumingOpId) {
+ const parentOps = opsByMethod.get(parentMaterial.quoteMakeMethodId) ?? [];
+ consumingOpId =
+ [...parentOps].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))[0]?.id ??
+ null;
+ }
+ if (consumingOpId && lastOpOfChild?.id && depMap.has(consumingOpId)) {
+ depMap.get(consumingOpId)!.add(lastOpOfChild.id);
+ }
+ }
+ const dependencies: JobOperationDependency[] = [];
+ for (const [operationId, deps] of depMap) {
+ for (const dependsOnId of deps) {
+ dependencies.push({ operationId, dependsOnId, jobId });
+ }
+ }
+
+ // Material floors: a purchased part, or a stocked part short of the required
+ // quantity, gates its consuming operation at now + the item's lead time.
+ let materialReadyDays = 0;
+ let materialFloorItem: string | null = null;
+ for (const material of materials) {
+ const multiplier = multiplierByMethod.get(material.quoteMakeMethodId);
+ if (multiplier === undefined) continue;
+ const required = quantity * multiplier * material.quantity;
+ let floorDays = 0;
+ if (material.methodType === "Purchase to Order") {
+ floorDays =
+ availability.leadTimeDaysByItem.get(material.itemId) ??
+ DEFAULT_ITEM_LEAD_TIME_DAYS;
+ } else if (
+ material.methodType === "Pull from Inventory" &&
+ (availability.onHandByItem.get(material.itemId) ?? 0) < required
+ ) {
+ floorDays =
+ availability.leadTimeDaysByItem.get(material.itemId) ??
+ DEFAULT_ITEM_LEAD_TIME_DAYS;
+ }
+ if (floorDays <= 0) continue;
+
+ let consumingOpId = material.quoteOperationId;
+ if (!consumingOpId) {
+ const methodOps = opsByMethod.get(material.quoteMakeMethodId) ?? [];
+ consumingOpId =
+ [...methodOps].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))[0]?.id ??
+ null;
+ }
+ if (!consumingOpId) continue;
+ const consumingOp = opById.get(consumingOpId);
+ if (!consumingOp) continue;
+
+ const readyAt = now + floorDays * DAY_MS;
+ consumingOp.materialReadyAt =
+ consumingOp.materialReadyAt === undefined
+ ? readyAt
+ : Math.max(consumingOp.materialReadyAt, readyAt);
+ if (floorDays > materialReadyDays) {
+ materialReadyDays = floorDays;
+ materialFloorItem = material.itemReadableId;
+ }
+ }
+
+ const zeroStandardOperationCount = builtOps.filter(
+ (op) =>
+ (op.setupTime ?? 0) === 0 &&
+ (op.laborTime ?? 0) === 0 &&
+ (op.machineTime ?? 0) === 0
+ ).length;
+
+ return {
+ jobId,
+ operations: builtOps,
+ dependencies,
+ materialReadyDays,
+ materialFloorItem,
+ zeroStandardOperationCount
+ };
+}
+
+/**
+ * A shallow clone that gives every simulation run its OWN reservation arrays.
+ * FiniteSchedulingContext's reservation arrays "are mutated in-run as
+ * operations are placed" (see its doc), so a second run over the same context
+ * would see the first run's placements. Everything else is shared by reference.
+ */
+export function cloneFiniteContext(
+ ctx: FiniteSchedulingContext
+): FiniteSchedulingContext {
+ const capacityByWorkCenter = new Map<string, ResourceCapacityData>();
+ for (const [id, data] of ctx.capacityByWorkCenter) {
+ capacityByWorkCenter.set(id, {
+ ...data,
+ reservations: [...data.reservations]
+ });
+ }
+ const reservationsByEmployee = new Map<string, ReservationInterval[]>();
+ for (const [id, list] of ctx.reservationsByEmployee) {
+ reservationsByEmployee.set(id, [...list]);
+ }
+ return { ...ctx, capacityByWorkCenter, reservationsByEmployee };
+}
+
+/**
+ * Calendar days from now to a finish instant, both resolved on the location's
+ * calendar, minimum 1. `convert` turns leadTime into promisedDate = today + N,
+ * so calendar days is the only unit that round-trips.
+ */
+export function calendarDaysFromNow(
+ finishMs: number,
+ nowMs: number,
+ timeZone: string
+): number {
+ const finish = toCalendarDate(fromAbsolute(finishMs, timeZone));
+ const today = toCalendarDate(fromAbsolute(nowMs, timeZone));
+ const days = finish.compare(today);
+ return days < 1 ? 1 : days;
+}
+
+export type QuoteScenarioSignals = {
+ /** an unplaceable / late conflict on any op — wins outright when present */
+ conflict: string | null;
+ /** the engine's note for the reservation that waited longest for capacity */
+ queueNote: string | null;
+ /** name of the work center carrying the most placed time on the critical path */
+ bottleneckWorkCenter: string | null;
+ /** how many of this scenario's operations run on that work center */
+ bottleneckOperationCount: number;
+};
+
+/**
+ * The makespan DRIVER, not the largest single wait. A long quote lead time is
+ * usually dominated by (a) a purchased/short-stock material floor — an absolute
+ * `now + leadTime` date the queue can't move — or (b) the job's own production
+ * volume on a shared work center, which is identical whether or not other jobs
+ * are excluded. The old "largest capacity wait" cause never surfaced either, so
+ * an end-of-queue and a best-case run that finish on the same day looked
+ * unexplained. This decomposes the total into the three parts and names the
+ * biggest one, so the sentence tells the same story the numbers do.
+ *
+ * `ownProductionDays` is `bestCaseDays - materialDays` (best case has no
+ * other-job queue, so it is material + the job's own work); `queueRemovableDays`
+ * is `queuedDays - bestCaseDays` — exactly what jumping the queue would save.
+ * Pure so `quote-lead-time.test.ts` can pin the ranking.
+ */
+export function composeQuoteCause(args: {
+ scenario: "queued" | "bestCase";
+ materialDays: number;
+ materialItem: string | null;
+ ownProductionDays: number;
+ queueRemovableDays: number;
+ signals: QuoteScenarioSignals;
+}): string | null {
+ const {
+ scenario,
+ materialDays,
+ materialItem,
+ ownProductionDays,
+ queueRemovableDays,
+ signals
+ } = args;
+
+ // A real placement conflict (unplaceable op, past due date) always wins.
+ if (signals.conflict) return signals.conflict;
+
+ // Best case has no other-job queue, so its queue component is zero.
+ const queueDays = scenario === "queued" ? queueRemovableDays : 0;
+
+ const productionCause = () => {
+ if (signals.bottleneckWorkCenter) {
+ return `Mostly this job's own production — ${signals.bottleneckWorkCenter} carries the most work across ${signals.bottleneckOperationCount} operations`;
+ }
+ return "Mostly this job's own production time across the routing";
+ };
+ const materialCause = () =>
+ materialItem
+ ? `Gated by material — ${materialItem} lead time is ${materialDays} days`
+ : `Gated by material — a purchased part's lead time is ${materialDays} days`;
+
+ // Rank the three contributors; name the largest. Ties fall to the more
+ // actionable explanation: material (order sooner) over production, and queue
+ // (expedite) only when it genuinely dominates.
+ if (
+ queueDays > materialDays &&
+ queueDays > ownProductionDays &&
+ signals.queueNote
+ ) {
+ return signals.queueNote;
+ }
+ if (materialDays > 0 && materialDays >= ownProductionDays) {
+ return materialCause();
+ }
+ if (ownProductionDays > 0) return productionCause();
+
+ // Nothing dominant (a tiny job placed at once) — fall back to whatever the
+ // engine noted, else no cause.
+ return signals.queueNote;
+}
+
+// ============================================================================
+// Orchestrator — runQuoteLeadTimeWhatIf
+// ============================================================================
+
+export type QuoteLeadTimeScenario = {
+ /** ISO instant of the last placed end */
+ finishAt: string | null;
+ /** calendar days from today (location tz), min 1 */
+ leadTimeDays: number | null;
+ /** first conflict, else the longest wait's note */
+ cause: string | null;
+};
+
+export type QuoteLeadTimeForecast = {
+ quoteLineId: string;
+ locationId: string;
+ computedAt: string;
+ /** ops whose three time standards are all 0 (constant across quantities) */
+ zeroStandardOperationCount: number;
+ quantities: Array<{
+ quantity: number;
+ /** 0 when nothing gates */
+ materialReadyDays: number;
+ /** end of queue */
+ queued: QuoteLeadTimeScenario;
+ /** front of queue */
+ bestCase: QuoteLeadTimeScenario;
+ /** present only when a dueDate was sent */
+ target: {
+ /** YYYY-MM-DD */
+ date: string;
+ verdict: "on-time" | "expedite" | "late";
+ /** negative = short, vs the queued finish */
+ slackDays: number;
+ } | null;
+ }>;
+ /** rendered verbatim in the modal */
+ assumptions: string[];
+};
+
+/**
+ * Load a quote line's routing + BOM with Kysely, scoped to the company. Returns
+ * null when the line has no make method (a Pull/Purchase line has no routing to
+ * schedule). Every numeric is Number()-coerced — Kysely hands NUMERIC back as a
+ * string.
+ */
+async function loadQuoteLineRouting(
+ db: Kysely<DB>,
+ quoteLineId: string,
+ companyId: string
+): Promise<{
+ makeMethods: QuoteMakeMethodRow[];
+ materials: QuoteMaterialRow[];
+ operations: QuoteOperationRow[];
+} | null> {
+ const [makeMethodRows, materialRows, operationRows] = await Promise.all([
+ db
+ .selectFrom("quoteMakeMethod")
+ .select(["id", "parentMaterialId"])
+ .where("quoteLineId", "=", quoteLineId)
+ .where("companyId", "=", companyId)
+ .execute(),
+ db
+ .selectFrom("quoteMaterial")
+ .innerJoin("item", "item.id", "quoteMaterial.itemId")
+ .select([
+ "quoteMaterial.id as id",
+ "quoteMaterial.quoteMakeMethodId as quoteMakeMethodId",
+ "quoteMaterial.itemId as itemId",
+ "item.readableId as itemReadableId",
+ "quoteMaterial.methodType as methodType",
+ "quoteMaterial.quantity as quantity",
+ "quoteMaterial.quoteOperationId as quoteOperationId"
+ ])
+ .where("quoteMaterial.quoteLineId", "=", quoteLineId)
+ .where("quoteMaterial.companyId", "=", companyId)
+ .execute(),
+ db
+ .selectFrom("quoteOperation")
+ .select([
+ "id",
+ "quoteMakeMethodId",
+ "processId",
+ "workCenterId",
+ "order",
+ "operationOrder",
+ "operationType",
+ "description",
+ "setupTime",
+ "setupUnit",
+ "laborTime",
+ "laborUnit",
+ "machineTime",
+ "machineUnit",
+ "operationLeadTime"
+ ])
+ .where("quoteLineId", "=", quoteLineId)
+ .where("companyId", "=", companyId)
+ .execute()
+ ]);
+
+ if (makeMethodRows.length === 0) return null;
+
+ const makeMethods: QuoteMakeMethodRow[] = makeMethodRows.map((m) => ({
+ id: m.id,
+ parentMaterialId: m.parentMaterialId
+ }));
+ const materials: QuoteMaterialRow[] = materialRows.map((m) => ({
+ id: m.id,
+ quoteMakeMethodId: m.quoteMakeMethodId,
+ itemId: m.itemId,
+ itemReadableId: m.itemReadableId,
+ methodType: m.methodType,
+ quantity: Number(m.quantity),
+ quoteOperationId: m.quoteOperationId
+ }));
+ const operations: QuoteOperationRow[] = operationRows
+ .filter(
+ (o): o is typeof o & { quoteMakeMethodId: string } =>
+ o.quoteMakeMethodId !== null
+ )
+ .map((o) => ({
+ id: o.id,
+ quoteMakeMethodId: o.quoteMakeMethodId,
+ processId: o.processId,
+ workCenterId: o.workCenterId,
+ order: Number(o.order),
+ operationOrder: o.operationOrder,
+ operationType: o.operationType,
+ description: o.description,
+ setupTime: Number(o.setupTime),
+ setupUnit: o.setupUnit,
+ laborTime: Number(o.laborTime),
+ laborUnit: o.laborUnit,
+ machineTime: Number(o.machineTime),
+ machineUnit: o.machineUnit,
+ operationLeadTime: Number(o.operationLeadTime)
+ }));
+
+ return { makeMethods, materials, operations };
+}
+
+/**
+ * Item lead times (itemReplenishment.leadTime, default 7) and location on-hand
+ * (itemStockQuantities, the aggregate runMrp reads) for the material floors.
+ */
+async function loadMaterialAvailability(
+ db: Kysely<DB>,
+ itemIds: string[],
+ locationId: string,
+ companyId: string
+): Promise<MaterialAvailability> {
+ const leadTimeDaysByItem = new Map<string, number>();
+ const onHandByItem = new Map<string, number>();
+ if (itemIds.length === 0) return { leadTimeDaysByItem, onHandByItem };
+
+ const [replenishmentRows, stockRows] = await Promise.all([
+ db
+ .selectFrom("itemReplenishment")
+ .select(["itemId", "leadTime"])
+ .where("itemId", "in", itemIds)
+ .where("companyId", "=", companyId)
+ .execute(),
+ db
+ .selectFrom("itemStockQuantities")
+ .select(["itemId", "quantityOnHand"])
+ .where("itemId", "in", itemIds)
+ .where("locationId", "=", locationId)
+ .where("companyId", "=", companyId)
+ .execute()
+ ]);
+ for (const r of replenishmentRows) {
+ if (r.itemId != null) {
+ leadTimeDaysByItem.set(
+ r.itemId,
+ Number(r.leadTime ?? DEFAULT_ITEM_LEAD_TIME_DAYS)
+ );
+ }
+ }
+ for (const r of stockRows) {
+ if (r.itemId != null) {
+ onHandByItem.set(r.itemId, Number(r.quantityOnHand) || 0);
+ }
+ }
+ return { leadTimeDaysByItem, onHandByItem };
+}
+
+/**
+ * Capable-to-promise for a quote line: forward-ASAP finite placement of the
+ * line's synthetic routing against the live reservation snapshot ("end of
+ * queue", excludeJobIds []) and against the location's open jobs excluded
+ * ("best case", the same snapshot runExpediteWhatIf uses). Persists nothing.
+ * Returns null when the line has no routing to schedule.
+ */
+export async function runQuoteLeadTimeWhatIf(params: {
+ db: Kysely<DB>;
+ client: SupabaseClient<Database>;
+ companyId: string;
+ userId: string;
+ locationId: string;
+ quoteLineId: string;
+ quantities: number[];
+ dueDate?: string | null;
+}): Promise<QuoteLeadTimeForecast | null> {
+ const {
+ db,
+ client,
+ companyId,
+ userId,
+ locationId,
+ quoteLineId,
+ quantities,
+ dueDate
+ } = params;
+
+ // The engine's clock convention: one `now` for the whole run. Not used for
+ // anything but epoch-ms arithmetic.
+ const now = Date.now();
+
+ const locationRow = await db
+ .selectFrom("location")
+ .select(["timezone", "name"])
+ .where("id", "=", locationId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ const timeZone = locationRow?.timezone ?? "UTC";
+ const locationName = locationRow?.name ?? "this location";
+
+ const routing = await loadQuoteLineRouting(db, quoteLineId, companyId);
+ if (!routing) return null;
+
+ const availability = await loadMaterialAvailability(
+ db,
+ Array.from(new Set(routing.materials.map((m) => m.itemId))),
+ locationId,
+ companyId
+ );
+
+ const provider = new KyselyMasterDataProvider(db, client, companyId, {
+ cacheCompanyData: true
+ });
+
+ const batch = await loadOrderedBatch(db, locationId, companyId);
+
+ // Mirror the existing batch reservations (persist: false reads them back)
+ // so the what-if agrees with the rows already in its snapshot.
+ let batchPlacements: Map<string, BatchPlacement> | null = null;
+ try {
+ batchPlacements = await placeReleasedBatches({
+ db,
+ provider,
+ companyId,
+ locationId,
+ now,
+ userId,
+ orderedJobIds: batch,
+ horizonEnd: now + (SCHEDULING_HORIZON_DAYS + 7) * 24 * 3_600_000,
+ persist: false
+ });
+ } catch {
+ // fall through — the sim runs with per-member placement
+ }
+
+ const selector = new WorkCenterSelector(provider, locationId);
+ await selector.initialize();
+
+ // The op ids, process ids and dependency graph are identical for every
+ // quantity — only operationQuantity scales. Build the first simulation to
+ // derive the windows fetch and the two contexts once.
+ const firstSim = buildQuoteSimulation({
+ quoteLineId,
+ quantity: quantities[0]!,
+ ...routing,
+ availability,
+ now
+ });
+ const firstOps = Array.from(
+ buildScheduledOperations(firstSim.operations).values()
+ );
+
+ const windows = await loadAvailabilityWindows({
+ provider,
+ workCenterSelector: selector,
+ operations: firstOps,
+ locationId,
+ now
+ });
+
+ const queuedCtx = await buildFiniteContext({
+ provider,
+ operations: firstOps,
+ dependencies: firstSim.dependencies,
+ availability: windows,
+ locationId,
+ timeZone,
+ now,
+ excludeJobIds: []
+ });
+ const bestCtx = await buildFiniteContext({
+ provider,
+ operations: firstOps,
+ dependencies: firstSim.dependencies,
+ availability: windows,
+ locationId,
+ timeZone,
+ now,
+ excludeJobIds: batch
+ });
+
+ // The busiest work center is named in the cause sentence, so map the
+ // candidate work-center ids to names once.
+ const workCenterNames = new Map<string, string>();
+ {
+ const ids = Array.from(windows.workCenterIds);
+ if (ids.length > 0) {
+ const wcRows = await db
+ .selectFrom("workCenter")
+ .select(["id", "name"])
+ .where("id", "in", ids)
+ .where("companyId", "=", companyId)
+ .execute();
+ for (const wc of wcRows) workCenterNames.set(wc.id, wc.name);
+ }
+ }
+
+ // One selector instance for every run: selectWorkCentersForOperations resets
+ // plannedReservations at its start and setFiniteContext swaps the context, so
+ // a cloned context per run is the only isolation needed.
+ const runScenario = (
+ ctx: FiniteSchedulingContext,
+ ops: ScheduledOperation[]
+ ): { finishMs: number | null; signals: QuoteScenarioSignals } => {
+ selector.setFiniteContext(cloneFiniteContext(ctx));
+ const selections = selector.selectWorkCentersForOperations(ops, {
+ // The target verdict is computed from the finish dates below; a due date
+ // here would only add lateness conflicts that mask the real cause.
+ jobDueDate: null,
+ batchPlacements
+ });
+ // Projected finish = the latest placed end across selections and the
+ // planned reservations, the same union selectWorkCenters() computes.
+ let finishMs: number | null = null;
+ const bump = (ms: number) => {
+ if (finishMs === null || ms > finishMs) finishMs = ms;
+ };
+ for (const s of selections.values()) {
+ if (s.placedEnd) bump(toInstantMs(s.placedEnd));
+ }
+ // The first placement conflict, if any. An op with no process or no work
+ // center at this location comes back as `error` with nothing placed, so it
+ // counts too — otherwise the finish silently omits it.
+ let conflict: string | null = null;
+ for (const s of selections.values()) {
+ const reason = s.conflict ?? s.error ?? null;
+ if (reason) {
+ conflict = reason;
+ break;
+ }
+ }
+ // The note of the reservation that waited longest for capacity, and the
+ // work center carrying the most placed time (the bottleneck resource).
+ let queueNote: string | null = null;
+ let maxWait = -1;
+ const wcLoad = new Map<string, { ms: number; ops: number }>();
+ for (const p of selector.getPlannedReservations()) {
+ if (p.endAt > p.startAt) bump(p.endAt);
+ if (p.scheduleNote) {
+ const wait =
+ p.earliestStartAt !== undefined ? p.startAt - p.earliestStartAt : 0;
+ if (wait > maxWait) {
+ maxWait = wait;
+ queueNote = p.scheduleNote;
+ }
+ }
+ if (p.resourceKind === "WorkCenter" && p.endAt > p.startAt) {
+ const load = wcLoad.get(p.resourceId) ?? { ms: 0, ops: 0 };
+ load.ms += p.endAt - p.startAt;
+ load.ops += 1;
+ wcLoad.set(p.resourceId, load);
+ }
+ }
+ let bottleneckWorkCenter: string | null = null;
+ let bottleneckOperationCount = 0;
+ let maxLoad = -1;
+ for (const [wcId, load] of wcLoad) {
+ if (load.ms > maxLoad) {
+ maxLoad = load.ms;
+ bottleneckWorkCenter = workCenterNames.get(wcId) ?? null;
+ bottleneckOperationCount = load.ops;
+ }
+ }
+ return {
+ finishMs,
+ signals: {
+ conflict,
+ queueNote,
+ bottleneckWorkCenter,
+ bottleneckOperationCount
+ }
+ };
+ };
+
+ const scenarioResult = (
+ finishMs: number | null,
+ cause: string | null
+ ): QuoteLeadTimeScenario => ({
+ finishAt: finishMs === null ? null : msToInstantIso(finishMs),
+ leadTimeDays:
+ finishMs === null ? null : calendarDaysFromNow(finishMs, now, timeZone),
+ cause
+ });
+
+ const quantityResults = quantities.map((quantity) => {
+ const sim = buildQuoteSimulation({
+ quoteLineId,
+ quantity,
+ ...routing,
+ availability,
+ now
+ });
+ const ops = Array.from(buildScheduledOperations(sim.operations).values());
+
+ const queued = runScenario(queuedCtx, ops);
+ const bestCase = runScenario(bestCtx, ops);
+
+ const queuedDays =
+ queued.finishMs === null
+ ? null
+ : calendarDaysFromNow(queued.finishMs, now, timeZone);
+ const bestDays =
+ bestCase.finishMs === null
+ ? null
+ : calendarDaysFromNow(bestCase.finishMs, now, timeZone);
+ // Decompose the total so the cause names the makespan DRIVER, not the
+ // largest single wait: best case = material floor + the job's own work;
+ // queued adds the removable other-job queue on top.
+ const materialDays = sim.materialReadyDays;
+ const ownProductionDays = Math.max(0, (bestDays ?? 0) - materialDays);
+ const queueRemovableDays = Math.max(0, (queuedDays ?? 0) - (bestDays ?? 0));
+
+ const queuedCause = composeQuoteCause({
+ scenario: "queued",
+ materialDays,
+ materialItem: sim.materialFloorItem,
+ ownProductionDays,
+ queueRemovableDays,
+ signals: queued.signals
+ });
+ const bestCaseCause = composeQuoteCause({
+ scenario: "bestCase",
+ materialDays,
+ materialItem: sim.materialFloorItem,
+ ownProductionDays,
+ queueRemovableDays,
+ signals: bestCase.signals
+ });
+
+ let target: {
+ date: string;
+ verdict: "on-time" | "expedite" | "late";
+ slackDays: number;
+ } | null = null;
+ if (dueDate) {
+ const queuedFinishDate =
+ queued.finishMs === null
+ ? null
+ : businessDayFromMs(queued.finishMs, timeZone);
+ const bestFinishDate =
+ bestCase.finishMs === null
+ ? null
+ : businessDayFromMs(bestCase.finishMs, timeZone);
+ let verdict: "on-time" | "expedite" | "late";
+ if (queuedFinishDate && queuedFinishDate <= dueDate) {
+ verdict = "on-time";
+ } else if (bestFinishDate && bestFinishDate <= dueDate) {
+ verdict = "expedite";
+ } else {
+ verdict = "late";
+ }
+ const slackDays = queuedFinishDate
+ ? parseDate(dueDate).compare(parseDate(queuedFinishDate))
+ : 0;
+ target = { date: dueDate, verdict, slackDays };
+ }
+
+ return {
+ quantity,
+ materialReadyDays: sim.materialReadyDays,
+ queued: scenarioResult(queued.finishMs, queuedCause),
+ bestCase: scenarioResult(bestCase.finishMs, bestCaseCause),
+ target
+ };
+ });
+
+ const assumptions = [
+ `Placed after every job already released at ${locationName}`,
+ `Purchased material is available after its item lead time; stock is netted at ${locationName} only`,
+ "No shipping buffer is added"
+ ];
+
+ return {
+ quoteLineId,
+ locationId,
+ computedAt: msToInstantIso(now),
+ zeroStandardOperationCount: firstSim.zeroStandardOperationCount,
+ quantities: quantityResults,
+ assumptions
+ };
+}
diff --git a/packages/planning/src/scheduling/run-schedule.ts b/packages/planning/src/scheduling/run-schedule.ts
index 1f023e27b3..0bdd2f7087 100644
--- a/packages/planning/src/scheduling/run-schedule.ts
+++ b/packages/planning/src/scheduling/run-schedule.ts
@@ -70,7 +70,7 @@ const asMs = (value: unknown): number | null =>
* order leads the queue instead of trailing on NULLS LAST), then due date ASC
* NULLS LAST, priority ASC, createdAt ASC. Sorted in TS.
*/
-async function loadOrderedBatch(
+export async function loadOrderedBatch(
db: Kysely<DB>,
locationId: string,
companyId: string
diff --git a/packages/planning/src/scheduling/scheduling-engine.ts b/packages/planning/src/scheduling/scheduling-engine.ts
index 9c206d5dfd..19b3dda1dc 100644
--- a/packages/planning/src/scheduling/scheduling-engine.ts
+++ b/packages/planning/src/scheduling/scheduling-engine.ts
@@ -16,12 +16,6 @@ import {
buildMakeMethodDependencies
} from "./assembly-handler.ts";
import type { BatchPlacement } from "./batch-scheduler.ts";
-import {
- type CalendarShiftRow,
- type CalendarWindow,
- expandCalendar,
- unionWindows
-} from "./calendar-utils.ts";
import {
type BehindTargetOperation,
composeBehindTarget
@@ -40,27 +34,22 @@ import {
dependenciesToRecords
} from "./dependency-manager.ts";
import { calculateDurationHours } from "./duration-calculator.ts";
+import {
+ type AvailabilityWindows,
+ buildFiniteContext,
+ loadAvailabilityWindows
+} from "./finite-context.ts";
import {
KyselyMasterDataProvider,
type MasterDataProvider
} from "./master-data-provider.ts";
import { MaterialManager } from "./material-manager.ts";
import { calendarAdapters, computeNeedByDates } from "./need-by-calculator.ts";
-import {
- buildAbsencesByEmployee,
- buildAssignmentsByEmployee,
- buildOvertimeByEmployee,
- buildPeopleBudgets,
- buildPeopleByWorkCenter,
- extendWindowsByOvertime,
- subtractAbsences
-} from "./people-utils.ts";
import {
applyPriorities,
calculatePrioritiesByWorkCenter,
toOperationWithJobInfo
} from "./priority-calculator.ts";
-import type { ResourceCapacityData } from "./slot-allocator.ts";
import type {
BaseOperation,
Job,
@@ -74,11 +63,10 @@ import { capacityHoldingJobStatuses } from "./types.ts";
import {
applyWorkCenterSelections,
type FiniteSchedulingContext,
- type PoolEmployee,
WorkCenterSelector
} from "./work-center-selector.ts";
-export const SCHEDULING_HORIZON_DAYS = 365;
+export { SCHEDULING_HORIZON_DAYS } from "./finite-context.ts";
const log = getFunctionLogger("schedule");
@@ -148,13 +136,7 @@ export class SchedulingEngine {
* the finite placement context so targets and forecasts run on the SAME
* calendar physics (and the provider is read once, not twice).
*/
- private availabilityWindows: {
- workCenterIds: Set<string>;
- workCenterAvailability: Map<string, CalendarWindow[]>;
- locationDefaultWindows: CalendarWindow[];
- rangeStart: number;
- rangeEnd: number;
- } | null = null;
+ private availabilityWindows: AvailabilityWindows | null = null;
private provider: MasterDataProvider;
@@ -555,63 +537,17 @@ export class SchedulingEngine {
* calendar — memoized so the backward need-by pass and buildFiniteContext
* share the same load instead of reading the provider twice.
*/
- private async loadAvailabilityWindows(): Promise<{
- workCenterIds: Set<string>;
- workCenterAvailability: Map<string, CalendarWindow[]>;
- locationDefaultWindows: CalendarWindow[];
- rangeStart: number;
- rangeEnd: number;
- }> {
+ private async loadAvailabilityWindows(): Promise<AvailabilityWindows> {
if (this.availabilityWindows) {
return this.availabilityWindows;
}
-
- const operations = Array.from(this.scheduledOperations.values());
- const processIds = Array.from(
- new Set(operations.map((op) => op.processId).filter(Boolean))
- ) as string[];
-
- // Candidates for selection + current assignments (assigned work centers
- // stay in play via the sticky/fallback rules).
- const workCenterIds = new Set(
- this.workCenterSelector?.getAllCandidateWorkCenterIds(processIds) ?? []
- );
- for (const op of operations) {
- if (op.workCenterId) {
- workCenterIds.add(op.workCenterId);
- }
- }
-
- const rangeStart = this.now;
- const rangeEnd = this.now + (SCHEDULING_HORIZON_DAYS + 7) * 24 * 3_600_000;
-
- const [workCenterAvailability, locationDefaultWindows] = await Promise.all([
- this.provider.getWorkCenterAvailability(
- [...workCenterIds],
- rangeStart,
- rangeEnd
- ),
- // People with no employeeShift rows default to the job location's calendar
- // (plant hours), not 24×7 — matching the default machine window so
- // unconfigured labor is non-constraining within plant hours.
- this.job?.locationId
- ? this.provider.getLocationCalendarWindows(
- this.job.locationId,
- rangeStart,
- rangeEnd
- )
- : Promise.resolve<CalendarWindow[]>([
- { start: rangeStart, end: rangeEnd }
- ]) // rangeStart/rangeEnd are epoch-ms
- ]);
-
- this.availabilityWindows = {
- workCenterIds,
- workCenterAvailability,
- locationDefaultWindows,
- rangeStart,
- rangeEnd
- };
+ this.availabilityWindows = await loadAvailabilityWindows({
+ provider: this.provider,
+ workCenterSelector: this.workCenterSelector,
+ operations: Array.from(this.scheduledOperations.values()),
+ locationId: this.job?.locationId ?? null,
+ now: this.now
+ });
return this.availabilityWindows;
}
@@ -674,220 +610,17 @@ export class SchedulingEngine {
if (!this.workCenterSelector) {
return null;
}
-
- // The run's single clock (shared across the batch) — never Date.now() here.
- const now = this.now;
- const operations = Array.from(this.scheduledOperations.values());
- const processIds = Array.from(
- new Set(operations.map((op) => op.processId).filter(Boolean))
- ) as string[];
-
- // One shared windows fetch per run (also used by the need-by pass).
- const {
- workCenterIds,
- workCenterAvailability,
- locationDefaultWindows,
- rangeStart,
- rangeEnd
- } = await this.loadAvailabilityWindows();
-
- const operationIds = operations
- .map((op) => op.id)
- .filter((id): id is string => Boolean(id));
-
- const [
- liveReservations,
- processRequirements,
- peopleRows,
- absenceRows,
- operationsWithEvents
- ] = await Promise.all([
- this.provider.getLiveReservations(now, this.excludeJobIds),
- this.provider.getProcessRequirements(processIds),
- this.provider.getPeopleAssignments(rangeStart, rangeEnd, this.timezone),
- this.provider.getPeopleAbsences(rangeStart, rangeEnd, this.timezone),
- this.provider.getOperationsWithEvents(operationIds)
- ]);
-
- const abilityIds = Array.from(
- new Set(processRequirements.map((r) => r.abilityId))
- );
- const employees = await this.provider.getQualifiedEmployees(abilityIds);
- // People members at ungated stations need real availability windows too, so
- // shift rows are loaded for the union of qualified + assigned people
- const employeeIds = Array.from(
- new Set([
- ...employees.map((e) => e.employeeId),
- ...peopleRows.map((r) => r.employeeId)
- ])
- );
- const shiftRows = await this.provider.getEmployeeShiftWindows(employeeIds);
-
- // Work centers: capacity 1, open per the availability ladder (explicit
- // workCenterShift rows → location shifts → stock Mon–Fri 8h, or one open
- // window for an alwaysOn machine). Reservations GATE placement (one op at a
- // time) and feed attribution. A WC with no resolved windows (e.g. deleted)
- // schedules nothing and surfaces a conflict.
- // Require-staffing policy (per-location) + which stations are lights-out —
- // both feed the selector's fallback gates. One cached read each per batch.
- const [requiresStaffing, alwaysOnWorkCenterIds] = await Promise.all([
- this.job?.locationId
- ? this.provider.getLocationRequiresStaffing(this.job.locationId)
- : Promise.resolve(false),
- this.provider.getAlwaysOnWorkCenterIds(Array.from(workCenterIds))
- ]);
-
- const capacityByWorkCenter = new Map<string, ResourceCapacityData>();
- for (const wcId of workCenterIds) {
- capacityByWorkCenter.set(wcId, {
- workCenter: { id: wcId, alwaysOn: alwaysOnWorkCenterIds.has(wcId) },
- windows: workCenterAvailability.get(wcId) ?? [],
- reservations: liveReservations
- .filter(
- (r) => r.resourceKind === "WorkCenter" && r.resourceId === wcId
- )
- .map((r) => ({
- startAt: r.startAt,
- endAt: r.endAt,
- readableJobId: r.readableJobId
- }))
- });
- }
-
- const requirementByProcess = new Map(
- processRequirements.map((r) => [
- r.processId,
- { abilityId: r.abilityId, abilityName: r.abilityName }
- ])
- );
-
- // Each qualified person's availability = their assigned shifts expanded
- // over the horizon (grouped by timezone, unioned). No shift assignment
- // => always available.
- const shiftPatternsByEmployee = new Map<
- string,
- Map<string, CalendarShiftRow[]>
- >();
- for (const row of shiftRows) {
- let byTz = shiftPatternsByEmployee.get(row.employeeId);
- if (!byTz) {
- byTz = new Map();
- shiftPatternsByEmployee.set(row.employeeId, byTz);
- }
- const list = byTz.get(row.timezone) ?? [];
- list.push({
- dayOfWeek: row.dayOfWeek,
- startTime: row.startTime,
- endTime: row.endTime
- });
- byTz.set(row.timezone, list);
- }
- const windowsByEmployee = new Map<string, CalendarWindow[]>();
- for (const [employeeId, byTz] of shiftPatternsByEmployee) {
- const lists = Array.from(byTz.entries()).map(([tz, shifts]) =>
- expandCalendar(shifts, rangeStart, rangeEnd, tz)
- );
- windowsByEmployee.set(employeeId, unionWindows(lists));
- }
-
- // People with no shift assignment default to the job location's calendar
- // (plant hours, matching the default machine window) — not 24×7 — so
- // unconfigured labor degrades to non-constraining within plant hours.
- // Materialized here so absences/overtime can adjust it too.
- for (const employeeId of employeeIds) {
- if (!windowsByEmployee.has(employeeId)) {
- windowsByEmployee.set(employeeId, locationDefaultWindows);
- }
- }
-
- const timeZone = this.job?.timezone ?? "UTC";
-
- // Absences subtract the person's availability on those dates everywhere —
- // people-preferred and qualified-fallback paths alike
- const absentByEmployee = buildAbsencesByEmployee(absenceRows);
- for (const [employeeId, absentDates] of absentByEmployee) {
- const windows = windowsByEmployee.get(employeeId);
- if (windows) {
- windowsByEmployee.set(
- employeeId,
- subtractAbsences(windows, absentDates, timeZone)
- );
- }
- }
-
- // An absent person is never that day's people
- const presentPeopleRows = peopleRows.filter(
- (row) => !absentByEmployee.get(row.employeeId)?.has(row.date)
- );
- const peopleByWorkCenter = buildPeopleByWorkCenter(presentPeopleRows);
- // Inverted board (employee -> date -> stations) so the any-qualified
- // fallback can tell a manned person is committed elsewhere that day.
- const assignmentsByEmployee =
- buildAssignmentsByEmployee(peopleByWorkCenter);
-
- // Authorized overtime = a longer day: extend the person's last window on
- // each overtime date so the allocator can pack work into the extra hours
- const overtimeByEmployee = buildOvertimeByEmployee(presentPeopleRows);
- for (const [employeeId, overtimeByDate] of overtimeByEmployee) {
- const windows = windowsByEmployee.get(employeeId);
- if (windows) {
- windowsByEmployee.set(
- employeeId,
- extendWindowsByOvertime(windows, overtimeByDate, timeZone)
- );
- }
- }
-
- // Split days: each station only gets its budgeted share of the person
- const peopleBudgets = buildPeopleBudgets(presentPeopleRows);
-
- const employeesByAbility = new Map<string, PoolEmployee[]>();
- for (const e of employees) {
- const list = employeesByAbility.get(e.abilityId) ?? [];
- list.push({
- employeeId: e.employeeId,
- expiresAt: e.expiresAt,
- windows: windowsByEmployee.get(e.employeeId) ?? locationDefaultWindows
- });
- employeesByAbility.set(e.abilityId, list);
- }
-
- // Named-person bookings across ALL abilities, keyed by employee id.
- // Legacy OperatorPool rows are ignored deliberately: they can't be
- // attributed to a person, and they stop existing after each job's next
- // replan (the reactive stale-wave refreshes everything).
- const reservationsByEmployee = new Map<
- string,
- { startAt: number; endAt: number; readableJobId?: string }[]
- >();
- for (const r of liveReservations) {
- if (r.resourceKind !== "Employee") continue;
- const list = reservationsByEmployee.get(r.resourceId) ?? [];
- list.push({
- startAt: r.startAt,
- endAt: r.endAt,
- readableJobId: r.readableJobId
- });
- reservationsByEmployee.set(r.resourceId, list);
- }
-
- return {
- capacityByWorkCenter,
- requirementByProcess,
- employeesByAbility,
- reservationsByEmployee,
- peopleByWorkCenter,
- assignmentsByEmployee,
- requiresStaffing,
- peopleBudgets,
- windowsByEmployee,
+ const availability = await this.loadAvailabilityWindows();
+ return buildFiniteContext({
+ provider: this.provider,
+ operations: Array.from(this.scheduledOperations.values()),
dependencies: this.dependencies,
- now,
- horizonDays: SCHEDULING_HORIZON_DAYS,
- windowsEnd: rangeEnd,
- timeZone,
- operationsWithEvents
- };
+ availability,
+ locationId: this.job?.locationId ?? null,
+ timeZone: this.job?.timezone ?? "UTC",
+ now: this.now,
+ excludeJobIds: this.excludeJobIds
+ });
}
/**
diff --git a/packages/planning/src/scheduling/types.ts b/packages/planning/src/scheduling/types.ts
index 22bc7e9fb7..4811aff7a4 100644
--- a/packages/planning/src/scheduling/types.ts
+++ b/packages/planning/src/scheduling/types.ts
@@ -53,6 +53,12 @@ export type BaseOperation = {
* operation row; never read by forward placement.
*/
operationLeadTime?: number | null;
+ /**
+ * Earliest instant this op's material is available (epoch ms). Only set by
+ * the quote lead-time what-if for ops that consume a purchased part; never
+ * set on job operations, so live scheduling is unchanged.
+ */
+ materialReadyAt?: number;
/**
* Manufacturing lead time (in business days) of the make method's item that
* this operation belongs to. Applied only at assembly boundaries so a
diff --git a/packages/planning/src/scheduling/work-center-selector.test.ts b/packages/planning/src/scheduling/work-center-selector.test.ts
index 8035d99918..733c480c28 100644
--- a/packages/planning/src/scheduling/work-center-selector.test.ts
+++ b/packages/planning/src/scheduling/work-center-selector.test.ts
@@ -174,6 +174,53 @@ it("an untouched op books the full standard hours", async () => {
assertEquals(spanMs, 4 * 60 * 60 * 1000); // full 4h
});
+it("materialReadyAt floors the placement", async () => {
+ // Same fixture placed twice: an op WITHOUT the floor starts at now; the same
+ // op WITH materialReadyAt three days out starts no earlier than that floor.
+ const now = utc("2026-01-05T00:00:00.000Z"); // Monday
+ const floor = now + 3 * 24 * 3_600_000;
+
+ const baseOp = () =>
+ makeOp({
+ id: "op-1",
+ workCenterId: "wc1",
+ startDate: null,
+ dueDate: null,
+ setupTime: 0,
+ laborTime: 4,
+ laborUnit: "Total Hours" as const,
+ machineTime: 0,
+ operationQuantity: 10,
+ quantityComplete: 0
+ });
+
+ const unfloored = new WorkCenterSelector(
+ {} as unknown as MasterDataProvider,
+ "loc1"
+ );
+ unfloored.setFiniteContext(makeContext());
+ const unflooredSelections = await unfloored.selectWorkCentersForOperations(
+ [baseOp()],
+ { jobDueDate: null }
+ );
+ const unflooredSelection = unflooredSelections.get("op-1");
+ assert(unflooredSelection?.placedStart);
+ assertEquals(utc(unflooredSelection.placedStart), now);
+
+ const floored = new WorkCenterSelector(
+ {} as unknown as MasterDataProvider,
+ "loc1"
+ );
+ floored.setFiniteContext(makeContext());
+ const flooredSelections = await floored.selectWorkCentersForOperations(
+ [{ ...baseOp(), materialReadyAt: floor }],
+ { jobDueDate: null }
+ );
+ const flooredSelection = flooredSelections.get("op-1");
+ assert(flooredSelection?.placedStart);
+ assert(utc(flooredSelection.placedStart) >= floor);
+});
+
// --- load balancing across equivalent work centers --------------------------
it("two identical not-started ops spread across equivalent work centers", async () => {
diff --git a/packages/planning/src/scheduling/work-center-selector.ts b/packages/planning/src/scheduling/work-center-selector.ts
index 13baf8e47e..de731a8e29 100644
--- a/packages/planning/src/scheduling/work-center-selector.ts
+++ b/packages/planning/src/scheduling/work-center-selector.ts
@@ -442,6 +442,9 @@ export class WorkCenterSelector {
earliestMs = Math.max(earliestMs, depEnd);
}
}
+ if (op.materialReadyAt !== undefined) {
+ earliestMs = Math.max(earliestMs, op.materialReadyAt);
+ }
const start = earliestMs;
const outsideDurationHours =
op.durationHours ??
@@ -534,6 +537,10 @@ export class WorkCenterSelector {
dominantDepId = depId;
}
}
+ if (op.materialReadyAt !== undefined && op.materialReadyAt > earliestMs) {
+ earliestMs = op.materialReadyAt;
+ dominantDepId = null;
+ }
const earliestStart = earliestMs;
// Cap at the precomputed windows: walking past them finds nothing and
// would flag feasible far-future ops as capacity conflicts