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.
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
- Task 1: Add an optional
materialReadyAtfloor to finite placement - Task 2: Extract
buildFiniteContextintofinite-context.ts - Task 3: Pure quote-simulation builders + tests
- Task 4:
runQuoteLeadTimeWhatIforchestrator + package export (DB smoke deferred to Task 8 — stack not up) - Task 5: ERP route, validator and path
- Task 6:
QuoteLeadTimeModal+ button on the pricing grid - Task 7: Translations, docs
- Task 8: Browser verification — BLOCKED: no dev stack booted for this worktree
(no
.env.local; only shared postgres+redis up). Needscrbn 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 toBaseOperation - 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:
- In
types.ts, insideBaseOperation(L30-74) add, afteroperationLeadTime?:/** * 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;ScheduledOperationextendsBaseOperation(L120-137), so it inherits the field. - In
work-center-selector.ts, the regular-op earliest-start block (~L527-537,let earliestMs = ctx.now; let dominantDepId ...): after the dependency loop and beforeconst earliestStart = earliestMs;addif (op.materialReadyAt !== undefined && op.materialReadyAt > earliestMs) { earliestMs = op.materialReadyAt; dominantDepId = null; } - In the Outside Processing branch (~L419-445,
let earliestMs = ctx.now;followed by theop.startDateand dependency loop): after the dependency loop addif (op.materialReadyAt !== undefined) { earliestMs = Math.max(earliestMs, op.materialReadyAt); } - In
work-center-selector.test.ts, copy the smallest existing single-op placement test (the one around L112 that builds one op and assertsplacedStart) and add a test "materialReadyAt floors the placement": same fixture, setmaterialReadyAt = ctx.now + 3 * 24 * 3_600_000, assert the planned reservation'sstartAt >= 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:
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— delegateloadAvailabilityWindows(L558-616) andbuildFiniteContext(L673-897) to the new module
Steps:
- Create
finite-context.tsexporting:
Move the bodies verbatim from the engine. Replaceexport 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>;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) — exportSCHEDULING_HORIZON_DAYSfromfinite-context.tsand re-import it in the engine if it is currently defined in the engine (L81). - In the engine, keep the private methods as thin wrappers so no caller changes:
loadAvailabilityWindows()memoizes onthis.availabilityWindowsand calls the new function;buildFiniteContext()returnsnullwhenthis.workCenterSelectoris null, else awaits the windows and calls the new function. The need-by pass (computeNeedBys, L625) keeps usingthis.loadAvailabilityWindows(). - Do not change
selectWorkCenters()or anything after it.
Verify:
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.tscreateDependencies(L332-420) for the dependency walk;envelope.test.tsmakeOperations(L35-70) for hand-built ops in tests
Steps:
- Define the input row types (plain objects, already
Number()-coerced by the loader in Task 4):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 }; - Export the pure builder:
Algorithm: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 }- Root method = the one with
parentMaterialId === null. Multiplier of the root = 1. For every other method, itsparentMaterialIdnames aQuoteMaterialRow; 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", copyprocessId, workCenterId, order, operationOrder, operationType, description, setupTime/Unit, laborTime/Unit, machineTime/Unit, operationLeadTime. - Dependencies: per method
buildOperationDependencies(methodOps)(fromdependency-manager.ts); for each non-root method, add the edgeconsumingOp depends on lastOpOfChildwhere consumingOp = the parent material'squoteOperationId, else the parent method's lowest-orderop; skip when either side is missing. Convert withdependenciesToRecords(map, jobId, "")and drop thecompanyIdkey (the context only readsoperationId/dependsOnId/jobId), or build theJobOperationDependency[]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) ?? 7whenmethodType === "Purchase to Order", or whenmethodType === "Pull from Inventory"and(onHandByItem.get(itemId) ?? 0) < required; else none. Consuming op as above. Setop.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 withsetupTime === 0 && laborTime === 0 && machineTime === 0.
- Root method = the one with
- Export
cloneFiniteContext(ctx: FiniteSchedulingContext): FiniteSchedulingContext: newcapacityByWorkCenterMap whose values are{ ...data, reservations: [...data.reservations] }, newreservationsByEmployeeMap with copied arrays, every other property shared by reference. Add a comment citing the type's doc ("Reservation arrays are mutated in-run"). - Export the pure day math:
usingexport function calendarDaysFromNow(finishMs: number, nowMs: number, timeZone: string): number@internationalized/date:toCalendarDate(fromAbsolute(ms, timeZone))for both,days = finish.compare(today)(already an integer — no rounding call needed), returningdays < 1 ? 1 : days. - 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 haveoperationQuantity = 2 × quantityand the edgeconsumingOp ← child's last op; - no
quoteOperationIdon the material → edge goes to the parent's first op; Purchase to Ordermaterial with lead time 10 → consuming opmaterialReadyAt === now + 10 days,materialReadyDays === 10;Pull from Inventorywith 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").
- a root method with two ops "After Previous" → one dependency edge, quantities scale
(
Verify:
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—exportloadOrderedBatch(L73) - Modify:
packages/planning/src/index.ts— export the new entry point and types - Copy from (precedent):
run-schedule.tsrunExpediteWhatIf(L242-294)
Steps:
- Export the result types from the spec (
QuoteLeadTimeScenario,QuoteLeadTimeForecast) verbatim. - Add
loadQuoteLineRouting(db, quoteLineId, companyId)(module-private): three Kysely selects filtered byquoteLineIdANDcompanyId—quoteMakeMethod(id, parentMaterialId),quoteMaterial(id, quoteMakeMethodId, itemId, methodType, quantity, quoteOperationId),quoteOperation(the columns ofQuoteOperationRow). Coerce every numeric withNumber(...). Returnnullwhen there is no make method (aPull from Inventory/Purchase to Orderquote line has no routing). - 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 readmrp.ts:277uses). - Add the orchestrator:
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 useDatefor anything else).timeZone=db.selectFrom("location").select("timezone").where("id","=",locationId).where("companyId","=",companyId)→?? "UTC".routing = await loadQuoteLineRouting(...); returnnullif none.provider = new KyselyMasterDataProvider(db, client, companyId, { cacheCompanyData: true }).batch = await loadOrderedBatch(db, locationId, companyId).- Batch placements exactly as
runExpediteWhatIfdoes (placeReleasedBatcheswithpersist: 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: []) andbestCtx(excludeJobIds: batch);dependenciesfrom 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= maxtoInstantMs(selection.placedEnd)over selections andp.endAtoverselector.getPlannedReservations()(the same unionselectWorkCenters()computes, engine L930-945);cause= the first non-nullselection.conflict, else thescheduleNoteof the planned reservation with the largeststartAt − earliestStartAt, elsenull. One selector instance is reused for every run:selectWorkCentersForOperationsresetsthis.plannedReservations = []at its start (work-center-selector.ts:361), andsetFiniteContextswaps the context, so a clone per run is the only isolation needed. leadTimeDays = calendarDaysFromNow(finishMs, now, timeZone);finishAt = msToInstantIso(finishMs).targetwhendueDateis set:queuedFinishDate = businessDayFromMs(finishMs, timeZone)(the helperwork-center-selector.tsuses foroutsideEndDate), verdict"on-time"ifqueuedFinishDate <= 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 (readlocation.namein the same select astimezone).
run-schedule.ts: addexporttoloadOrderedBatch.index.ts: addexport { type QuoteLeadTimeForecast, type QuoteLeadTimeScenario, runQuoteLeadTimeWhatIf } from "./scheduling/quote-lead-time.ts";
Verify:
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— addquoteLeadTimeValidator - Modify:
apps/erp/app/utils/path.ts— addquoteLineLeadTimenext toquoteLineRecalculatePrice(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.tsxfor the quote-scoped reads
Steps:
sales.models.ts, nearselectedLineSchema(L1058):
Export it through the module barrel like the neighbours.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() });path.ts:quoteLineLeadTime: (quoteId: string, lineId: string) => generatePath(${x}/quote/${quoteId}/${lineId}/lead-time).- 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 returndata({ 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 viathrow 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 returndata({ 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.tsxdoes; 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.errorand returndata({ forecast: null, error: "Failed to predict lead time" }).
Verify:
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:
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):
JobExpediteModalinapps/erp/app/modules/production/ui/Jobs/JobHeader.tsx(L1163-1260) for the modal shell, loading state, "Bottleneck" alert; the pricing table itself (QuoteLinePricing.tsxL738-746) for the quantity-column table;apps/erp/app/modules/production/ui/Schedule/People/TimeOffDialog.tsxfor aDatePickerfrom@carbon/reactinside a dialog
Steps:
- Modal props:
Inside:{ quoteId: string; lineId: string; quantities: number[]; isEditable: boolean; onApply: (leadTimeByQuantity: Record<number, number>) => Promise<void>; onClose: () => void; }useFetcher<typeof action>()(import the action type from the route file); on mountfetcher.submit({ quantities }, { method: "post", encType: "application/json", action: path.to.quoteLineLeadTime(quoteId, lineId) }). Local stateconstraint: "queued" | "bestCase" | "target"(default"queued") andtargetDate: CalendarDate | null. Changing the target date resubmits withdueDate: date.toString(); the forecast for the other two constraints is already in the same response, so switching between them re-renders without a request. - Header: the constraint picker is
Tabs/TabsList/TabsTriggerfrom@carbon/react, copied from the view switcher inapps/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, aDatePickerfrom@carbon/react(precedentTimeOffDialog.tsx) appears beside it. - Body while loading: spinner + "Predicting lead time…" (copy the expedite modal's
118px block). On
error: the message in anAlert. Onforecast === nullwithout error: "This line has no routing to schedule." Otherwise ONETablewhose 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: theassumptionsas a muted<ul>; whenzeroStandardOperationCount > 0an extra muted line "N operations have no time standards". Numbers are shown plainly, never in parentheses.
- queued / bestCase: Quantity · Materials ("N days" or "—") · Finish
(
- Footer: "Apply to all quantities" (
isEditableonly; disabled while loading, while no forecast, under "target" with no date, or under "target" while any row's verdict is"late"— with aTooltip"One or more quantities cannot meet this date") and "Close". Apply builds{ [quantity]: leadTimeDays }for every row from the selected constraint, awaitsonApply(map), then callsonClose(). QuoteLinePricing.tsx: addonUpdateLeadTimesnext toonUpdatePrice(L495). It must NOT loop overonUpdatePrice— that callback snapshotseditableFields.pricesper call and replaces the whole map insetEditableFields, so a loop would keep only the last quantity's value in state. Implementation:
Then addconst 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] );const [leadTimeModalOpen, setLeadTimeModalOpen] = useState(false); on the Lead Time row headerHStack(L750-753) render, whenisEmployee && hasCalculatedCost, anIconButtonaria-label="Predict lead time"icon={<LuCalendarClock />}variant="ghost"size="sm"that opens the modal. Mount<QuoteLeadTimeModal … onApply={onUpdateLeadTimes} />when open, passingquantitiesandisEditable. Every string goes through Lingui (<Trans>/t\…``).
Verify:
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/*/*.povia/translate - Modify:
.claude/rules/scheduling-data-structures.md— under "Where it lives" addfinite-context.tsandquote-lead-time.ts(runQuoteLeadTimeWhatIf: synthetic ops through the pure selector; two contexts, queued vs front-of-queue;materialReadyAtfloor, 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 torunExpediteWhatIf - 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 throughonUpdateLeadTimes
Steps:
- Run
pnpm lingui:extract(or the command.claude/rules/i18n-lingui-system.mdnames), then/translate. - Make the three doc edits above; keep each under ten lines.
Verify:
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:
crbn up;pnpm --filter @carbon/jobs dev:jobsis not needed (no Inngest path)./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.- 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.
- 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".
- 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). - 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.