mirror of
https://github.com/Sea-Haven-Industries/shoc-frontend-new.git
synced 2026-09-30 08:03:13 +00:00
feat(dashboard): build dashboard experience (SH-336)
This commit is contained in:
parent
07734d8361
commit
1b17cbec01
39 changed files with 2068 additions and 493 deletions
|
|
@ -148,6 +148,11 @@ export const API_PATHS = {
|
|||
},
|
||||
dashboard: {
|
||||
stats: "Dashboard/Stats",
|
||||
workload: "Dashboard/Workload",
|
||||
performance: "Dashboard/Performance",
|
||||
regions: "Dashboard/Regions",
|
||||
vendorInsights: "Dashboard/VendorInsights",
|
||||
trend: "Dashboard/Trend",
|
||||
},
|
||||
dropdownOptions: {
|
||||
byCategory: "DropdownOptions/ByCategory",
|
||||
|
|
|
|||
|
|
@ -1,240 +0,0 @@
|
|||
import type { ReactNode } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutlined";
|
||||
import FolderOpenOutlinedIcon from "@mui/icons-material/FolderOpenOutlined";
|
||||
import ScheduleOutlinedIcon from "@mui/icons-material/ScheduleOutlined";
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
CircularProgress,
|
||||
Paper,
|
||||
Stack,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useDashboardStats } from "@/domain/dashboard/use-cases/use-dashboard-stats";
|
||||
|
||||
const INVOICE_STATUSES = ["Draft", "Challenged", "Pending Approval", "Approved", "Paid"] as const;
|
||||
|
||||
const PRIORITY_LEVELS = [5, 4, 3, 2, 1] as const;
|
||||
|
||||
interface KpiCardProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
value?: string | number;
|
||||
icon: ReactNode;
|
||||
color: "success" | "primary" | "info" | "warning";
|
||||
onClick: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
function KpiCard({ title, description, value, icon, color, onClick, loading }: KpiCardProps) {
|
||||
const colorMap = {
|
||||
success: "success.main",
|
||||
primary: "primary.main",
|
||||
info: "info.main",
|
||||
warning: "warning.main",
|
||||
} as const;
|
||||
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
onClick={onClick}
|
||||
className="flex min-h-[140px] flex-1 cursor-pointer transition-shadow hover:shadow-md"
|
||||
sx={{
|
||||
borderLeftWidth: 4,
|
||||
borderLeftStyle: "solid",
|
||||
borderLeftColor: colorMap[color],
|
||||
}}
|
||||
>
|
||||
<Box className="flex w-full gap-4 p-4">
|
||||
<Box
|
||||
className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full"
|
||||
sx={{ bgcolor: `${colorMap[color]}22`, color: colorMap[color] }}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
|
||||
<Box className="flex min-w-0 flex-col justify-center gap-1">
|
||||
<Typography variant="subtitle1" className="font-semibold">
|
||||
{title}
|
||||
</Typography>
|
||||
{value !== undefined && (
|
||||
<Typography variant="h4" component="p" className="font-bold leading-tight">
|
||||
{loading ? "..." : typeof value === "number" ? value.toLocaleString() : value}
|
||||
</Typography>
|
||||
)}
|
||||
{Boolean(description) && (
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
color: "text.secondary",
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const navigate = useNavigate();
|
||||
const { data: stats, isLoading, isFetching, error } = useDashboardStats();
|
||||
|
||||
const formatStat = (value: number | undefined) => (isLoading ? undefined : (value ?? 0));
|
||||
|
||||
return (
|
||||
<Box className="flex flex-col gap-4 p-4">
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={2}
|
||||
sx={{
|
||||
alignItems: "baseline",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h5" component="h1">
|
||||
Dashboard
|
||||
</Typography>
|
||||
{isFetching && !isLoading && <CircularProgress size={16} />}
|
||||
</Stack>
|
||||
{Boolean(error) && (
|
||||
<Alert severity="error">
|
||||
{error instanceof Error ? error.message : "Failed to load dashboard stats"}
|
||||
</Alert>
|
||||
)}
|
||||
<Stack
|
||||
direction={{ xs: "column", lg: "row" }}
|
||||
spacing={2}
|
||||
useFlexGap
|
||||
sx={{
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<KpiCard
|
||||
title="Create a Work Order"
|
||||
description="Report a problem you need fixed"
|
||||
icon={<AddIcon />}
|
||||
color="success"
|
||||
onClick={() => navigate("/workorders/new")}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Open Work Orders"
|
||||
value={formatStat(stats?.open)}
|
||||
icon={<FolderOpenOutlinedIcon />}
|
||||
color="primary"
|
||||
loading={isLoading}
|
||||
onClick={() => navigate("/workorders")}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Not Dispatched"
|
||||
value={formatStat(stats?.notDispatched)}
|
||||
icon={<ScheduleOutlinedIcon />}
|
||||
color="info"
|
||||
loading={isLoading}
|
||||
onClick={() => navigate("/workorders")}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Completed Orders"
|
||||
value={formatStat(stats?.completed)}
|
||||
icon={<CheckCircleOutlineIcon />}
|
||||
color="warning"
|
||||
loading={isLoading}
|
||||
onClick={() => navigate("/workorders")}
|
||||
/>
|
||||
</Stack>
|
||||
<Paper variant="outlined" className="overflow-hidden">
|
||||
<Box className="border-b border-border px-4 py-3">
|
||||
<Typography variant="h6" component="h2">
|
||||
Priority Analysis
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
color: "text.secondary",
|
||||
}}
|
||||
>
|
||||
Age of open Work Orders by Priority
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Priority</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Total
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
0-14 Days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
15-29 Days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
30-59 Days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
60+ Days
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{PRIORITY_LEVELS.map((priority) => (
|
||||
<TableRow key={priority}>
|
||||
<TableCell>{priority}</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</Paper>
|
||||
<Paper variant="outlined" className="overflow-hidden">
|
||||
<Box className="border-b border-border px-4 py-3">
|
||||
<Typography variant="h6" component="h2">
|
||||
Invoice Analysis
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Status</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Count
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Amount
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{INVOICE_STATUSES.map((status) => (
|
||||
<TableRow key={status}>
|
||||
<TableCell>{status}</TableCell>
|
||||
<TableCell align="right">0</TableCell>
|
||||
<TableCell align="right">$0.00</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import { Box, ButtonBase } from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
|
||||
export interface DashboardBarListRow {
|
||||
id: string;
|
||||
label: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface DashboardBarListProps {
|
||||
rows: DashboardBarListRow[];
|
||||
onSelectRow?: (row: DashboardBarListRow) => void;
|
||||
isSelectable?: (row: DashboardBarListRow) => boolean;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
function percentOf(count: number, max: number): number {
|
||||
if (max <= 0 || count <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.round((count / max) * 100);
|
||||
}
|
||||
|
||||
function BarListRow({ row, width }: { row: DashboardBarListRow; width: number }) {
|
||||
return (
|
||||
<Box className="flex w-full flex-col gap-1 py-1.5">
|
||||
<Box className="flex items-baseline justify-between gap-2">
|
||||
<Text variant="description" className="truncate">
|
||||
{row.label}
|
||||
</Text>
|
||||
<Text variant="description" tone="muted">
|
||||
{row.count.toLocaleString()}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box className="h-2 w-full overflow-hidden rounded-full" sx={{ bgcolor: "action.hover" }}>
|
||||
{width > 0 && (
|
||||
<Box
|
||||
data-testid="dashboard-bar-mark"
|
||||
className="h-full rounded-full"
|
||||
sx={{ width: `${width}%`, bgcolor: "primary.main" }}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function DashboardBarList({
|
||||
rows,
|
||||
onSelectRow,
|
||||
isSelectable,
|
||||
ariaLabel,
|
||||
}: DashboardBarListProps) {
|
||||
const max = Math.max(...rows.map((row) => row.count), 0);
|
||||
|
||||
return (
|
||||
<Box aria-label={ariaLabel} className="flex flex-col">
|
||||
{rows.map((row) => {
|
||||
const width = percentOf(row.count, max);
|
||||
const selectable = Boolean(onSelectRow) && row.count > 0 && (isSelectable?.(row) ?? true);
|
||||
|
||||
return selectable ? (
|
||||
<ButtonBase
|
||||
key={row.id}
|
||||
onClick={() => onSelectRow?.(row)}
|
||||
sx={{
|
||||
width: "100%",
|
||||
textAlign: "left",
|
||||
borderRadius: 1,
|
||||
px: 1,
|
||||
mx: -1,
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
<BarListRow row={row} width={width} />
|
||||
</ButtonBase>
|
||||
) : (
|
||||
<Box key={row.id} sx={{ px: 1, mx: -1 }}>
|
||||
<BarListRow row={row} width={width} />
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
44
src/app/(protected)/dashboard/_components/dashboard-card.tsx
Normal file
44
src/app/(protected)/dashboard/_components/dashboard-card.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import type { ReactNode } from "react";
|
||||
import { Box, CircularProgress, Paper } from "@mui/material";
|
||||
import { QueryErrorPanel } from "@/components/ui/query-error-panel";
|
||||
import { Text } from "@/components/ui/text";
|
||||
|
||||
interface DashboardCardProps {
|
||||
title: string;
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
isEmpty: boolean;
|
||||
emptyMessage: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function DashboardCard({
|
||||
title,
|
||||
isLoading = false,
|
||||
error,
|
||||
isEmpty,
|
||||
emptyMessage,
|
||||
children,
|
||||
}: DashboardCardProps) {
|
||||
return (
|
||||
<Paper variant="outlined" className="flex flex-col overflow-hidden">
|
||||
<Box className="border-b border-border px-4 py-3">
|
||||
<Text variant="heading">{title}</Text>
|
||||
</Box>
|
||||
{isLoading && (
|
||||
<Box className="flex items-center justify-center p-8">
|
||||
<CircularProgress size={24} />
|
||||
</Box>
|
||||
)}
|
||||
{!isLoading && Boolean(error) && <QueryErrorPanel compact className="m-4" />}
|
||||
{!isLoading && !error && isEmpty && (
|
||||
<Box className="p-6">
|
||||
<Text variant="description" tone="muted">
|
||||
{emptyMessage}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
{!isLoading && !error && !isEmpty && <Box className="p-4">{children}</Box>}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import type { ReactNode } from "react";
|
||||
import { Box, ButtonBase, Paper } from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
|
||||
type KpiTone = "success" | "primary" | "info" | "warning";
|
||||
|
||||
const toneColor: Record<KpiTone, string> = {
|
||||
success: "success.main",
|
||||
primary: "primary.main",
|
||||
info: "info.main",
|
||||
warning: "warning.main",
|
||||
};
|
||||
|
||||
interface DashboardKpiCardProps {
|
||||
title: string;
|
||||
value?: number;
|
||||
icon: ReactNode;
|
||||
tone: KpiTone;
|
||||
loading?: boolean;
|
||||
active?: boolean;
|
||||
onSelect?: () => void;
|
||||
}
|
||||
|
||||
export function DashboardKpiCard({
|
||||
title,
|
||||
value,
|
||||
icon,
|
||||
tone,
|
||||
loading = false,
|
||||
active = false,
|
||||
onSelect,
|
||||
}: DashboardKpiCardProps) {
|
||||
const color = toneColor[tone];
|
||||
const content = (
|
||||
<Box className="flex w-full items-center gap-4 p-4" sx={{ textAlign: "left" }}>
|
||||
<Box
|
||||
className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full"
|
||||
sx={{ bgcolor: `${color}22`, color }}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
<Box className="flex min-w-0 flex-col gap-0.5">
|
||||
<Text variant="label" tone="muted">
|
||||
{title}
|
||||
</Text>
|
||||
<Text variant="label" sx={{ fontSize: 28, fontWeight: 700, lineHeight: 1.2 }}>
|
||||
{loading ? "…" : (value ?? 0).toLocaleString()}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
className="min-h-[104px]"
|
||||
sx={{ borderLeftWidth: 4, borderLeftStyle: "solid", borderLeftColor: color }}
|
||||
>
|
||||
{active && Boolean(onSelect) ? (
|
||||
<ButtonBase sx={{ width: "100%", cursor: "pointer" }} onClick={onSelect}>
|
||||
{content}
|
||||
</ButtonBase>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import { ToggleButton, ToggleButtonGroup } from "@mui/material";
|
||||
import { DASHBOARD_RANGES, type DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
|
||||
const RANGE_LABELS: Record<DashboardRangeKey, string> = {
|
||||
"this-week": "This week",
|
||||
"last-3-months": "Last 3 months",
|
||||
today: "Today",
|
||||
"all-time": "All time",
|
||||
};
|
||||
|
||||
interface DashboardRangeToggleProps {
|
||||
value: DashboardRangeKey;
|
||||
onChange: (value: DashboardRangeKey) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function DashboardRangeToggle({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
}: DashboardRangeToggleProps) {
|
||||
return (
|
||||
<ToggleButtonGroup
|
||||
exclusive
|
||||
size="small"
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
aria-label="Dashboard date range"
|
||||
onChange={(_, next: DashboardRangeKey | null) => {
|
||||
if (next) {
|
||||
onChange(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{DASHBOARD_RANGES.map((range) => (
|
||||
<ToggleButton key={range} value={range}>
|
||||
{RANGE_LABELS[range]}
|
||||
</ToggleButton>
|
||||
))}
|
||||
</ToggleButtonGroup>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
import { useMemo, useState } from "react";
|
||||
import { Box, IconButton } from "@mui/material";
|
||||
import ArrowBackOutlinedIcon from "@mui/icons-material/ArrowBackOutlined";
|
||||
import ArrowForwardOutlinedIcon from "@mui/icons-material/ArrowForwardOutlined";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type { DashboardTrendPoint } from "@/domain/dashboard/types/dashboard-trend";
|
||||
import { useDashboardTrend } from "@/domain/dashboard/use-cases/use-dashboard-trend";
|
||||
import {
|
||||
businessTodayIso,
|
||||
dashboardRangeParams,
|
||||
} from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
import { DashboardCard } from "./dashboard-card";
|
||||
|
||||
interface DashboardTrendCardProps {
|
||||
range: DashboardRangeKey;
|
||||
}
|
||||
|
||||
function trendParams(range: DashboardRangeKey, year: number) {
|
||||
if (range === "all-time") return { year };
|
||||
const params = dashboardRangeParams(range);
|
||||
return {
|
||||
...params,
|
||||
...(range === "last-3-months" ? { range: "3m" as const } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function barHeight(point: DashboardTrendPoint, max: number): number {
|
||||
if (point.total <= 0 || max <= 0) return 0;
|
||||
return Math.max(6, Math.round((point.total / max) * 100));
|
||||
}
|
||||
|
||||
function TrendBar({ point, max }: { point: DashboardTrendPoint; max: number }) {
|
||||
const height = barHeight(point, max);
|
||||
return (
|
||||
<Box
|
||||
className="flex min-w-[42px] flex-1 flex-col items-center gap-1"
|
||||
data-testid="dashboard-trend-point"
|
||||
sx={{ borderLeft: point.isCurrent ? "2px dashed" : undefined, borderColor: "warning.main" }}
|
||||
>
|
||||
<Text variant="description" tone="muted">
|
||||
{point.total.toLocaleString()}
|
||||
</Text>
|
||||
<Box className="flex h-32 items-end">
|
||||
{height > 0 && (
|
||||
<Box
|
||||
data-testid="dashboard-trend-bar"
|
||||
className="w-6 rounded-t"
|
||||
sx={{
|
||||
height: `${height}%`,
|
||||
bgcolor: point.isCurrent ? "warning.main" : "primary.main",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Text variant="description" className="max-w-16 truncate text-center" title={point.label}>
|
||||
{point.label}
|
||||
</Text>
|
||||
{point.isCurrent && <Text variant="description">Today</Text>}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function DashboardTrendCard({ range }: DashboardTrendCardProps) {
|
||||
const currentYear = Number(businessTodayIso().slice(0, 4));
|
||||
const [year, setYear] = useState(currentYear);
|
||||
const params = useMemo(() => trendParams(range, year), [range, year]);
|
||||
const trend = useDashboardTrend(params);
|
||||
const points = trend.data?.points ?? [];
|
||||
const max = Math.max(...points.map((point) => point.total), 0);
|
||||
|
||||
return (
|
||||
<DashboardCard
|
||||
title="Work Order Trend"
|
||||
isLoading={trend.isLoading}
|
||||
error={trend.error}
|
||||
isEmpty={!trend.isLoading && !trend.error && points.length === 0}
|
||||
emptyMessage="No work orders match the current filters."
|
||||
>
|
||||
<Box className="flex flex-col gap-3">
|
||||
<Box className="flex items-center justify-between">
|
||||
<Text variant="description" tone="muted">
|
||||
{trend.data?.granularity ? `${trend.data.granularity} buckets` : "Trend"}
|
||||
</Text>
|
||||
{range === "all-time" && (
|
||||
<Box className="flex items-center">
|
||||
<IconButton
|
||||
aria-label="Previous year"
|
||||
size="small"
|
||||
onClick={() => setYear((value) => value - 1)}
|
||||
>
|
||||
<ArrowBackOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<Text variant="description">{year}</Text>
|
||||
<IconButton
|
||||
aria-label="Next year"
|
||||
size="small"
|
||||
onClick={() => setYear((value) => value + 1)}
|
||||
>
|
||||
<ArrowForwardOutlinedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<Box
|
||||
className="flex min-h-48 items-end gap-1 overflow-x-auto pb-1"
|
||||
aria-label="Work Order Trend chart"
|
||||
>
|
||||
{points.map((point) => (
|
||||
<TrendBar key={`${point.date}-${point.label}`} point={point} max={max} />
|
||||
))}
|
||||
</Box>
|
||||
<Text variant="description" tone="muted">
|
||||
The dashed marker and “Today” label identify the current business date.
|
||||
</Text>
|
||||
</Box>
|
||||
</DashboardCard>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import { useNavigate } from "react-router";
|
||||
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type { DispatcherPerformanceRow } from "@/domain/dashboard/types/dashboard-performance";
|
||||
import {
|
||||
workOrderDispatcherDrilldownSearch,
|
||||
workOrderDrilldownUrl,
|
||||
} from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
import { DashboardCard } from "./dashboard-card";
|
||||
|
||||
const EMPTY_MESSAGE = "No dispatchers are set up yet.";
|
||||
|
||||
interface DispatcherPerformanceCardProps {
|
||||
rows: DispatcherPerformanceRow[];
|
||||
range: DashboardRangeKey;
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
function formatDays(value: number): string {
|
||||
return (Math.round(value * 10) / 10).toLocaleString();
|
||||
}
|
||||
|
||||
function DispatcherNameCell({
|
||||
row,
|
||||
range,
|
||||
}: {
|
||||
row: DispatcherPerformanceRow;
|
||||
range: DashboardRangeKey;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const drillable = Boolean(row.dispatcherId) && row.completionRate > 0;
|
||||
|
||||
if (!drillable) {
|
||||
return <Text variant="description">{row.dispatcherName}</Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Text
|
||||
variant="description"
|
||||
as="button"
|
||||
className="cursor-pointer text-left font-medium underline-offset-2 hover:underline"
|
||||
onClick={() =>
|
||||
navigate(workOrderDrilldownUrl(workOrderDispatcherDrilldownSearch(row.dispatcherId, range)))
|
||||
}
|
||||
>
|
||||
{row.dispatcherName}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export function DispatcherPerformanceCard({
|
||||
rows,
|
||||
range,
|
||||
isLoading = false,
|
||||
error,
|
||||
}: DispatcherPerformanceCardProps) {
|
||||
return (
|
||||
<DashboardCard
|
||||
title="Dispatcher Performance"
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
isEmpty={!isLoading && !error && rows.length === 0}
|
||||
emptyMessage={EMPTY_MESSAGE}
|
||||
>
|
||||
<TableContainer>
|
||||
<Table size="small" aria-label="Dispatcher Performance">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Dispatcher</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Completion %
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Avg days
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((row) => (
|
||||
<TableRow key={row.dispatcherId || row.dispatcherName}>
|
||||
<TableCell>
|
||||
<DispatcherNameCell row={row} range={range} />
|
||||
</TableCell>
|
||||
<TableCell align="right">{`${row.completionRate.toLocaleString()}%`}</TableCell>
|
||||
<TableCell align="right">
|
||||
{row.averageResolutionDays == null ? "—" : formatDays(row.averageResolutionDays)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</DashboardCard>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import { useNavigate } from "react-router";
|
||||
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type { DispatcherWorkloadRow } from "@/domain/dashboard/types/dashboard-workload";
|
||||
import {
|
||||
workOrderDispatcherDrilldownSearch,
|
||||
workOrderDrilldownUrl,
|
||||
} from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
import { DashboardCard } from "./dashboard-card";
|
||||
|
||||
const EMPTY_MESSAGE = "No dispatchers are set up yet.";
|
||||
|
||||
interface DispatcherWorkloadCardProps {
|
||||
rows: DispatcherWorkloadRow[];
|
||||
range: DashboardRangeKey;
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
function DispatcherNameCell({
|
||||
row,
|
||||
range,
|
||||
}: {
|
||||
row: DispatcherWorkloadRow;
|
||||
range: DashboardRangeKey;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const drillable = Boolean(row.dispatcherId) && row.totalWorkOrders > 0;
|
||||
|
||||
if (!drillable) {
|
||||
return <Text variant="description">{row.dispatcherName}</Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Text
|
||||
variant="description"
|
||||
as="button"
|
||||
className="cursor-pointer text-left font-medium underline-offset-2 hover:underline"
|
||||
onClick={() =>
|
||||
navigate(workOrderDrilldownUrl(workOrderDispatcherDrilldownSearch(row.dispatcherId, range)))
|
||||
}
|
||||
>
|
||||
{row.dispatcherName}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export function DispatcherWorkloadCard({
|
||||
rows,
|
||||
range,
|
||||
isLoading = false,
|
||||
error,
|
||||
}: DispatcherWorkloadCardProps) {
|
||||
return (
|
||||
<DashboardCard
|
||||
title="Dispatcher Workload"
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
isEmpty={!isLoading && !error && rows.length === 0}
|
||||
emptyMessage={EMPTY_MESSAGE}
|
||||
>
|
||||
<TableContainer>
|
||||
<Table size="small" aria-label="Dispatcher Workload">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Dispatcher</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Open
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Total
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((row) => (
|
||||
<TableRow key={row.dispatcherId || row.dispatcherName}>
|
||||
<TableCell>
|
||||
<DispatcherNameCell row={row} range={range} />
|
||||
</TableCell>
|
||||
<TableCell align="right">{row.openWorkOrders.toLocaleString()}</TableCell>
|
||||
<TableCell align="right">{row.totalWorkOrders.toLocaleString()}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</DashboardCard>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import type { VendorInsightRow } from "@/domain/dashboard/types/dashboard-vendor-insights";
|
||||
import { DashboardCard } from "./dashboard-card";
|
||||
|
||||
const EMPTY_MESSAGE = "No active vendor has any work orders yet.";
|
||||
|
||||
interface VendorInsightsCardProps {
|
||||
rows: VendorInsightRow[];
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
export function VendorInsightsCard({ rows, isLoading = false, error }: VendorInsightsCardProps) {
|
||||
return (
|
||||
<DashboardCard
|
||||
title="Vendor Insights"
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
isEmpty={!isLoading && !error && rows.length === 0}
|
||||
emptyMessage={EMPTY_MESSAGE}
|
||||
>
|
||||
<TableContainer>
|
||||
<Table size="small" aria-label="Vendor Insights">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Vendor</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Completion %
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Reschedule %
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Avg days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Jobs
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((row) => (
|
||||
<TableRow key={row.vendorId || row.vendorName}>
|
||||
<TableCell>
|
||||
<Text variant="description">{row.vendorName}</Text>
|
||||
</TableCell>
|
||||
<TableCell align="right">{`${row.completionRate.toLocaleString()}%`}</TableCell>
|
||||
<TableCell align="right">{`${row.rescheduleRate.toLocaleString()}%`}</TableCell>
|
||||
<TableCell align="right">
|
||||
{row.averageResolutionDays == null
|
||||
? "—"
|
||||
: row.averageResolutionDays.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell align="right">{row.totalJobs.toLocaleString()}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</DashboardCard>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { useNavigate } from "react-router";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type { DashboardBreakdownRow } from "@/domain/dashboard/types/dashboard-stats";
|
||||
import {
|
||||
workOrderDrilldownUrl,
|
||||
workOrderTypeDrilldownSearch,
|
||||
} from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
import { DashboardBarList } from "./dashboard-bar-list";
|
||||
import { DashboardCard } from "./dashboard-card";
|
||||
|
||||
const EMPTY_MESSAGE = "No work orders match the current filters.";
|
||||
|
||||
interface WorkOrderBreakdownCardProps {
|
||||
breakdown: DashboardBreakdownRow[];
|
||||
range: DashboardRangeKey;
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
export function WorkOrderBreakdownCard({
|
||||
breakdown,
|
||||
range,
|
||||
isLoading = false,
|
||||
error,
|
||||
}: WorkOrderBreakdownCardProps) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<DashboardCard
|
||||
title="Work Order Breakdown"
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
isEmpty={!isLoading && !error && breakdown.length === 0}
|
||||
emptyMessage={EMPTY_MESSAGE}
|
||||
>
|
||||
<DashboardBarList
|
||||
ariaLabel="Work Order Breakdown"
|
||||
rows={breakdown.map((row) => ({ id: row.status, label: row.status, count: row.count }))}
|
||||
isSelectable={(row) => workOrderTypeDrilldownSearch(row.id, range) !== null}
|
||||
onSelectRow={(row) => {
|
||||
const search = workOrderTypeDrilldownSearch(row.id, range);
|
||||
if (search) navigate(workOrderDrilldownUrl(search));
|
||||
}}
|
||||
/>
|
||||
</DashboardCard>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import type { RegionWorkOrdersRow } from "@/domain/dashboard/types/dashboard-regions";
|
||||
import { DashboardBarList } from "./dashboard-bar-list";
|
||||
import { DashboardCard } from "./dashboard-card";
|
||||
|
||||
const EMPTY_MESSAGE = "No work orders match the current filters.";
|
||||
|
||||
interface WorkOrdersByRegionCardProps {
|
||||
rows: RegionWorkOrdersRow[];
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
export function WorkOrdersByRegionCard({
|
||||
rows,
|
||||
isLoading = false,
|
||||
error,
|
||||
}: WorkOrdersByRegionCardProps) {
|
||||
return (
|
||||
<DashboardCard
|
||||
title="Work Orders by Region"
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
isEmpty={!isLoading && !error && rows.length === 0}
|
||||
emptyMessage={EMPTY_MESSAGE}
|
||||
>
|
||||
<DashboardBarList
|
||||
ariaLabel="Work Orders by Region"
|
||||
rows={rows.map((row) => ({
|
||||
id: row.region,
|
||||
label: row.region,
|
||||
count: row.workOrderCount,
|
||||
}))}
|
||||
/>
|
||||
</DashboardCard>
|
||||
);
|
||||
}
|
||||
123
src/app/(protected)/dashboard/index.tsx
Normal file
123
src/app/(protected)/dashboard/index.tsx
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import EventOutlinedIcon from "@mui/icons-material/EventOutlined";
|
||||
import PendingActionsIcon from "@mui/icons-material/PendingActions";
|
||||
import ShieldOutlinedIcon from "@mui/icons-material/ShieldOutlined";
|
||||
import { Box, Button, CircularProgress } from "@mui/material";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { DashboardKpiCard } from "@/app/(protected)/dashboard/_components/dashboard-kpi-card";
|
||||
import { DashboardRangeToggle } from "@/app/(protected)/dashboard/_components/dashboard-range-toggle";
|
||||
import { DashboardTrendCard } from "@/app/(protected)/dashboard/_components/dashboard-trend-card";
|
||||
import { DispatcherPerformanceCard } from "@/app/(protected)/dashboard/_components/dispatcher-performance-card";
|
||||
import { DispatcherWorkloadCard } from "@/app/(protected)/dashboard/_components/dispatcher-workload-card";
|
||||
import { VendorInsightsCard } from "@/app/(protected)/dashboard/_components/vendor-insights-card";
|
||||
import { WorkOrderBreakdownCard } from "@/app/(protected)/dashboard/_components/work-order-breakdown-card";
|
||||
import { WorkOrdersByRegionCard } from "@/app/(protected)/dashboard/_components/work-orders-by-region-card";
|
||||
import {
|
||||
DEFAULT_DASHBOARD_RANGE,
|
||||
type DashboardRangeKey,
|
||||
} from "@/domain/dashboard/types/dashboard-range";
|
||||
import { useDashboardPerformance } from "@/domain/dashboard/use-cases/use-dashboard-performance";
|
||||
import { useDashboardRegions } from "@/domain/dashboard/use-cases/use-dashboard-regions";
|
||||
import { useDashboardStats } from "@/domain/dashboard/use-cases/use-dashboard-stats";
|
||||
import { useDashboardVendorInsights } from "@/domain/dashboard/use-cases/use-dashboard-vendor-insights";
|
||||
import { useDashboardWorkload } from "@/domain/dashboard/use-cases/use-dashboard-workload";
|
||||
import {
|
||||
avetaPendingDrilldownSearch,
|
||||
scheduledTomorrowDrilldownSearch,
|
||||
UPLIFTS_ROUTE,
|
||||
workOrderDrilldownUrl,
|
||||
} from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
|
||||
export default function DashboardPage() {
|
||||
const navigate = useNavigate();
|
||||
const [range, setRange] = useState<DashboardRangeKey>(DEFAULT_DASHBOARD_RANGE);
|
||||
const stats = useDashboardStats(range);
|
||||
const workload = useDashboardWorkload(range);
|
||||
const performance = useDashboardPerformance(range);
|
||||
const regions = useDashboardRegions(range);
|
||||
const vendors = useDashboardVendorInsights();
|
||||
|
||||
const isRefreshing =
|
||||
[stats, workload, performance, regions, vendors].some((query) => query.isFetching) &&
|
||||
!stats.isLoading;
|
||||
|
||||
return (
|
||||
<Box className="flex flex-col gap-4 p-4">
|
||||
<PageHeader
|
||||
title="Dashboard"
|
||||
actions={
|
||||
<Box className="flex items-center gap-2">
|
||||
{isRefreshing && <CircularProgress size={16} />}
|
||||
{range !== DEFAULT_DASHBOARD_RANGE && (
|
||||
<Button size="small" onClick={() => setRange(DEFAULT_DASHBOARD_RANGE)}>
|
||||
Reset filters
|
||||
</Button>
|
||||
)}
|
||||
<DashboardRangeToggle value={range} onChange={setRange} />
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<Box className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
<DashboardKpiCard
|
||||
title="Scheduled Tomorrow"
|
||||
icon={<EventOutlinedIcon />}
|
||||
tone="primary"
|
||||
value={stats.data?.scheduledTomorrow}
|
||||
loading={stats.isLoading}
|
||||
active={(stats.data?.scheduledTomorrow ?? 0) > 0}
|
||||
onSelect={() => navigate(workOrderDrilldownUrl(scheduledTomorrowDrilldownSearch()))}
|
||||
/>
|
||||
<DashboardKpiCard
|
||||
title="Pending Uplifts"
|
||||
icon={<PendingActionsIcon />}
|
||||
tone="info"
|
||||
value={stats.data?.pendingUplifts}
|
||||
loading={stats.isLoading}
|
||||
active={(stats.data?.pendingUplifts ?? 0) > 0}
|
||||
onSelect={() => navigate(UPLIFTS_ROUTE)}
|
||||
/>
|
||||
<DashboardKpiCard
|
||||
title="Aveta Pending"
|
||||
icon={<ShieldOutlinedIcon />}
|
||||
tone="warning"
|
||||
value={stats.data?.avetaPending}
|
||||
loading={stats.isLoading}
|
||||
active={(stats.data?.avetaPending ?? 0) > 0}
|
||||
onSelect={() => navigate(workOrderDrilldownUrl(avetaPendingDrilldownSearch()))}
|
||||
/>
|
||||
</Box>
|
||||
<Box className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||
<WorkOrderBreakdownCard
|
||||
breakdown={stats.data?.breakdown ?? []}
|
||||
range={range}
|
||||
isLoading={stats.isLoading}
|
||||
error={stats.error}
|
||||
/>
|
||||
<WorkOrdersByRegionCard
|
||||
rows={regions.data ?? []}
|
||||
isLoading={regions.isLoading}
|
||||
error={regions.error}
|
||||
/>
|
||||
<DispatcherWorkloadCard
|
||||
rows={workload.data ?? []}
|
||||
range={range}
|
||||
isLoading={workload.isLoading}
|
||||
error={workload.error}
|
||||
/>
|
||||
<DispatcherPerformanceCard
|
||||
rows={performance.data ?? []}
|
||||
range={range}
|
||||
isLoading={performance.isLoading}
|
||||
error={performance.error}
|
||||
/>
|
||||
</Box>
|
||||
<DashboardTrendCard range={range} />
|
||||
<VendorInsightsCard
|
||||
rows={vendors.data ?? []}
|
||||
isLoading={vendors.isLoading}
|
||||
error={vendors.error}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,240 +1,5 @@
|
|||
import type { ReactNode } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutlined";
|
||||
import FolderOpenOutlinedIcon from "@mui/icons-material/FolderOpenOutlined";
|
||||
import ScheduleOutlinedIcon from "@mui/icons-material/ScheduleOutlined";
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
CircularProgress,
|
||||
Paper,
|
||||
Stack,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useDashboardStats } from "@/domain/dashboard/use-cases/use-dashboard-stats";
|
||||
import DashboardPage from "@/app/(protected)/dashboard";
|
||||
|
||||
const INVOICE_STATUSES = ["Draft", "Challenged", "Pending Approval", "Approved", "Paid"] as const;
|
||||
|
||||
const PRIORITY_LEVELS = [5, 4, 3, 2, 1] as const;
|
||||
|
||||
interface KpiCardProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
value?: string | number;
|
||||
icon: ReactNode;
|
||||
color: "success" | "primary" | "info" | "warning";
|
||||
onClick: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
function KpiCard({ title, description, value, icon, color, onClick, loading }: KpiCardProps) {
|
||||
const colorMap = {
|
||||
success: "success.main",
|
||||
primary: "primary.main",
|
||||
info: "info.main",
|
||||
warning: "warning.main",
|
||||
} as const;
|
||||
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
onClick={onClick}
|
||||
className="flex min-h-[140px] flex-1 cursor-pointer transition-shadow hover:shadow-md"
|
||||
sx={{
|
||||
borderLeftWidth: 4,
|
||||
borderLeftStyle: "solid",
|
||||
borderLeftColor: colorMap[color],
|
||||
}}
|
||||
>
|
||||
<Box className="flex w-full gap-4 p-4">
|
||||
<Box
|
||||
className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full"
|
||||
sx={{ bgcolor: `${colorMap[color]}22`, color: colorMap[color] }}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
|
||||
<Box className="flex min-w-0 flex-col justify-center gap-1">
|
||||
<Typography variant="subtitle1" className="font-semibold">
|
||||
{title}
|
||||
</Typography>
|
||||
{value !== undefined && (
|
||||
<Typography variant="h4" component="p" className="font-bold leading-tight">
|
||||
{loading ? "..." : typeof value === "number" ? value.toLocaleString() : value}
|
||||
</Typography>
|
||||
)}
|
||||
{Boolean(description) && (
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
color: "text.secondary",
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const navigate = useNavigate();
|
||||
const { data: stats, isLoading, isFetching, error } = useDashboardStats();
|
||||
|
||||
const formatStat = (value: number | undefined) => (isLoading ? undefined : (value ?? 0));
|
||||
|
||||
return (
|
||||
<Box className="flex flex-col gap-4 p-4">
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={2}
|
||||
sx={{
|
||||
alignItems: "baseline",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h5" component="h1">
|
||||
Dashboard
|
||||
</Typography>
|
||||
{isFetching && !isLoading && <CircularProgress size={16} />}
|
||||
</Stack>
|
||||
{Boolean(error) && (
|
||||
<Alert severity="error">
|
||||
{error instanceof Error ? error.message : "Failed to load dashboard stats"}
|
||||
</Alert>
|
||||
)}
|
||||
<Stack
|
||||
direction={{ xs: "column", lg: "row" }}
|
||||
spacing={2}
|
||||
useFlexGap
|
||||
sx={{
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<KpiCard
|
||||
title="Create a Work Order"
|
||||
description="Report a problem you need fixed"
|
||||
icon={<AddIcon />}
|
||||
color="success"
|
||||
onClick={() => navigate("/workorders/new")}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Open Work Orders"
|
||||
value={formatStat(stats?.open)}
|
||||
icon={<FolderOpenOutlinedIcon />}
|
||||
color="primary"
|
||||
loading={isLoading}
|
||||
onClick={() => navigate("/workorders")}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Not Dispatched"
|
||||
value={formatStat(stats?.notDispatched)}
|
||||
icon={<ScheduleOutlinedIcon />}
|
||||
color="info"
|
||||
loading={isLoading}
|
||||
onClick={() => navigate("/workorders")}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Completed Orders"
|
||||
value={formatStat(stats?.completed)}
|
||||
icon={<CheckCircleOutlineIcon />}
|
||||
color="warning"
|
||||
loading={isLoading}
|
||||
onClick={() => navigate("/workorders")}
|
||||
/>
|
||||
</Stack>
|
||||
<Paper variant="outlined" className="overflow-hidden">
|
||||
<Box className="border-b border-border px-4 py-3">
|
||||
<Typography variant="h6" component="h2">
|
||||
Priority Analysis
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
color: "text.secondary",
|
||||
}}
|
||||
>
|
||||
Age of open Work Orders by Priority
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Priority</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Total
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
0-14 Days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
15-29 Days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
30-59 Days
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
60+ Days
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{PRIORITY_LEVELS.map((priority) => (
|
||||
<TableRow key={priority}>
|
||||
<TableCell>{priority}</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
<TableCell align="right">—</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</Paper>
|
||||
<Paper variant="outlined" className="overflow-hidden">
|
||||
<Box className="border-b border-border px-4 py-3">
|
||||
<Typography variant="h6" component="h2">
|
||||
Invoice Analysis
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<TableContainer>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell className="font-semibold">Status</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Count
|
||||
</TableCell>
|
||||
<TableCell align="right" className="font-semibold">
|
||||
Amount
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{INVOICE_STATUSES.map((status) => (
|
||||
<TableRow key={status}>
|
||||
<TableCell>{status}</TableCell>
|
||||
<TableCell align="right">0</TableCell>
|
||||
<TableCell align="right">$0.00</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
export default function HomePage() {
|
||||
return <DashboardPage />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
import { useEffect, useRef, useState } from "react";
|
||||
import { useSearchParams } from "react-router";
|
||||
import type { WorkOrderAdvancedFilters } from "@/domain/work-orders/types/work-order-advanced-filters";
|
||||
import { parseDashboardDrilldownParams } from "@/domain/work-orders/utils/dashboard-drilldown-params";
|
||||
|
||||
export function useDashboardDrilldownFilters(
|
||||
onApply: (filters: WorkOrderAdvancedFilters) => void,
|
||||
): boolean {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const appliedRef = useRef(false);
|
||||
const [fromDashboard, setFromDashboard] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (appliedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const drilldown = parseDashboardDrilldownParams(searchParams);
|
||||
if (!drilldown) {
|
||||
return;
|
||||
}
|
||||
|
||||
appliedRef.current = true;
|
||||
setFromDashboard(true);
|
||||
onApply(drilldown);
|
||||
setSearchParams({}, { replace: true });
|
||||
}, [searchParams, setSearchParams, onApply]);
|
||||
|
||||
return fromDashboard;
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { Box } from "@mui/material";
|
||||
import { Box, Link as MuiLink } from "@mui/material";
|
||||
import { Link as RouterLink } from "react-router";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { QueryErrorPanel } from "@/components/ui/query-error-panel";
|
||||
import { WorkOrdersAdvancedFiltersBanner } from "@/app/(protected)/workorders/_components/list/work-orders-advanced-filters-banner";
|
||||
|
|
@ -8,6 +9,7 @@ import { WorkOrdersListHeader } from "@/app/(protected)/workorders/_components/l
|
|||
import { WorkOrdersListPagePanels } from "@/app/(protected)/workorders/_components/list/work-orders-list-page-panels";
|
||||
import { WoTable } from "@/app/(protected)/workorders/_components/list/table/wo-table";
|
||||
import { useWorkOrdersListPage } from "@/app/(protected)/workorders/_hooks/use-work-orders-list-page";
|
||||
import { useDashboardDrilldownFilters } from "@/app/(protected)/workorders/_hooks/use-dashboard-drilldown-filters";
|
||||
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
|
||||
import { hasCompletionDocService } from "@/domain/work-orders/utils/completion-doc-service-gate";
|
||||
import { useAuthContext } from "@/providers/auth-context";
|
||||
|
|
@ -24,6 +26,7 @@ export default function WorkOrdersListPage() {
|
|||
const { user } = useAuthContext();
|
||||
const page = useWorkOrdersListPage();
|
||||
const { filters, tableData } = page;
|
||||
const fromDashboard = useDashboardDrilldownFilters(filters.applyAdvancedFilters);
|
||||
|
||||
return (
|
||||
<Box className="flex h-full flex-col overflow-hidden p-2.5">
|
||||
|
|
@ -52,6 +55,12 @@ export default function WorkOrdersListPage() {
|
|||
}
|
||||
/>
|
||||
|
||||
{fromDashboard && (
|
||||
<MuiLink component={RouterLink} to="/" underline="hover" className="mb-2 self-start">
|
||||
Back to Dashboard
|
||||
</MuiLink>
|
||||
)}
|
||||
|
||||
<WorkOrdersFilterBar
|
||||
weekMonday={filters.weekMonday}
|
||||
onWeekChange={filters.setWeekMonday}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,24 @@
|
|||
import { API_PATHS } from "@/api/api-paths";
|
||||
import { apiGet } from "@/api/api";
|
||||
import { handleApiResponse } from "@/api/handle-api-response";
|
||||
import type { DashboardStats } from "@/domain/dashboard/types/dashboard-stats";
|
||||
import type { Options } from "ky";
|
||||
import type { DashboardRangeParams } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type {
|
||||
DashboardBreakdownRow,
|
||||
DashboardStats,
|
||||
} from "@/domain/dashboard/types/dashboard-stats";
|
||||
import type { DispatcherPerformanceRow } from "@/domain/dashboard/types/dashboard-performance";
|
||||
import type { DashboardTrendParams } from "@/domain/dashboard/types/dashboard-trend";
|
||||
import type {
|
||||
DashboardTrend,
|
||||
DashboardTrendGranularity,
|
||||
} from "@/domain/dashboard/types/dashboard-trend";
|
||||
import {
|
||||
UNMAPPED_REGION_LABEL,
|
||||
type RegionWorkOrdersRow,
|
||||
} from "@/domain/dashboard/types/dashboard-regions";
|
||||
import type { DispatcherWorkloadRow } from "@/domain/dashboard/types/dashboard-workload";
|
||||
import type { VendorInsightRow } from "@/domain/dashboard/types/dashboard-vendor-insights";
|
||||
|
||||
function toNumber(value: unknown): number {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
|
|
@ -16,20 +33,254 @@ function toNumber(value: unknown): number {
|
|||
return 0;
|
||||
}
|
||||
|
||||
function mapDashboardStats(raw: unknown): DashboardStats {
|
||||
const data = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
|
||||
function asString(value: unknown): string {
|
||||
if (typeof value === "string") {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
function asRecords(value: unknown): Record<string, unknown>[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return value.filter(
|
||||
(item): item is Record<string, unknown> =>
|
||||
typeof item === "object" && item !== null && !Array.isArray(item),
|
||||
);
|
||||
}
|
||||
|
||||
function readField(data: Record<string, unknown>, key: string): unknown {
|
||||
const capitalized = key.charAt(0).toUpperCase() + key.slice(1);
|
||||
const value = data[key] ?? data[capitalized];
|
||||
return value === null ? undefined : value;
|
||||
}
|
||||
|
||||
function toRecord(value: unknown): Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function readCollection(value: unknown, key: string): Record<string, unknown>[] {
|
||||
const data = toRecord(value);
|
||||
const collection = key ? (readField(data, key) ?? value) : value;
|
||||
return asRecords(collection);
|
||||
}
|
||||
|
||||
function rangeSearchParams(range?: DashboardRangeParams): Options | undefined {
|
||||
if (!range?.dateFrom || !range?.dateTo) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return { searchParams: { dateFrom: range.dateFrom, dateTo: range.dateTo } };
|
||||
}
|
||||
|
||||
function trendSearchParams(params?: DashboardTrendParams): Options | undefined {
|
||||
if (
|
||||
!params ||
|
||||
(!params.dateFrom && !params.dateTo && !params.granularity && !params.range && !params.year)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const searchParams: Record<string, string | number> = {};
|
||||
if (params.dateFrom) searchParams.dateFrom = params.dateFrom;
|
||||
if (params.dateTo) searchParams.dateTo = params.dateTo;
|
||||
if (params.granularity) searchParams.granularity = params.granularity;
|
||||
if (params.range) searchParams.range = params.range;
|
||||
if (params.year) searchParams.year = params.year;
|
||||
|
||||
return { searchParams };
|
||||
}
|
||||
|
||||
function mapBreakdownRow(raw: Record<string, unknown>): DashboardBreakdownRow {
|
||||
return {
|
||||
open: toNumber(data.open ?? data.Open),
|
||||
notDispatched: toNumber(data.notDispatched ?? data.NotDispatched),
|
||||
completed: toNumber(data.completed ?? data.Completed),
|
||||
status:
|
||||
asString(readField(raw, "status") ?? readField(raw, "name") ?? readField(raw, "label")) ||
|
||||
UNMAPPED_REGION_LABEL,
|
||||
count: toNumber(readField(raw, "count") ?? readField(raw, "value")),
|
||||
};
|
||||
}
|
||||
|
||||
function mapBreakdown(value: unknown): DashboardBreakdownRow[] {
|
||||
if (Array.isArray(value)) {
|
||||
return asRecords(value).map(mapBreakdownRow);
|
||||
}
|
||||
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return Object.entries(value as Record<string, unknown>)
|
||||
.map(([status, count]) => ({ status, count: toNumber(count) }))
|
||||
.filter((row) => row.status !== "");
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function mapDispatcherIdentity(raw: Record<string, unknown>): {
|
||||
dispatcherId: string;
|
||||
dispatcherName: string;
|
||||
} {
|
||||
return {
|
||||
dispatcherId: asString(
|
||||
readField(raw, "dispatcherId") ?? readField(raw, "id") ?? readField(raw, "userId"),
|
||||
),
|
||||
dispatcherName: asString(readField(raw, "dispatcherName") ?? readField(raw, "name")),
|
||||
};
|
||||
}
|
||||
|
||||
function mapDashboardStats(raw: unknown): DashboardStats {
|
||||
const data = toRecord(raw);
|
||||
const average = readField(data, "averageResolutionDays");
|
||||
|
||||
return {
|
||||
total: toNumber(readField(data, "total")),
|
||||
open: toNumber(readField(data, "open")),
|
||||
notDispatched: toNumber(readField(data, "notDispatched")),
|
||||
completed: toNumber(readField(data, "completed")),
|
||||
dueCount: toNumber(readField(data, "dueCount")),
|
||||
completedDueCount: toNumber(readField(data, "completedDueCount")),
|
||||
completionRate: toNumber(readField(data, "completionRate")),
|
||||
averageResolutionDays: average == null ? null : toNumber(average),
|
||||
scheduledTomorrow: toNumber(readField(data, "scheduledTomorrow")),
|
||||
pendingUplifts: toNumber(readField(data, "pendingUplifts")),
|
||||
avetaPending: toNumber(readField(data, "avetaPending")),
|
||||
breakdown: mapBreakdown(readField(data, "breakdown") ?? readField(data, "workOrderBreakdown")),
|
||||
};
|
||||
}
|
||||
|
||||
function mapDispatcherWorkload(raw: unknown): DispatcherWorkloadRow[] {
|
||||
return readCollection(raw, "items").map((rawRow) => {
|
||||
const identity = mapDispatcherIdentity(rawRow);
|
||||
return {
|
||||
...identity,
|
||||
openWorkOrders: toNumber(
|
||||
readField(rawRow, "openWorkOrders") ??
|
||||
readField(rawRow, "openCount") ??
|
||||
readField(rawRow, "open"),
|
||||
),
|
||||
totalWorkOrders: toNumber(
|
||||
readField(rawRow, "totalWorkOrders") ??
|
||||
readField(rawRow, "totalCount") ??
|
||||
readField(rawRow, "scheduledWorkOrders") ??
|
||||
readField(rawRow, "scheduled"),
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function mapDispatcherPerformance(raw: unknown): DispatcherPerformanceRow[] {
|
||||
return readCollection(raw, "items").map((rawRow) => {
|
||||
const identity = mapDispatcherIdentity(rawRow);
|
||||
return {
|
||||
...identity,
|
||||
completionRate: toNumber(
|
||||
readField(rawRow, "completionRate") ?? readField(rawRow, "onTimeRate"),
|
||||
),
|
||||
averageResolutionDays:
|
||||
readField(rawRow, "averageResolutionDays") == null
|
||||
? null
|
||||
: toNumber(readField(rawRow, "averageResolutionDays")),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function mapRegions(raw: unknown): RegionWorkOrdersRow[] {
|
||||
return readCollection(raw, "items").map((rawRow) => {
|
||||
const region =
|
||||
asString(readField(rawRow, "region") ?? readField(rawRow, "name")) || UNMAPPED_REGION_LABEL;
|
||||
return {
|
||||
region,
|
||||
workOrderCount: toNumber(
|
||||
readField(rawRow, "workOrderCount") ??
|
||||
readField(rawRow, "count") ??
|
||||
readField(rawRow, "total"),
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function mapVendorInsights(raw: unknown): VendorInsightRow[] {
|
||||
return readCollection(raw, "items").map((rawRow) => ({
|
||||
vendorId: asString(
|
||||
readField(rawRow, "vendorId") ??
|
||||
readField(rawRow, "vendorCompanyId") ??
|
||||
readField(rawRow, "id"),
|
||||
),
|
||||
vendorName: asString(
|
||||
readField(rawRow, "vendorName") ??
|
||||
readField(rawRow, "vendorCompanyName") ??
|
||||
readField(rawRow, "companyName") ??
|
||||
readField(rawRow, "name"),
|
||||
),
|
||||
completionRate: toNumber(readField(rawRow, "completionRate")),
|
||||
rescheduleRate: toNumber(readField(rawRow, "rescheduleRate")),
|
||||
averageResolutionDays:
|
||||
readField(rawRow, "averageResolutionDays") == null
|
||||
? null
|
||||
: toNumber(readField(rawRow, "averageResolutionDays")),
|
||||
totalJobs: toNumber(readField(rawRow, "totalJobs")),
|
||||
}));
|
||||
}
|
||||
|
||||
function mapTrendGranularity(value: unknown): DashboardTrendGranularity | null {
|
||||
const granularity = asString(value).toLowerCase();
|
||||
return granularity === "day" || granularity === "week" || granularity === "month"
|
||||
? granularity
|
||||
: null;
|
||||
}
|
||||
|
||||
function mapDashboardTrend(raw: unknown): DashboardTrend {
|
||||
const data = toRecord(raw);
|
||||
const buckets = readCollection(data, "buckets");
|
||||
const legacyPoints = readCollection(data, "points");
|
||||
const points = (buckets.length > 0 ? buckets : legacyPoints).map((rawPoint) => ({
|
||||
date: asString(readField(rawPoint, "date")),
|
||||
label: asString(
|
||||
readField(rawPoint, "label") ?? readField(rawPoint, "period") ?? readField(rawPoint, "date"),
|
||||
),
|
||||
total: toNumber(
|
||||
readField(rawPoint, "total") ?? readField(rawPoint, "count") ?? readField(rawPoint, "value"),
|
||||
),
|
||||
open: toNumber(readField(rawPoint, "open")),
|
||||
completed: toNumber(readField(rawPoint, "completed")),
|
||||
canceled: toNumber(readField(rawPoint, "canceled")),
|
||||
overdue: toNumber(readField(rawPoint, "overdue")),
|
||||
isCurrent: readField(rawPoint, "isCurrent") === true,
|
||||
}));
|
||||
|
||||
return { granularity: mapTrendGranularity(readField(data, "granularity")), points };
|
||||
}
|
||||
|
||||
export const dashboardApi = {
|
||||
getStats: async (): Promise<DashboardStats> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.stats);
|
||||
const response = handleApiResponse<unknown>(data);
|
||||
return mapDashboardStats(response);
|
||||
getStats: async (range?: DashboardRangeParams): Promise<DashboardStats> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.stats, rangeSearchParams(range));
|
||||
return mapDashboardStats(handleApiResponse<unknown>(data));
|
||||
},
|
||||
getWorkload: async (range?: DashboardRangeParams): Promise<DispatcherWorkloadRow[]> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.workload, rangeSearchParams(range));
|
||||
return mapDispatcherWorkload(handleApiResponse<unknown>(data));
|
||||
},
|
||||
getPerformance: async (range?: DashboardRangeParams): Promise<DispatcherPerformanceRow[]> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.performance, rangeSearchParams(range));
|
||||
return mapDispatcherPerformance(handleApiResponse<unknown>(data));
|
||||
},
|
||||
getRegions: async (range?: DashboardRangeParams): Promise<RegionWorkOrdersRow[]> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.regions, rangeSearchParams(range));
|
||||
return mapRegions(handleApiResponse<unknown>(data));
|
||||
},
|
||||
getVendorInsights: async (): Promise<VendorInsightRow[]> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.vendorInsights);
|
||||
return mapVendorInsights(handleApiResponse<unknown>(data));
|
||||
},
|
||||
getTrend: async (params?: DashboardTrendParams): Promise<DashboardTrend> => {
|
||||
const data = await apiGet<unknown>(API_PATHS.dashboard.trend, trendSearchParams(params));
|
||||
return mapDashboardTrend(handleApiResponse<unknown>(data));
|
||||
},
|
||||
};
|
||||
|
|
|
|||
6
src/domain/dashboard/types/dashboard-performance.ts
Normal file
6
src/domain/dashboard/types/dashboard-performance.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export interface DispatcherPerformanceRow {
|
||||
dispatcherId: string;
|
||||
dispatcherName: string;
|
||||
completionRate: number;
|
||||
averageResolutionDays: number | null;
|
||||
}
|
||||
10
src/domain/dashboard/types/dashboard-range.ts
Normal file
10
src/domain/dashboard/types/dashboard-range.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
export const DASHBOARD_RANGES = ["this-week", "last-3-months", "today", "all-time"] as const;
|
||||
|
||||
export type DashboardRangeKey = (typeof DASHBOARD_RANGES)[number];
|
||||
|
||||
export const DEFAULT_DASHBOARD_RANGE: DashboardRangeKey = "this-week";
|
||||
|
||||
export interface DashboardRangeParams {
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
}
|
||||
6
src/domain/dashboard/types/dashboard-regions.ts
Normal file
6
src/domain/dashboard/types/dashboard-regions.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export const UNMAPPED_REGION_LABEL = "Unmapped/Other";
|
||||
|
||||
export interface RegionWorkOrdersRow {
|
||||
region: string;
|
||||
workOrderCount: number;
|
||||
}
|
||||
|
|
@ -1,5 +1,19 @@
|
|||
export interface DashboardBreakdownRow {
|
||||
status: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface DashboardStats {
|
||||
total: number;
|
||||
open: number;
|
||||
notDispatched: number;
|
||||
completed: number;
|
||||
dueCount: number;
|
||||
completedDueCount: number;
|
||||
completionRate: number;
|
||||
averageResolutionDays: number | null;
|
||||
scheduledTomorrow: number;
|
||||
pendingUplifts: number;
|
||||
avetaPending: number;
|
||||
breakdown: DashboardBreakdownRow[];
|
||||
}
|
||||
|
|
|
|||
25
src/domain/dashboard/types/dashboard-trend.ts
Normal file
25
src/domain/dashboard/types/dashboard-trend.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
export type DashboardTrendGranularity = "day" | "week" | "month";
|
||||
|
||||
export interface DashboardTrendParams {
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
granularity?: DashboardTrendGranularity;
|
||||
range?: "3m";
|
||||
year?: number;
|
||||
}
|
||||
|
||||
export interface DashboardTrendPoint {
|
||||
date: string;
|
||||
label: string;
|
||||
total: number;
|
||||
open: number;
|
||||
completed: number;
|
||||
canceled: number;
|
||||
overdue: number;
|
||||
isCurrent: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardTrend {
|
||||
granularity: DashboardTrendGranularity | null;
|
||||
points: DashboardTrendPoint[];
|
||||
}
|
||||
8
src/domain/dashboard/types/dashboard-vendor-insights.ts
Normal file
8
src/domain/dashboard/types/dashboard-vendor-insights.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export interface VendorInsightRow {
|
||||
vendorId: string;
|
||||
vendorName: string;
|
||||
completionRate: number;
|
||||
rescheduleRate: number;
|
||||
averageResolutionDays: number | null;
|
||||
totalJobs: number;
|
||||
}
|
||||
6
src/domain/dashboard/types/dashboard-workload.ts
Normal file
6
src/domain/dashboard/types/dashboard-workload.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export interface DispatcherWorkloadRow {
|
||||
dispatcherId: string;
|
||||
dispatcherName: string;
|
||||
openWorkOrders: number;
|
||||
totalWorkOrders: number;
|
||||
}
|
||||
16
src/domain/dashboard/use-cases/use-dashboard-performance.ts
Normal file
16
src/domain/dashboard/use-cases/use-dashboard-performance.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
import type { DispatcherPerformanceRow } from "@/domain/dashboard/types/dashboard-performance";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import { dashboardRangeParams } from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useDashboardPerformance(
|
||||
range: DashboardRangeKey,
|
||||
): UseQueryResult<DispatcherPerformanceRow[], Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.dashboard.performance(range),
|
||||
queryFn: () => dashboardApi.getPerformance(dashboardRangeParams(range)),
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
}
|
||||
16
src/domain/dashboard/use-cases/use-dashboard-regions.ts
Normal file
16
src/domain/dashboard/use-cases/use-dashboard-regions.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
import type { RegionWorkOrdersRow } from "@/domain/dashboard/types/dashboard-regions";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import { dashboardRangeParams } from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useDashboardRegions(
|
||||
range: DashboardRangeKey,
|
||||
): UseQueryResult<RegionWorkOrdersRow[], Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.dashboard.regions(range),
|
||||
queryFn: () => dashboardApi.getRegions(dashboardRangeParams(range)),
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
|
@ -1,12 +1,14 @@
|
|||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type { DashboardStats } from "@/domain/dashboard/types/dashboard-stats";
|
||||
import { dashboardRangeParams } from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useDashboardStats(): UseQueryResult<DashboardStats, Error> {
|
||||
export function useDashboardStats(range: DashboardRangeKey): UseQueryResult<DashboardStats, Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.dashboard.stats(),
|
||||
queryFn: () => dashboardApi.getStats(),
|
||||
queryKey: queryKeys.dashboard.stats(range),
|
||||
queryFn: () => dashboardApi.getStats(dashboardRangeParams(range)),
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
17
src/domain/dashboard/use-cases/use-dashboard-trend.ts
Normal file
17
src/domain/dashboard/use-cases/use-dashboard-trend.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
import type {
|
||||
DashboardTrend,
|
||||
DashboardTrendParams,
|
||||
} from "@/domain/dashboard/types/dashboard-trend";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useDashboardTrend(
|
||||
params?: DashboardTrendParams,
|
||||
): UseQueryResult<DashboardTrend, Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.dashboard.trend(params),
|
||||
queryFn: () => dashboardApi.getTrend(params),
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
import type { VendorInsightRow } from "@/domain/dashboard/types/dashboard-vendor-insights";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useDashboardVendorInsights(): UseQueryResult<VendorInsightRow[], Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.dashboard.vendorInsights(),
|
||||
queryFn: () => dashboardApi.getVendorInsights(),
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
}
|
||||
16
src/domain/dashboard/use-cases/use-dashboard-workload.ts
Normal file
16
src/domain/dashboard/use-cases/use-dashboard-workload.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
import type { DispatcherWorkloadRow } from "@/domain/dashboard/types/dashboard-workload";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import { dashboardRangeParams } from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
import { queryKeys } from "@/infra/query-key/query-key";
|
||||
|
||||
export function useDashboardWorkload(
|
||||
range: DashboardRangeKey,
|
||||
): UseQueryResult<DispatcherWorkloadRow[], Error> {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.dashboard.workload(range),
|
||||
queryFn: () => dashboardApi.getWorkload(dashboardRangeParams(range)),
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
}
|
||||
73
src/domain/dashboard/utils/dashboard-range-utils.ts
Normal file
73
src/domain/dashboard/utils/dashboard-range-utils.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { DEFAULT_DASHBOARD_RANGE } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type {
|
||||
DashboardRangeKey,
|
||||
DashboardRangeParams,
|
||||
} from "@/domain/dashboard/types/dashboard-range";
|
||||
|
||||
export const BUSINESS_TIME_ZONE = "America/New_York";
|
||||
|
||||
const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export function businessTodayIso(now: Date = new Date()): string {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: BUSINESS_TIME_ZONE,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(now);
|
||||
}
|
||||
|
||||
export function isIsoDate(value: string): boolean {
|
||||
return ISO_DATE_PATTERN.test(value);
|
||||
}
|
||||
|
||||
export function addDaysIso(isoDate: string, days: number): string {
|
||||
const [year, month, day] = isoDate.split("-").map(Number);
|
||||
const shifted = new Date(Date.UTC(year, month - 1, day + days));
|
||||
return shifted.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function mondayOf(isoDate: string): string {
|
||||
const [year, month, day] = isoDate.split("-").map(Number);
|
||||
const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
|
||||
return addDaysIso(isoDate, -((weekday + 6) % 7));
|
||||
}
|
||||
|
||||
export function monthStartIso(isoDate: string): string {
|
||||
return `${isoDate.slice(0, 7)}-01`;
|
||||
}
|
||||
|
||||
export function monthEndIso(isoDate: string): string {
|
||||
const year = Number(isoDate.slice(0, 4));
|
||||
const month = Number(isoDate.slice(5, 7));
|
||||
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
||||
return `${isoDate.slice(0, 7)}-${String(lastDay).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function shiftMonthsIso(isoDate: string, months: number): string {
|
||||
const year = Number(isoDate.slice(0, 4));
|
||||
const month = Number(isoDate.slice(5, 7));
|
||||
const shifted = new Date(Date.UTC(year, month - 1 + months, 1));
|
||||
return `${shifted.getUTCFullYear()}-${String(shifted.getUTCMonth() + 1).padStart(2, "0")}-01`;
|
||||
}
|
||||
|
||||
export function dashboardRangeParams(
|
||||
range: DashboardRangeKey = DEFAULT_DASHBOARD_RANGE,
|
||||
today: string = businessTodayIso(),
|
||||
): DashboardRangeParams {
|
||||
switch (range) {
|
||||
case "today":
|
||||
return { dateFrom: today, dateTo: today };
|
||||
case "this-week": {
|
||||
const monday = mondayOf(today);
|
||||
return { dateFrom: monday, dateTo: addDaysIso(monday, 4) };
|
||||
}
|
||||
case "last-3-months":
|
||||
return {
|
||||
dateFrom: monthStartIso(shiftMonthsIso(today, -2)),
|
||||
dateTo: monthEndIso(today),
|
||||
};
|
||||
case "all-time":
|
||||
return {};
|
||||
}
|
||||
}
|
||||
82
src/domain/dashboard/utils/work-order-drilldown-links.ts
Normal file
82
src/domain/dashboard/utils/work-order-drilldown-links.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { ALL_WIZARD_STATUSES } from "@/domain/work-orders/types/work-order-wizard";
|
||||
import { WO_TYPES, type WOType } from "@/domain/work-orders/types/work-order-wizard";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import {
|
||||
addDaysIso,
|
||||
businessTodayIso,
|
||||
dashboardRangeParams,
|
||||
} from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
|
||||
export const WORK_ORDERS_ROUTE = "/workorders";
|
||||
export const UPLIFTS_ROUTE = "/uplifts";
|
||||
|
||||
export const OPEN_WIZARD_STATUSES: readonly string[] = ALL_WIZARD_STATUSES.filter(
|
||||
(status) => status !== "Completed",
|
||||
);
|
||||
|
||||
export function workOrderDrilldownUrl(search: URLSearchParams): string {
|
||||
const query = search.toString();
|
||||
return query ? `${WORK_ORDERS_ROUTE}?${query}` : WORK_ORDERS_ROUTE;
|
||||
}
|
||||
|
||||
function setDateRange(search: URLSearchParams, range: DashboardRangeKey): void {
|
||||
const params = dashboardRangeParams(range);
|
||||
if (params.dateFrom && params.dateTo) {
|
||||
search.set("dateFrom", params.dateFrom);
|
||||
search.set("dateTo", params.dateTo);
|
||||
}
|
||||
}
|
||||
|
||||
export function workOrderRangeDrilldownSearch(range: DashboardRangeKey): URLSearchParams {
|
||||
const search = new URLSearchParams();
|
||||
setDateRange(search, range);
|
||||
return search;
|
||||
}
|
||||
|
||||
export function workOrderStatusDrilldownSearch(
|
||||
status: string,
|
||||
range: DashboardRangeKey,
|
||||
): URLSearchParams {
|
||||
const search = workOrderRangeDrilldownSearch(range);
|
||||
search.set("statuses", status);
|
||||
return search;
|
||||
}
|
||||
|
||||
export function workOrderTypeDrilldownSearch(
|
||||
type: string,
|
||||
range: DashboardRangeKey,
|
||||
): URLSearchParams | null {
|
||||
if (!WO_TYPES.includes(type as WOType)) return null;
|
||||
const search = workOrderRangeDrilldownSearch(range);
|
||||
search.set("types", type);
|
||||
return search;
|
||||
}
|
||||
|
||||
export function workOrderDispatcherDrilldownSearch(
|
||||
dispatcherId: string,
|
||||
range: DashboardRangeKey,
|
||||
): URLSearchParams {
|
||||
const search = workOrderRangeDrilldownSearch(range);
|
||||
search.set("dispatchers", dispatcherId);
|
||||
return search;
|
||||
}
|
||||
|
||||
export function scheduledTomorrowDrilldownSearch(
|
||||
today: string = businessTodayIso(),
|
||||
): URLSearchParams {
|
||||
const tomorrow = addDaysIso(today, 1);
|
||||
const search = new URLSearchParams();
|
||||
search.set("dateFrom", tomorrow);
|
||||
search.set("dateTo", tomorrow);
|
||||
return search;
|
||||
}
|
||||
|
||||
export function avetaPendingDrilldownSearch(today: string = businessTodayIso()): URLSearchParams {
|
||||
const search = new URLSearchParams();
|
||||
search.set("dateFrom", today);
|
||||
search.set("dateTo", addDaysIso(today, 1));
|
||||
search.set("aveta", "1");
|
||||
search.set("docs", "No");
|
||||
search.set("statuses", OPEN_WIZARD_STATUSES.join(","));
|
||||
return search;
|
||||
}
|
||||
109
src/domain/work-orders/utils/dashboard-drilldown-params.ts
Normal file
109
src/domain/work-orders/utils/dashboard-drilldown-params.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import type { CompletionDocFilter } from "@/domain/work-orders/types/work-order-advanced-filters";
|
||||
import type { WorkOrderAdvancedFilters } from "@/domain/work-orders/types/work-order-advanced-filters";
|
||||
import { EMPTY_ADVANCED_FILTERS } from "@/domain/work-orders/types/work-order-advanced-filters";
|
||||
import { ALL_WIZARD_STATUSES, WO_TYPES } from "@/domain/work-orders/types/work-order-wizard";
|
||||
import type { WizardWOStatus, WOType } from "@/domain/work-orders/types/work-order-wizard";
|
||||
import type { UpliftFilterStatus } from "@/domain/work-orders/types/work-order-uplift-filter";
|
||||
import { cloneAdvancedFilters } from "@/domain/work-orders/utils/advanced-filters-utils";
|
||||
|
||||
const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
const COMPLETION_DOC_FILTERS: CompletionDocFilter[] = ["No", "Yes", "NN"];
|
||||
|
||||
const UPLIFT_FILTER_VALUES: UpliftFilterStatus[] = [
|
||||
"pending",
|
||||
"approved",
|
||||
"auto_approved",
|
||||
"rejected",
|
||||
];
|
||||
|
||||
function parseList(raw: string | null): string[] {
|
||||
if (!raw) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return raw
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item !== "");
|
||||
}
|
||||
|
||||
function parseStatuses(raw: string | null): WizardWOStatus[] {
|
||||
const valid = new Set<string>(ALL_WIZARD_STATUSES);
|
||||
return [...new Set(parseList(raw))].filter((status): status is WizardWOStatus =>
|
||||
valid.has(status),
|
||||
);
|
||||
}
|
||||
|
||||
function parseTypes(raw: string | null): WOType[] {
|
||||
const valid = new Set<string>(WO_TYPES);
|
||||
return [...new Set(parseList(raw))].filter((type): type is WOType => valid.has(type));
|
||||
}
|
||||
|
||||
function parseCompletionDocs(raw: string | null): CompletionDocFilter[] {
|
||||
const valid = new Set<string>(COMPLETION_DOC_FILTERS);
|
||||
return [...new Set(parseList(raw))].filter((doc): doc is CompletionDocFilter => valid.has(doc));
|
||||
}
|
||||
|
||||
function parseUpliftStatuses(raw: string | null): UpliftFilterStatus[] {
|
||||
const valid = new Set<string>(UPLIFT_FILTER_VALUES);
|
||||
return [...new Set(parseList(raw))].filter((value): value is UpliftFilterStatus =>
|
||||
valid.has(value),
|
||||
);
|
||||
}
|
||||
|
||||
export function parseDashboardDrilldownParams(
|
||||
params: URLSearchParams,
|
||||
): WorkOrderAdvancedFilters | null {
|
||||
const dateFrom = (params.get("dateFrom") ?? "").trim();
|
||||
const dateTo = (params.get("dateTo") ?? "").trim();
|
||||
const hasDateRange = ISO_DATE_PATTERN.test(dateFrom) && ISO_DATE_PATTERN.test(dateTo);
|
||||
const avetaOnly = params.get("aveta") === "1";
|
||||
const docs = parseCompletionDocs(params.get("docs"));
|
||||
const statuses = parseStatuses(params.get("statuses"));
|
||||
const types = parseTypes(params.get("types"));
|
||||
const dispatchers = parseList(params.get("dispatchers"));
|
||||
const upliftStatuses = parseUpliftStatuses(params.get("upliftStatuses"));
|
||||
const hasUplift = params.get("hasUplift") === "1";
|
||||
|
||||
const hasAny =
|
||||
hasDateRange ||
|
||||
avetaOnly ||
|
||||
docs.length > 0 ||
|
||||
statuses.length > 0 ||
|
||||
types.length > 0 ||
|
||||
dispatchers.length > 0 ||
|
||||
upliftStatuses.length > 0 ||
|
||||
hasUplift;
|
||||
|
||||
if (!hasAny) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const filters = cloneAdvancedFilters(EMPTY_ADVANCED_FILTERS);
|
||||
|
||||
if (hasDateRange) {
|
||||
filters.dateRange = "custom";
|
||||
filters.customFrom = dateFrom;
|
||||
filters.customTo = dateTo;
|
||||
}
|
||||
filters.avetaOnly = avetaOnly;
|
||||
filters.hasUplift = hasUplift || upliftStatuses.length > 0;
|
||||
if (docs.length > 0) {
|
||||
filters.docs = new Set(docs);
|
||||
}
|
||||
if (statuses.length > 0) {
|
||||
filters.statuses = new Set(statuses);
|
||||
}
|
||||
if (types.length > 0) {
|
||||
filters.types = new Set(types);
|
||||
}
|
||||
if (dispatchers.length > 0) {
|
||||
filters.dispatchers = new Set(dispatchers);
|
||||
}
|
||||
if (upliftStatuses.length > 0) {
|
||||
filters.upliftStatuses = new Set(upliftStatuses);
|
||||
}
|
||||
|
||||
return filters;
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import type { DashboardTrendParams } from "@/domain/dashboard/types/dashboard-trend";
|
||||
import type { WorkOrdersListParams } from "@/domain/work-orders/types/work-order-list";
|
||||
import type {
|
||||
WorkOrderBoardQueryParams,
|
||||
|
|
@ -49,7 +51,15 @@ export const queryKeys = {
|
|||
},
|
||||
dashboard: {
|
||||
all: ["dashboard"] as const,
|
||||
stats: () => [...queryKeys.dashboard.all, "stats"] as const,
|
||||
stats: (range: DashboardRangeKey) => [...queryKeys.dashboard.all, "stats", range] as const,
|
||||
workload: (range: DashboardRangeKey) =>
|
||||
[...queryKeys.dashboard.all, "workload", range] as const,
|
||||
performance: (range: DashboardRangeKey) =>
|
||||
[...queryKeys.dashboard.all, "performance", range] as const,
|
||||
regions: (range: DashboardRangeKey) => [...queryKeys.dashboard.all, "regions", range] as const,
|
||||
vendorInsights: () => [...queryKeys.dashboard.all, "vendorInsights"] as const,
|
||||
trend: (params?: DashboardTrendParams) =>
|
||||
[...queryKeys.dashboard.all, "trend", params ?? {}] as const,
|
||||
},
|
||||
dropdownOptions: {
|
||||
all: ["dropdownOptions"] as const,
|
||||
|
|
|
|||
153
src/test/app/(protected)/dashboard/dashboard-page.test.tsx
Normal file
153
src/test/app/(protected)/dashboard/dashboard-page.test.tsx
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import { fireEvent, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DashboardRangeKey } from "@/domain/dashboard/types/dashboard-range";
|
||||
import { renderWithProviders } from "@/test/test-utils";
|
||||
|
||||
const navigate = vi.fn();
|
||||
const statsRange = vi.fn<(range: DashboardRangeKey) => void>();
|
||||
|
||||
vi.mock("react-router", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-router")>()),
|
||||
useNavigate: () => navigate,
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/dashboard/use-cases/use-dashboard-workload", () => ({
|
||||
useDashboardWorkload: () => ({ data: [], isLoading: false, isFetching: false, error: null }),
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/dashboard/use-cases/use-dashboard-performance", () => ({
|
||||
useDashboardPerformance: () => ({ data: [], isLoading: false, isFetching: false, error: null }),
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/dashboard/use-cases/use-dashboard-regions", () => ({
|
||||
useDashboardRegions: () => ({ data: [], isLoading: false, isFetching: false, error: null }),
|
||||
}));
|
||||
|
||||
vi.mock("@/domain/dashboard/use-cases/use-dashboard-vendor-insights", () => ({
|
||||
useDashboardVendorInsights: () => ({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
isFetching: false,
|
||||
error: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
const statsData = {
|
||||
scheduledTomorrow: 3,
|
||||
pendingUplifts: 5,
|
||||
avetaPending: 0,
|
||||
breakdown: [
|
||||
{ status: "PM", count: 7 },
|
||||
{ status: "Completed", count: 0 },
|
||||
],
|
||||
};
|
||||
|
||||
vi.mock("@/domain/dashboard/use-cases/use-dashboard-stats", () => ({
|
||||
useDashboardStats: (range: DashboardRangeKey) => {
|
||||
statsRange(range);
|
||||
return { data: statsData, isLoading: false, isFetching: false, error: null };
|
||||
},
|
||||
}));
|
||||
|
||||
import DashboardPage from "@/app/(protected)/dashboard";
|
||||
import {
|
||||
avetaPendingDrilldownSearch,
|
||||
scheduledTomorrowDrilldownSearch,
|
||||
} from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
import { addDaysIso, businessTodayIso } from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
|
||||
function renderDashboard() {
|
||||
return renderWithProviders(<DashboardPage />);
|
||||
}
|
||||
|
||||
describe("DashboardPage", () => {
|
||||
beforeEach(() => {
|
||||
navigate.mockReset();
|
||||
statsRange.mockReset();
|
||||
});
|
||||
|
||||
it("renders the prototype title, range options, and card titles", () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(screen.getByRole("heading", { name: "Dashboard" })).toBeInTheDocument();
|
||||
for (const label of ["This week", "Last 3 months", "Today", "All time"]) {
|
||||
expect(screen.getByRole("button", { name: label })).toBeInTheDocument();
|
||||
}
|
||||
for (const title of [
|
||||
"Scheduled Tomorrow",
|
||||
"Pending Uplifts",
|
||||
"Aveta Pending",
|
||||
"Work Order Breakdown",
|
||||
"Dispatcher Workload",
|
||||
"Dispatcher Performance",
|
||||
"Work Orders by Region",
|
||||
"Vendor Insights",
|
||||
]) {
|
||||
expect(screen.getByText(title)).toBeInTheDocument();
|
||||
}
|
||||
expect(statsRange).toHaveBeenCalledWith("this-week");
|
||||
});
|
||||
|
||||
it("exposes positive KPI cards as keyboard-accessible drill-downs", () => {
|
||||
renderDashboard();
|
||||
|
||||
const tomorrowCard = screen.getByRole("button", { name: /Scheduled Tomorrow/ });
|
||||
expect(tomorrowCard).toBeInTheDocument();
|
||||
fireEvent.click(tomorrowCard);
|
||||
|
||||
const today = businessTodayIso();
|
||||
expect(navigate).toHaveBeenCalledWith(
|
||||
`/workorders?${scheduledTomorrowDrilldownSearch(today).toString()}`,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Pending Uplifts/ }));
|
||||
expect(navigate).toHaveBeenCalledWith("/uplifts");
|
||||
});
|
||||
|
||||
it("keeps zero counts inert", () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(screen.queryByRole("button", { name: /Aveta Pending/ })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByText("Aveta Pending"));
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
|
||||
const inertRow = screen.getByText("Completed");
|
||||
fireEvent.click(inertRow);
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("drills the breakdown status into filtered work orders", () => {
|
||||
renderDashboard();
|
||||
|
||||
fireEvent.click(screen.getByText("PM"));
|
||||
|
||||
const calls = navigate.mock.calls;
|
||||
const [url] = calls[calls.length - 1] ?? [];
|
||||
expect(String(url)).toContain("/workorders?");
|
||||
expect(String(url)).toContain("types=PM");
|
||||
});
|
||||
|
||||
it("switches the stats range from the toggle", () => {
|
||||
renderDashboard();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Today" }));
|
||||
|
||||
expect(statsRange).toHaveBeenCalledWith("today");
|
||||
});
|
||||
|
||||
it("shows the documented empty states when datasets are empty", () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(screen.getByText("No work orders match the current filters.")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("No dispatchers are set up yet.")).toHaveLength(2);
|
||||
expect(screen.getByText("No active vendor has any work orders yet.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps drilldown dates deterministic on the business clock", () => {
|
||||
const today = businessTodayIso();
|
||||
|
||||
expect(scheduledTomorrowDrilldownSearch(today).get("dateFrom")).toBe(addDaysIso(today, 1));
|
||||
expect(avetaPendingDrilldownSearch(today).get("aveta")).toBe("1");
|
||||
});
|
||||
});
|
||||
182
src/test/domain/dashboard/dashboard-api.test.ts
Normal file
182
src/test/domain/dashboard/dashboard-api.test.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiGet = vi.fn();
|
||||
|
||||
vi.mock("@/api/api", () => ({
|
||||
apiGet: (...args: unknown[]) => apiGet(...args),
|
||||
}));
|
||||
|
||||
import { dashboardApi } from "@/domain/dashboard/api/dashboard-api";
|
||||
|
||||
describe("dashboardApi", () => {
|
||||
beforeEach(() => {
|
||||
apiGet.mockReset();
|
||||
});
|
||||
|
||||
it("maps stats tolerantly and sends the range params", async () => {
|
||||
apiGet.mockResolvedValue({
|
||||
Data: {
|
||||
Total: 12,
|
||||
Open: 8,
|
||||
NotDispatched: 2,
|
||||
Completed: 4,
|
||||
DueCount: 5,
|
||||
CompletedDueCount: 3,
|
||||
CompletionRate: 60,
|
||||
AverageResolutionDays: 4.5,
|
||||
ScheduledTomorrow: "3",
|
||||
PendingUplifts: 2,
|
||||
AvetaPending: "1",
|
||||
Breakdown: [
|
||||
{ Status: "Scheduled", Count: "7" },
|
||||
{ Status: "Completed", Count: 4 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const stats = await dashboardApi.getStats({ dateFrom: "2026-09-14", dateTo: "2026-09-18" });
|
||||
|
||||
expect(stats).toEqual({
|
||||
total: 12,
|
||||
open: 8,
|
||||
notDispatched: 2,
|
||||
completed: 4,
|
||||
dueCount: 5,
|
||||
completedDueCount: 3,
|
||||
completionRate: 60,
|
||||
averageResolutionDays: 4.5,
|
||||
scheduledTomorrow: 3,
|
||||
pendingUplifts: 2,
|
||||
avetaPending: 1,
|
||||
breakdown: [
|
||||
{ status: "Scheduled", count: 7 },
|
||||
{ status: "Completed", count: 4 },
|
||||
],
|
||||
});
|
||||
expect(apiGet).toHaveBeenCalledWith("Dashboard/Stats", {
|
||||
searchParams: { dateFrom: "2026-09-14", dateTo: "2026-09-18" },
|
||||
});
|
||||
});
|
||||
|
||||
it("omits search params for the all-time range", async () => {
|
||||
apiGet.mockResolvedValue({ scheduledTomorrow: 0, pendingUplifts: 0, avetaPending: 0 });
|
||||
|
||||
await dashboardApi.getStats({});
|
||||
|
||||
expect(apiGet).toHaveBeenCalledWith("Dashboard/Stats", undefined);
|
||||
});
|
||||
|
||||
it("maps workload rows", async () => {
|
||||
apiGet.mockResolvedValue({
|
||||
Items: [{ DispatcherId: 12, DispatcherName: "Dana Reyes", OpenCount: "4", TotalCount: 6 }],
|
||||
});
|
||||
|
||||
await expect(dashboardApi.getWorkload()).resolves.toEqual([
|
||||
{
|
||||
dispatcherId: "12",
|
||||
dispatcherName: "Dana Reyes",
|
||||
openWorkOrders: 4,
|
||||
totalWorkOrders: 6,
|
||||
},
|
||||
]);
|
||||
expect(apiGet).toHaveBeenCalledWith("Dashboard/Workload", undefined);
|
||||
});
|
||||
|
||||
it("maps performance rows", async () => {
|
||||
apiGet.mockResolvedValue({
|
||||
Items: [
|
||||
{
|
||||
DispatcherId: 12,
|
||||
DispatcherName: "Dana Reyes",
|
||||
CompletionRate: 96.5,
|
||||
AverageResolutionDays: 3.25,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(dashboardApi.getPerformance()).resolves.toEqual([
|
||||
{
|
||||
dispatcherId: "12",
|
||||
dispatcherName: "Dana Reyes",
|
||||
completionRate: 96.5,
|
||||
averageResolutionDays: 3.25,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps unknown regions to Unmapped", async () => {
|
||||
apiGet.mockResolvedValue({
|
||||
Items: [{ Region: "North", Count: 5 }, { Name: " ", WorkOrderCount: 2 }, {}],
|
||||
});
|
||||
|
||||
await expect(dashboardApi.getRegions()).resolves.toEqual([
|
||||
{ region: "North", workOrderCount: 5 },
|
||||
{ region: "Unmapped/Other", workOrderCount: 2 },
|
||||
{ region: "Unmapped/Other", workOrderCount: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps vendor insights with company-name fallback", async () => {
|
||||
apiGet.mockResolvedValue({
|
||||
Items: [
|
||||
{
|
||||
VendorCompanyId: 3,
|
||||
VendorCompanyName: "Gateway Plumbing",
|
||||
CompletionRate: 82,
|
||||
RescheduleRate: 4,
|
||||
AverageResolutionDays: 3,
|
||||
TotalJobs: 11,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(dashboardApi.getVendorInsights()).resolves.toEqual([
|
||||
{
|
||||
vendorId: "3",
|
||||
vendorName: "Gateway Plumbing",
|
||||
completionRate: 82,
|
||||
rescheduleRate: 4,
|
||||
averageResolutionDays: 3,
|
||||
totalJobs: 11,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps the trend contract and sends date, granularity, and year params", async () => {
|
||||
apiGet.mockResolvedValue({
|
||||
Granularity: "Week",
|
||||
Buckets: [{ Date: "2026-09-07", Label: "2026-W37", Total: "9", IsCurrent: true }],
|
||||
});
|
||||
|
||||
await expect(
|
||||
dashboardApi.getTrend({
|
||||
dateFrom: "2026-09-01",
|
||||
dateTo: "2026-09-30",
|
||||
granularity: "month",
|
||||
year: 2026,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
granularity: "week",
|
||||
points: [
|
||||
{
|
||||
date: "2026-09-07",
|
||||
label: "2026-W37",
|
||||
total: 9,
|
||||
open: 0,
|
||||
completed: 0,
|
||||
canceled: 0,
|
||||
overdue: 0,
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(apiGet).toHaveBeenCalledWith("Dashboard/Trend", {
|
||||
searchParams: {
|
||||
dateFrom: "2026-09-01",
|
||||
dateTo: "2026-09-30",
|
||||
granularity: "month",
|
||||
year: 2026,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
68
src/test/domain/dashboard/dashboard-range-utils.test.ts
Normal file
68
src/test/domain/dashboard/dashboard-range-utils.test.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
addDaysIso,
|
||||
businessTodayIso,
|
||||
dashboardRangeParams,
|
||||
mondayOf,
|
||||
monthEndIso,
|
||||
monthStartIso,
|
||||
} from "@/domain/dashboard/utils/dashboard-range-utils";
|
||||
|
||||
describe("businessTodayIso", () => {
|
||||
it("formats the America/New_York calendar date regardless of UTC time", () => {
|
||||
expect(businessTodayIso(new Date("2026-09-16T23:30:00Z"))).toBe("2026-09-16");
|
||||
expect(businessTodayIso(new Date("2026-09-17T02:30:00Z"))).toBe("2026-09-16");
|
||||
expect(businessTodayIso(new Date("2026-01-01T04:30:00Z"))).toBe("2025-12-31");
|
||||
});
|
||||
});
|
||||
|
||||
describe("addDaysIso", () => {
|
||||
it("rolls over month and year boundaries", () => {
|
||||
expect(addDaysIso("2026-01-31", 1)).toBe("2026-02-01");
|
||||
expect(addDaysIso("2026-12-31", 1)).toBe("2027-01-01");
|
||||
expect(addDaysIso("2026-09-14", -7)).toBe("2026-09-07");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mondayOf", () => {
|
||||
it("returns the Monday of the ISO week", () => {
|
||||
expect(mondayOf("2026-09-16")).toBe("2026-09-14");
|
||||
expect(mondayOf("2026-09-14")).toBe("2026-09-14");
|
||||
expect(mondayOf("2026-09-13")).toBe("2026-09-07");
|
||||
});
|
||||
});
|
||||
|
||||
describe("monthStartIso / monthEndIso", () => {
|
||||
it("returns month bounds", () => {
|
||||
expect(monthStartIso("2026-09-16")).toBe("2026-09-01");
|
||||
expect(monthEndIso("2026-09-16")).toBe("2026-09-30");
|
||||
expect(monthEndIso("2026-02-16")).toBe("2026-02-28");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dashboardRangeParams", () => {
|
||||
it("maps today to the business date", () => {
|
||||
expect(dashboardRangeParams("today", "2026-09-16")).toEqual({
|
||||
dateFrom: "2026-09-16",
|
||||
dateTo: "2026-09-16",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps this week to the Monday-Friday business week", () => {
|
||||
expect(dashboardRangeParams("this-week", "2026-09-16")).toEqual({
|
||||
dateFrom: "2026-09-14",
|
||||
dateTo: "2026-09-18",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps last 3 months to the trailing month span", () => {
|
||||
expect(dashboardRangeParams("last-3-months", "2026-09-16")).toEqual({
|
||||
dateFrom: "2026-07-01",
|
||||
dateTo: "2026-09-30",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps all time to unbounded params", () => {
|
||||
expect(dashboardRangeParams("all-time", "2026-09-16")).toEqual({});
|
||||
});
|
||||
});
|
||||
48
src/test/domain/dashboard/work-order-drilldown-links.test.ts
Normal file
48
src/test/domain/dashboard/work-order-drilldown-links.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
avetaPendingDrilldownSearch,
|
||||
scheduledTomorrowDrilldownSearch,
|
||||
workOrderDrilldownUrl,
|
||||
workOrderRangeDrilldownSearch,
|
||||
workOrderStatusDrilldownSearch,
|
||||
} from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
|
||||
describe("work-order drilldown links", () => {
|
||||
it("schedules the tomorrow drilldown on the business clock", () => {
|
||||
const search = scheduledTomorrowDrilldownSearch("2026-09-16");
|
||||
|
||||
expect(search.get("dateFrom")).toBe("2026-09-17");
|
||||
expect(search.get("dateTo")).toBe("2026-09-17");
|
||||
});
|
||||
|
||||
it("builds the Aveta Pending drilldown per SH-294", () => {
|
||||
const search = avetaPendingDrilldownSearch("2026-09-16");
|
||||
const statuses = (search.get("statuses") ?? "").split(",");
|
||||
|
||||
expect(search.get("dateFrom")).toBe("2026-09-16");
|
||||
expect(search.get("dateTo")).toBe("2026-09-17");
|
||||
expect(search.get("aveta")).toBe("1");
|
||||
expect(search.get("docs")).toBe("No");
|
||||
expect(statuses).toContain("Scheduled");
|
||||
expect(statuses).not.toContain("Completed");
|
||||
});
|
||||
|
||||
it("carries the range into status drilldowns", () => {
|
||||
const search = workOrderStatusDrilldownSearch("Scheduled", "today");
|
||||
|
||||
expect(search.get("dateFrom")).toBe("2026-09-16");
|
||||
expect(search.get("dateTo")).toBe("2026-09-16");
|
||||
expect(search.get("statuses")).toBe("Scheduled");
|
||||
});
|
||||
|
||||
it("omits dates for the all-time range", () => {
|
||||
expect(workOrderRangeDrilldownSearch("all-time").toString()).toBe("");
|
||||
});
|
||||
|
||||
it("renders plain or query-bearing work order URLs", () => {
|
||||
expect(workOrderDrilldownUrl(new URLSearchParams())).toBe("/workorders");
|
||||
expect(workOrderDrilldownUrl(new URLSearchParams({ statuses: "Scheduled" }))).toBe(
|
||||
"/workorders?statuses=Scheduled",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { parseDashboardDrilldownParams } from "@/domain/work-orders/utils/dashboard-drilldown-params";
|
||||
import { avetaPendingDrilldownSearch } from "@/domain/dashboard/utils/work-order-drilldown-links";
|
||||
|
||||
describe("parseDashboardDrilldownParams", () => {
|
||||
it("returns null when no recognized param is present", () => {
|
||||
expect(parseDashboardDrilldownParams(new URLSearchParams())).toBeNull();
|
||||
expect(
|
||||
parseDashboardDrilldownParams(new URLSearchParams({ dateFrom: "2026-09-16" })),
|
||||
).toBeNull();
|
||||
expect(parseDashboardDrilldownParams(new URLSearchParams({ aveta: "0" }))).toBeNull();
|
||||
});
|
||||
|
||||
it("maps dates to a custom advanced-filter range", () => {
|
||||
const filters = parseDashboardDrilldownParams(
|
||||
new URLSearchParams({ dateFrom: "2026-09-14", dateTo: "2026-09-18" }),
|
||||
);
|
||||
|
||||
expect(filters).not.toBeNull();
|
||||
expect(filters?.dateRange).toBe("custom");
|
||||
expect(filters?.customFrom).toBe("2026-09-14");
|
||||
expect(filters?.customTo).toBe("2026-09-18");
|
||||
});
|
||||
|
||||
it("parses the Aveta Pending drilldown and drops unknown statuses", () => {
|
||||
const params = avetaPendingDrilldownSearch("2026-09-16");
|
||||
params.append("statuses", "NotAStatus");
|
||||
const filters = parseDashboardDrilldownParams(params);
|
||||
|
||||
expect(filters).not.toBeNull();
|
||||
expect(filters?.avetaOnly).toBe(true);
|
||||
expect(filters?.docs).toEqual(new Set(["No"]));
|
||||
expect(filters?.statuses).not.toBeNull();
|
||||
expect([...(filters?.statuses ?? [])]).not.toContain("Completed");
|
||||
expect([...(filters?.statuses ?? [])]).not.toContain("NotAStatus");
|
||||
expect(filters?.statuses.has("Scheduled")).toBe(true);
|
||||
expect(filters?.statuses.has("Pending Quote")).toBe(true);
|
||||
});
|
||||
|
||||
it("parses dispatcher and uplift params", () => {
|
||||
const filters = parseDashboardDrilldownParams(
|
||||
new URLSearchParams({
|
||||
dispatchers: " 12 , 13",
|
||||
upliftStatuses: "pending,bogus",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(filters?.dispatchers).toEqual(new Set(["12", "13"]));
|
||||
expect(filters?.hasUplift).toBe(true);
|
||||
expect(filters?.upliftStatuses).toEqual(new Set(["pending"]));
|
||||
});
|
||||
|
||||
it("rejects partial or malformed date ranges", () => {
|
||||
expect(
|
||||
parseDashboardDrilldownParams(
|
||||
new URLSearchParams({ dateFrom: "2026-9-16", dateTo: "2026-09-18" }),
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue