feat(portal): lead dashboard on the home page

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
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 10:25:47 +08:00
1 parent 7ff5c77b78
commit 5eead327a6
10 files changed
+568 -7

No files matched your search

@@ -0,0 +1,38 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
type Req = Parameters<typeof GET>[0];
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { captures: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("/api/dashboard/leads", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(req("/api/dashboard/leads"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the query string to mobile-api", async () => {
const res = await GET(req("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ captures: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2", { token: "jwt-abc" });
});
it("passes an upstream INVALID_PERIOD with its code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Start date must be on or before end date.", status: 400, code: "INVALID_PERIOD" });
const res = await GET(req("/api/dashboard/leads?from=2026-11-30&to=2026-11-01"));
expect(res.status).toBe(400);
expect(((await res.json()) as Record<string, unknown>).code).toBe("INVALID_PERIOD");
});
});
@@ -0,0 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// Proxy for /api/admin/dashboard/leads; mobile-api owns period validation and the BO_DASHBOARD guard.
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/dashboard/leads${new URL(req.url).search}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,60 @@
import type { ReactNode } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { EmptyState } from "@/app/components/ui/states";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { cn } from "@/app/lib/utils";
export interface DashColumn<R> {
label: string;
numeric?: boolean;
cell: (row: R) => ReactNode;
}
/** A titled table that stacks into label/value cards below md (one DOM, CSS only). */
export function DashTable<R>({ title, empty, columns, rows, rowKey }: {
title: string;
empty: string;
columns: DashColumn<R>[];
rows: R[];
rowKey: (row: R) => string;
}) {
return (
<Card>
<CardHeader><CardTitle className="text-base">{title}</CardTitle></CardHeader>
<CardContent>
{rows.length === 0 ? (
<EmptyState title={empty} className="py-6" />
) : (
<Table aria-label={title} className="max-md:block">
<TableHeader className="max-md:hidden">
<TableRow>
{columns.map((c) => (
<TableHead key={c.label} className={cn(c.numeric && "text-right")}>{c.label}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody className="max-md:block">
{rows.map((row) => (
<TableRow key={rowKey(row)} className="max-md:mb-3 max-md:block max-md:rounded-lg max-md:border max-md:p-2">
{columns.map((c) => (
<TableCell
key={c.label}
data-label={c.label}
className={cn(
"max-md:flex max-md:justify-between max-md:gap-4 max-md:whitespace-normal max-md:px-1 max-md:py-1",
"max-md:before:font-medium max-md:before:text-muted-foreground max-md:before:content-[attr(data-label)]",
c.numeric && "text-right tabular max-md:text-left",
)}
>
{c.cell(row)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,189 @@
"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>
);
}
@@ -117,6 +117,36 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
ModulesParent: "Parent",
DashWelcome: "Welcome, {name}",
DashWelcomeFallbackName: "admin",
DashLeadFunnelLabel: "Lead funnel",
DashThisMonth: "This month",
DashLastMonth: "Last month",
DashCustom: "Custom",
DashFrom: "From",
DashTo: "To",
DashRangeReversed: "The start date must not be after the end date.",
DashLoadFailed: "Could not load the dashboard.",
DashCaptures: "Captures",
DashNewLeads: "New leads",
DashWonInPeriod: "Won in period",
DashConversionRate: "Conversion rate",
DashMedianDays: "Median days to win",
DashOverdue: "Overdue follow-ups",
DashFunnel: "Funnel",
DashTrend: "Captures and wins over time",
DashWins: "Wins",
DashByEvent: "By event",
DashBySalesperson: "By salesperson",
DashByInterest: "By interest",
DashEvent: "Event",
DashSalesperson: "Salesperson",
DashInterest: "Interest",
DashAssigned: "Assigned",
DashWorked: "Worked",
DashConversion: "Conversion",
DashOverdueShort: "Overdue",
DashUnassigned: "Unassigned",
DashUnknownUser: "Unknown user",
DashEmpty: "No data for this period",
Close: "Close",
Enabled: "Enabled",
Admin: "Admin",
@@ -0,0 +1,22 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
vi.mock("@/app/lib/clientApi", () => mocks);
import { getLeadDashboard } from "./adminDashboard";
beforeEach(() => mocks.apiGet.mockReset().mockResolvedValue({}));
describe("adminDashboard", () => {
it("sends no query string when no params are given", async () => {
await getLeadDashboard({});
expect(mocks.apiGet).toHaveBeenCalledWith("/api/dashboard/leads");
});
it("sends only the given params", async () => {
await getLeadDashboard({ from: "2026-11-01", to: "2026-11-30", companyId: 2 });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2");
await getLeadDashboard({ companyId: 3 });
expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/dashboard/leads?companyId=3");
});
});
@@ -0,0 +1,32 @@
import { apiGet } from "@/app/lib/clientApi";
export interface LeadDashboard {
from: string;
to: string;
bucket: "DAY" | "MONTH";
captures: number;
newLeads: number;
wonInPeriod: number;
medianDaysToWin: number | null;
overdueFollowUps: number;
funnel: { OPEN: number; CONTACTED: number; QUALIFIED: number; WON: number; LOST: number };
trend: { bucket: string; captures: number; wins: number }[];
events: { eventUuid: string; name: string; companyId: number; captures: number; newLeads: number; won: number }[];
salespeople: { userId: number | null; name: string | null; assigned: number; worked: number; won: number; lost: number; overdue: number }[];
interests: { interestId: number; name: string; captures: number; won: number }[];
}
export interface LeadDashboardParams {
from?: string;
to?: string;
companyId?: number;
}
export function getLeadDashboard({ from, to, companyId }: LeadDashboardParams): Promise<LeadDashboard> {
const qs = new URLSearchParams();
if (from) qs.set("from", from);
if (to) qs.set("to", to);
if (companyId) qs.set("companyId", String(companyId));
const s = qs.toString();
return apiGet<LeadDashboard>(`/api/dashboard/leads${s ? `?${s}` : ""}`);
}
@@ -0,0 +1,173 @@
import { render, screen, waitFor, within, fireEvent } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { pickDate } from "@/test/pickDate";
const mocks = vi.hoisted(() => ({
getLeadDashboard: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminDashboard", () => ({ getLeadDashboard: mocks.getLeadDashboard }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { ApiError } from "@/app/lib/clientApi";
import HomePage from "./page";
const DATA = {
from: "2026-12-01", to: "2026-12-01", bucket: "DAY",
captures: 40, newLeads: 25, wonInPeriod: 8, medianDaysToWin: 4.5, overdueFollowUps: 3,
funnel: { OPEN: 11, CONTACTED: 12, QUALIFIED: 13, WON: 8, LOST: 6 },
trend: [{ bucket: "2026-12-01", captures: 5, wins: 1 }],
events: [{ eventUuid: "ev-1", name: "Expo KL", companyId: 2, captures: 20, newLeads: 10, won: 5 }],
salespeople: [
{ userId: null, name: null, assigned: 7, worked: 2, won: 1, lost: 0, overdue: 4 },
{ userId: 9, name: null, assigned: 0, worked: 0, won: 0, lost: 0, overdue: 0 },
{ userId: 5, name: "Sam", assigned: 10, worked: 6, won: 3, lost: 1, overdue: 2 },
],
interests: [{ interestId: 1, name: "Catering", captures: 15, won: 4 }],
};
const scope = (companyId?: number, showCompanyColumn = false) => ({
companyId, companies: [], showCompanyColumn, codeOf: (id?: number | null) => (id === 2 ? "CV" : ""), setCompanyId: vi.fn(),
});
const tile = (name: string) => within(screen.getByRole("group", { name }));
beforeEach(() => {
mocks.getLeadDashboard.mockReset().mockResolvedValue(DATA);
mocks.useAdminAuth.mockReset().mockReturnValue({ name: "Alice", loading: false, isSuper: false, hasModule: (m: string) => m === "BO_DASHBOARD" });
mocks.useCompanyScope.mockReset().mockReturnValue(scope());
});
afterEach(() => vi.useRealTimers());
describe("home page lead dashboard", () => {
it("shows only the welcome and never calls the API without the module", () => {
mocks.useAdminAuth.mockReturnValue({ name: "Alice", loading: false, hasModule: () => false });
render(<HomePage />);
expect(screen.getByText("Welcome, Alice")).toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
expect(mocks.getLeadDashboard).not.toHaveBeenCalled();
});
it("shows the welcome plus tiles with the This month default (no from/to)", async () => {
render(<HomePage />);
expect(screen.getByText("Welcome, Alice")).toBeInTheDocument();
await screen.findByRole("group", { name: "Captures" });
expect(tile("Captures").getByText("40")).toBeInTheDocument();
expect(tile("New leads").getByText("25")).toBeInTheDocument();
expect(tile("Won in period").getByText("8")).toBeInTheDocument();
expect(tile("Conversion rate").getByText("20%")).toBeInTheDocument();
expect(tile("Median days to win").getByText("4.5")).toBeInTheDocument();
expect(tile("Overdue follow-ups").getByText("3")).toBeInTheDocument();
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: undefined });
});
it("shows a dash for a null median and for zero captures", async () => {
mocks.getLeadDashboard.mockResolvedValue({ ...DATA, captures: 0, medianDaysToWin: null });
render(<HomePage />);
await waitFor(() => expect(tile("Conversion rate").getByText("–")).toBeInTheDocument());
expect(tile("Median days to win").getByText("–")).toBeInTheDocument();
});
it("shows the funnel counts and the trend chart", async () => {
const { container } = render(<HomePage />);
const funnel = await screen.findByRole("list", { name: "Lead funnel" });
const items = within(funnel).getAllByRole("listitem").map((li) => li.textContent);
expect(items).toEqual(["Open11", "Contacted12", "Qualified13", "Won8", "Lost6"]);
expect(container.querySelector('[data-slot="chart"]')).toBeInTheDocument();
});
it("shows the by-event, by-salesperson and by-interest tables", async () => {
render(<HomePage />);
const ev = within(await screen.findByRole("table", { name: "By event" }));
expect(ev.getByRole("link", { name: "Expo KL" })).toHaveAttribute("href", "/event-leads/ev-1");
expect(ev.getByText("25%")).toBeInTheDocument();
expect(ev.queryByText("Company")).not.toBeInTheDocument();
const sp = within(screen.getByRole("table", { name: "By salesperson" }));
expect(sp.getByText("Unassigned")).toBeInTheDocument();
expect(sp.getByText("Unknown user")).toBeInTheDocument();
expect(sp.getByText("Sam")).toBeInTheDocument();
expect(sp.getByText("30%")).toBeInTheDocument();
expect(sp.getAllByText("–").length).toBe(1);
const rowText = (name: string) => Array.from(sp.getByText(name).closest("tr")!.querySelectorAll("td")).map((td) => td.textContent);
expect(rowText("Unassigned")).toEqual(["Unassigned", "7", "2", "1", "0", "14%", "4"]);
expect(rowText("Sam")).toEqual(["Sam", "10", "6", "3", "1", "30%", "2"]);
const it = within(screen.getByRole("table", { name: "By interest" }));
expect(it.getByText("Catering")).toBeInTheDocument();
});
it("shows empty-state lines for empty lists", async () => {
mocks.getLeadDashboard.mockResolvedValue({ ...DATA, events: [], salespeople: [], interests: [] });
render(<HomePage />);
await waitFor(() => expect(screen.getAllByText("No data for this period")).toHaveLength(3));
});
it("sends the previous Malaysian month for Last month", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-12-01T10:00:00+08:00") });
render(<HomePage />);
fireEvent.click(screen.getByRole("button", { name: "Last month" }));
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-11-01", to: "2026-11-30", companyId: undefined }));
});
it("uses Malaysian time near midnight UTC and across a year boundary", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date("2026-12-31T20:00:00Z") }); // 2027-01-01 04:00 in KL
render(<HomePage />);
fireEvent.click(screen.getByRole("button", { name: "Last month" }));
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-12-01", to: "2026-12-31", companyId: undefined }));
});
it("rejects a reversed custom range without calling the API", async () => {
render(<HomePage />);
await screen.findByRole("group", { name: "Captures" });
fireEvent.click(screen.getByRole("button", { name: "Custom" }));
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
mocks.getLeadDashboard.mockClear();
pickDate("From", "2026-11-20");
pickDate("To", "2026-11-10");
expect(await screen.findByText("The start date must not be after the end date.")).toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Captures" })).not.toBeInTheDocument();
expect(mocks.getLeadDashboard).not.toHaveBeenCalled();
});
it("sends a valid custom range", async () => {
render(<HomePage />);
await screen.findByRole("group", { name: "Captures" });
fireEvent.click(screen.getByRole("button", { name: "Custom" }));
pickDate("From", "2026-11-10");
pickDate("To", "2026-11-20");
await waitFor(() => expect(mocks.getLeadDashboard).toHaveBeenLastCalledWith({ from: "2026-11-10", to: "2026-11-20", companyId: undefined }));
});
it("sends the picked company and shows no Company column", async () => {
mocks.useCompanyScope.mockReturnValue(scope(2, false));
render(<HomePage />);
const ev = within(await screen.findByRole("table", { name: "By event" }));
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: 2 });
expect(ev.queryByText("Company")).not.toBeInTheDocument();
});
it("on All companies sends no companyId and shows the Company column with the code", async () => {
mocks.useCompanyScope.mockReturnValue(scope(undefined, true));
render(<HomePage />);
const ev = within(await screen.findByRole("table", { name: "By event" }));
expect(mocks.getLeadDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined, companyId: undefined });
expect(ev.getByText("Company")).toBeInTheDocument();
expect(ev.getByText("CV")).toBeInTheDocument();
});
it("shows the API message for INVALID_PERIOD", async () => {
mocks.getLeadDashboard.mockRejectedValue(new ApiError("Start date must be on or before end date.", 400, { error: "Start date must be on or before end date.", code: "INVALID_PERIOD" }));
render(<HomePage />);
expect(await screen.findByText("Start date must be on or before end date.")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();
});
it("shows a retryable error for other failures", async () => {
mocks.getLeadDashboard.mockRejectedValueOnce(new Error("boom"));
render(<HomePage />);
expect(await screen.findByText("Could not load the dashboard.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await screen.findByRole("group", { name: "Captures" });
expect(tile("Captures").getByText("40")).toBeInTheDocument();
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Alice" }) }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Alice", hasModule: () => false }) }));
import HomePage from "./page";
+10 -6
View File
@@ -2,16 +2,20 @@
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { LeadDashboard } from "@/app/components/dashboard/LeadDashboard";
export default function HomePage() {
const t = useT();
const { name } = useAdminAuth();
const { name, hasModule } = useAdminAuth();
return (
<div className="space-y-2">
<h1 className="text-xl">{t("BackOfficeTitle")}</h1>
<p className="text-sm text-muted-foreground">
{t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })}
</p>
<div className="space-y-6">
<div className="space-y-2">
<h1 className="text-xl">{t("BackOfficeTitle")}</h1>
<p className="text-sm text-muted-foreground">
{t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })}
</p>
</div>
{hasModule("BO_DASHBOARD") && <LeadDashboard />}
</div>
);
}