import type { DemandPlanningRollupDto, GanttTaskDto, PlanningExceptionDto, PlanningTimelineDto } from "@mrp/shared"; import { useEffect, useMemo, useState } from "react"; import { Link } from "react-router-dom"; import { useAuth } from "../../auth/AuthProvider"; import { ApiError, api } from "../../lib/api"; type WorkbenchMode = "overview" | "heatmap" | "agenda"; type FocusRecord = { id: string; title: string; kind: "PROJECT" | "WORK_ORDER" | "OPERATION" | "MILESTONE"; status: string; ownerLabel: string | null; start: string; end: string; progress: number; detailHref: string | null; parentId: string | null; }; type HeatmapCell = { dateKey: string; count: number; lateCount: number; blockedCount: number; tasks: FocusRecord[]; }; const DAY_MS = 24 * 60 * 60 * 1000; function formatDate(value: string | null, options?: Intl.DateTimeFormatOptions) { if (!value) { return "Unscheduled"; } return new Intl.DateTimeFormat("en-US", options ?? { month: "short", day: "numeric", }).format(new Date(value)); } function startOfDay(value: Date) { return new Date(value.getFullYear(), value.getMonth(), value.getDate()); } function dateKey(value: Date) { return value.toISOString().slice(0, 10); } function parseFocusKind(task: GanttTaskDto): FocusRecord["kind"] { if (task.type === "project") { return "PROJECT"; } if (task.type === "milestone") { return "MILESTONE"; } if (task.id.startsWith("work-order-operation-")) { return "OPERATION"; } return "WORK_ORDER"; } function densityTone(cell: HeatmapCell) { if (cell.lateCount > 0) { return "border-rose-400/60 bg-rose-500/25"; } if (cell.blockedCount > 0) { return "border-amber-300/60 bg-amber-400/25"; } if (cell.count >= 4) { return "border-brand/80 bg-brand/35"; } if (cell.count >= 2) { return "border-brand/50 bg-brand/20"; } if (cell.count === 1) { return "border-line/80 bg-page/80"; } return "border-line/60 bg-surface/70"; } function buildFocusRecords(tasks: GanttTaskDto[]) { return tasks.map((task) => ({ id: task.id, title: task.text, kind: parseFocusKind(task), status: task.status ?? "PLANNED", ownerLabel: task.ownerLabel ?? null, start: task.start, end: task.end, progress: task.progress, detailHref: task.detailHref ?? null, parentId: task.parentId ?? null, })); } export function WorkbenchPage() { const { token } = useAuth(); const [timeline, setTimeline] = useState(null); const [planningRollup, setPlanningRollup] = useState(null); const [status, setStatus] = useState("Loading live planning timeline..."); const [workbenchMode, setWorkbenchMode] = useState("overview"); const [selectedFocusId, setSelectedFocusId] = useState(null); const [selectedHeatmapDate, setSelectedHeatmapDate] = useState(null); useEffect(() => { if (!token) { return; } Promise.all([api.getPlanningTimeline(token), api.getDemandPlanningRollup(token)]) .then(([data, rollup]) => { setTimeline(data); setPlanningRollup(rollup); setStatus("Planning workbench loaded."); }) .catch((error: unknown) => { const message = error instanceof ApiError ? error.message : "Unable to load planning timeline."; setStatus(message); }); }, [token]); const tasks = timeline?.tasks ?? []; const summary = timeline?.summary; const exceptions = timeline?.exceptions ?? []; const focusRecords = useMemo(() => buildFocusRecords(tasks), [tasks]); const focusById = useMemo(() => new Map(focusRecords.map((record) => [record.id, record])), [focusRecords]); const selectedFocus = selectedFocusId ? focusById.get(selectedFocusId) ?? null : focusRecords[0] ?? null; const heatmap = useMemo(() => { const start = summary ? startOfDay(new Date(summary.horizonStart)) : startOfDay(new Date()); const cells = new Map(); for (let index = 0; index < 84; index += 1) { const nextDate = new Date(start.getTime() + index * DAY_MS); cells.set(dateKey(nextDate), { dateKey: dateKey(nextDate), count: 0, lateCount: 0, blockedCount: 0, tasks: [] }); } for (const record of focusRecords) { if (record.kind === "PROJECT") { continue; } const startDate = startOfDay(new Date(record.start)); const endDate = startOfDay(new Date(record.end)); for (let cursor = startDate.getTime(); cursor <= endDate.getTime(); cursor += DAY_MS) { const key = dateKey(new Date(cursor)); const current = cells.get(key); if (!current) { continue; } current.count += 1; if (record.status === "AT_RISK" || record.status === "ON_HOLD") { current.blockedCount += 1; } if (new Date(record.end).getTime() < Date.now() && record.status !== "COMPLETE" && record.status !== "CANCELLED") { current.lateCount += 1; } current.tasks.push(record); } } return [...cells.values()]; }, [focusRecords, summary]); const selectedHeatmapCell = selectedHeatmapDate ? heatmap.find((cell) => cell.dateKey === selectedHeatmapDate) ?? null : null; const agendaItems = useMemo( () => [...focusRecords] .filter((record) => record.kind !== "OPERATION") .sort((left, right) => new Date(left.end).getTime() - new Date(right.end).getTime()) .slice(0, 18), [focusRecords] ); const modeOptions: Array<{ value: WorkbenchMode; label: string; detail: string }> = [ { value: "overview", label: "Overview", detail: "Dense planner board" }, { value: "heatmap", label: "Heatmap", detail: "Load by day" }, { value: "agenda", label: "Agenda", detail: "Upcoming due flow" }, ]; return (

Planning

Planning Workbench

A reactive planning surface for projects, work orders, operations, shortages, and schedule risk. Use it as the daily planner cockpit, not just a chart.

Workbench Status
{status}
{modeOptions.map((option) => ( ))}
{workbenchMode === "overview" ? : null} {workbenchMode === "heatmap" ? : null} {workbenchMode === "agenda" ? : null}
); } function MetricCard({ label, value }: { label: string; value: string | number }) { return (

{label}

{value}
); } function OverviewBoard({ focusRecords, onSelect }: { focusRecords: FocusRecord[]; onSelect: (id: string) => void }) { const projects = focusRecords.filter((record) => record.kind === "PROJECT").slice(0, 6); const operations = focusRecords.filter((record) => record.kind === "OPERATION").slice(0, 10); const workOrders = focusRecords.filter((record) => record.kind === "WORK_ORDER").slice(0, 10); return (

Overview

Scan project rollups, active work, and operation load without leaving the planner.

Program Queue

{projects.map((record) => ( ))}

Operation Load

{operations.map((record) => ( ))}

Active Work Orders

{workOrders.map((record) => ( ))}
); } function HeatmapBoard({ heatmap, selectedDate, onSelectDate }: { heatmap: HeatmapCell[]; selectedDate: string | null; onSelectDate: (date: string) => void }) { const weeks = []; for (let index = 0; index < heatmap.length; index += 7) { weeks.push(heatmap.slice(index, index + 7)); } return (

Load Heatmap

Dense daily load scan for operations and work orders, with late and blocked pressure highlighted.

{["M", "T", "W", "T", "F", "S", "S"].map((label) =>
{label}
)}
{weeks.map((week, weekIndex) => (
{formatDate(week[0]?.dateKey ?? null, { month: "short" })}
{week.map((cell) => ( ))}
))}
); } function AgendaBoard({ records, onSelect, compact = false }: { records: FocusRecord[]; onSelect: (id: string) => void; compact?: boolean }) { return (
{!compact ? (

Agenda

Upcoming projects, work orders, and milestones ordered by due date.

) : null}
{records.map((record) => ( ))}
); } function SelectedDayPanel({ cell, onSelect }: { cell: HeatmapCell; onSelect: (id: string) => void }) { return (
{formatDate(cell.dateKey, { weekday: "short", month: "short", day: "numeric" })}
{cell.count} scheduled {cell.lateCount} late
{cell.tasks.slice(0, 8).map((task) => ( ))}
); }