Users with BO_DASHBOARD get period presets, capture and win tiles, the status funnel, a captures/wins trend and breakdowns by event, salesperson and interest; everyone else keeps the welcome. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
190 lines
10 KiB
TypeScript
190 lines
10 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useMemo, useState } from "react";
|
||
import Link from "next/link";
|
||
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
||
import { Button } from "@/app/components/ui/button";
|
||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/app/components/ui/chart";
|
||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||
import { ErrorState } from "@/app/components/ui/states";
|
||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||
import { ApiError } from "@/app/lib/clientApi";
|
||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||
import { getLeadDashboard, type LeadDashboard } from "@/app/lib/services/adminDashboard";
|
||
import { DashTable, type DashColumn } from "./DashTable";
|
||
|
||
type Preset = "this" | "last" | "custom";
|
||
type Range = { from?: string; to?: string };
|
||
|
||
const DASH = "–";
|
||
const pct = (num: number, den: number) => (den > 0 ? `${Math.round((num / den) * 100)}%` : DASH);
|
||
|
||
/** First and last day of the previous calendar month, as seen in Kuala Lumpur right now. */
|
||
function lastMonthRange(): Range {
|
||
const today = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
|
||
const [y, m] = today.split("-").map(Number);
|
||
const py = m === 1 ? y - 1 : y;
|
||
const pm = m === 1 ? 12 : m - 1;
|
||
const mm = String(pm).padStart(2, "0");
|
||
const lastDay = new Date(Date.UTC(y, m - 1, 0)).getUTCDate();
|
||
return { from: `${py}-${mm}-01`, to: `${py}-${mm}-${lastDay}` };
|
||
}
|
||
|
||
function bucketLabel(bucket: string, kind: "DAY" | "MONTH"): string {
|
||
const [y, m, d] = bucket.split("-");
|
||
if (kind === "DAY") return `${d}/${m}`;
|
||
return new Date(Date.UTC(Number(y), Number(m) - 1, 1)).toLocaleString("en-GB", { month: "short", year: "numeric", timeZone: "UTC" });
|
||
}
|
||
|
||
function Tile({ label, value }: { label: string; value: string }) {
|
||
return (
|
||
<div role="group" aria-label={label} className="rounded-xl border bg-card p-4">
|
||
<div className="text-sm text-muted-foreground">{label}</div>
|
||
<div className="mt-1 text-2xl font-semibold tabular">{value}</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function LeadDashboard() {
|
||
const t = useT();
|
||
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
|
||
const [preset, setPreset] = useState<Preset>("this");
|
||
const [customFrom, setCustomFrom] = useState("");
|
||
const [customTo, setCustomTo] = useState("");
|
||
const [data, setData] = useState<LeadDashboard | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [refusedPeriod, setRefusedPeriod] = useState(false);
|
||
const [reloadKey, setReloadKey] = useState(0);
|
||
|
||
const range = useMemo<Range | null>(() => {
|
||
if (preset === "this") return {};
|
||
if (preset === "last") return lastMonthRange();
|
||
return customFrom && customTo && customFrom <= customTo ? { from: customFrom, to: customTo } : null;
|
||
}, [preset, customFrom, customTo]);
|
||
const reversed = preset === "custom" && !!customFrom && !!customTo && customFrom > customTo;
|
||
const from = range?.from;
|
||
const to = range?.to;
|
||
|
||
useEffect(() => {
|
||
if (!range) return;
|
||
let cancelled = false;
|
||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets data/error before the period/company/reloadKey-triggered fetch below, which is the actual synchronization.
|
||
setData(null);
|
||
setError(null);
|
||
getLeadDashboard({ from, to, companyId })
|
||
.then((d) => { if (!cancelled) setData(d); })
|
||
.catch((err: unknown) => {
|
||
if (cancelled) return;
|
||
const refused = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "INVALID_PERIOD";
|
||
setError(refused ? err.message : t("DashLoadFailed"));
|
||
setRefusedPeriod(refused);
|
||
});
|
||
return () => { cancelled = true; };
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps -- `range` is derived from from/to.
|
||
}, [from, to, companyId, reloadKey, !!range, t]);
|
||
|
||
const presets: [Preset, string][] = [["this", t("DashThisMonth")], ["last", t("DashLastMonth")], ["custom", t("DashCustom")]];
|
||
const chartConfig = { captures: { label: t("DashCaptures"), color: "var(--chart-1)" }, wins: { label: t("DashWins"), color: "var(--chart-2)" } } satisfies ChartConfig;
|
||
|
||
const eventCols: DashColumn<LeadDashboard["events"][number]>[] = [
|
||
{ label: t("DashEvent"), cell: (r) => <Link href={`/event-leads/${r.eventUuid}`} className="font-medium text-primary underline-offset-4 hover:underline">{r.name}</Link> },
|
||
...(showCompanyColumn ? [{ label: t("Company"), cell: (r: { companyId: number }) => codeOf(r.companyId) }] : []),
|
||
{ label: t("DashCaptures"), numeric: true, cell: (r) => r.captures },
|
||
{ label: t("LeadNew"), numeric: true, cell: (r) => r.newLeads },
|
||
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
|
||
{ label: t("DashConversion"), numeric: true, cell: (r) => pct(r.won, r.captures) },
|
||
];
|
||
const salesCols: DashColumn<LeadDashboard["salespeople"][number]>[] = [
|
||
{ label: t("DashSalesperson"), cell: (r) => (r.userId == null ? t("DashUnassigned") : r.name ?? t("DashUnknownUser")) },
|
||
{ label: t("DashAssigned"), numeric: true, cell: (r) => r.assigned },
|
||
{ label: t("DashWorked"), numeric: true, cell: (r) => r.worked },
|
||
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
|
||
{ label: t("LeadLost"), numeric: true, cell: (r) => r.lost },
|
||
{ label: t("DashConversion"), numeric: true, cell: (r) => pct(r.won, r.assigned) },
|
||
{ label: t("DashOverdueShort"), numeric: true, cell: (r) => r.overdue },
|
||
];
|
||
const interestCols: DashColumn<LeadDashboard["interests"][number]>[] = [
|
||
{ label: t("DashInterest"), cell: (r) => r.name },
|
||
{ label: t("DashCaptures"), numeric: true, cell: (r) => r.captures },
|
||
{ label: t("LeadWon"), numeric: true, cell: (r) => r.won },
|
||
];
|
||
|
||
const funnelRows: [keyof LeadDashboard["funnel"], string][] = [
|
||
["OPEN", t("LeadOpen")], ["CONTACTED", t("LeadContacted")], ["QUALIFIED", t("LeadQualified")], ["WON", t("LeadWon")], ["LOST", t("LeadLost")],
|
||
];
|
||
|
||
return (
|
||
<div className="space-y-4">
|
||
<div className="flex flex-wrap items-end gap-2">
|
||
{presets.map(([key, label]) => (
|
||
<Button key={key} variant={preset === key ? "default" : "outline"} aria-pressed={preset === key} onClick={() => setPreset(key)}>{label}</Button>
|
||
))}
|
||
{preset === "custom" && (
|
||
<>
|
||
<DatePicker aria-label={t("DashFrom")} value={customFrom} onChange={setCustomFrom} className="w-40" />
|
||
<DatePicker aria-label={t("DashTo")} value={customTo} onChange={setCustomTo} className="w-40" />
|
||
</>
|
||
)}
|
||
</div>
|
||
{reversed && <p role="alert" className="text-sm text-destructive">{t("DashRangeReversed")}</p>}
|
||
|
||
{range && error && <ErrorState message={error} onRetry={refusedPeriod ? undefined : () => setReloadKey((k) => k + 1)} />}
|
||
{range && !error && !data && <Skeleton className="h-40 w-full" />}
|
||
|
||
{range && data && (
|
||
<>
|
||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-6">
|
||
<Tile label={t("DashCaptures")} value={String(data.captures)} />
|
||
<Tile label={t("DashNewLeads")} value={String(data.newLeads)} />
|
||
<Tile label={t("DashWonInPeriod")} value={String(data.wonInPeriod)} />
|
||
<Tile label={t("DashConversionRate")} value={pct(data.funnel.WON, data.captures)} />
|
||
<Tile label={t("DashMedianDays")} value={data.medianDaysToWin == null ? DASH : String(data.medianDaysToWin)} />
|
||
<Tile label={t("DashOverdue")} value={String(data.overdueFollowUps)} />
|
||
</div>
|
||
|
||
<div className="grid gap-4 lg:grid-cols-2">
|
||
<Card>
|
||
<CardHeader><CardTitle className="text-base">{t("DashFunnel")}</CardTitle></CardHeader>
|
||
<CardContent>
|
||
<ul aria-label={t("DashLeadFunnelLabel")} className="space-y-2">
|
||
{funnelRows.map(([key, label]) => {
|
||
const max = Math.max(1, ...Object.values(data.funnel));
|
||
return (
|
||
<li key={key} className="flex items-center gap-2 text-sm">
|
||
<span className="w-24 shrink-0">{label}</span>
|
||
<span className="h-4 min-w-0 flex-1"><span className="block h-full rounded bg-primary" style={{ width: `${(data.funnel[key] / max) * 100}%` }} /></span>
|
||
<span className="w-10 shrink-0 text-right tabular">{data.funnel[key]}</span>
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
</CardContent>
|
||
</Card>
|
||
<Card>
|
||
<CardHeader><CardTitle className="text-base">{t("DashTrend")}</CardTitle></CardHeader>
|
||
<CardContent>
|
||
<ChartContainer config={chartConfig} role="img" aria-label={t("DashTrend")} className="aspect-auto h-56 w-full">
|
||
<BarChart data={data.trend.map((p) => ({ ...p, label: bucketLabel(p.bucket, data.bucket) }))}>
|
||
<CartesianGrid vertical={false} />
|
||
<XAxis dataKey="label" tickLine={false} axisLine={false} />
|
||
<YAxis allowDecimals={false} width={32} tickLine={false} axisLine={false} />
|
||
<ChartTooltip content={<ChartTooltipContent />} />
|
||
<Bar dataKey="captures" fill="var(--color-captures)" radius={2} />
|
||
<Bar dataKey="wins" fill="var(--color-wins)" radius={2} />
|
||
</BarChart>
|
||
</ChartContainer>
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
|
||
<DashTable title={t("DashByEvent")} empty={t("DashEmpty")} columns={eventCols} rows={data.events} rowKey={(r) => r.eventUuid} />
|
||
<DashTable title={t("DashBySalesperson")} empty={t("DashEmpty")} columns={salesCols} rows={data.salespeople} rowKey={(r) => String(r.userId)} />
|
||
<DashTable title={t("DashByInterest")} empty={t("DashEmpty")} columns={interestCols} rows={data.interests} rowKey={(r) => String(r.interestId)} />
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|