diff --git a/solvway-admin-portal/app/api/dashboard/leads/route.test.ts b/solvway-admin-portal/app/api/dashboard/leads/route.test.ts new file mode 100644 index 0000000..72d6ef5 --- /dev/null +++ b/solvway-admin-portal/app/api/dashboard/leads/route.test.ts @@ -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[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).code).toBe("INVALID_PERIOD"); + }); +}); diff --git a/solvway-admin-portal/app/api/dashboard/leads/route.ts b/solvway-admin-portal/app/api/dashboard/leads/route.ts new file mode 100644 index 0000000..de32eff --- /dev/null +++ b/solvway-admin-portal/app/api/dashboard/leads/route.ts @@ -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(`/api/admin/dashboard/leads${new URL(req.url).search}`, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/components/dashboard/DashTable.tsx b/solvway-admin-portal/app/components/dashboard/DashTable.tsx new file mode 100644 index 0000000..82ca5db --- /dev/null +++ b/solvway-admin-portal/app/components/dashboard/DashTable.tsx @@ -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 { + 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({ title, empty, columns, rows, rowKey }: { + title: string; + empty: string; + columns: DashColumn[]; + rows: R[]; + rowKey: (row: R) => string; +}) { + return ( + + {title} + + {rows.length === 0 ? ( + + ) : ( + + + + {columns.map((c) => ( + {c.label} + ))} + + + + {rows.map((row) => ( + + {columns.map((c) => ( + + {c.cell(row)} + + ))} + + ))} + +
+ )} +
+
+ ); +} diff --git a/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx b/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx new file mode 100644 index 0000000..13406d0 --- /dev/null +++ b/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx @@ -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 ( +
+
{label}
+
{value}
+
+ ); +} + +export function LeadDashboard() { + const t = useT(); + const { companyId, showCompanyColumn, codeOf } = useCompanyScope(); + const [preset, setPreset] = useState("this"); + const [customFrom, setCustomFrom] = useState(""); + const [customTo, setCustomTo] = useState(""); + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [refusedPeriod, setRefusedPeriod] = useState(false); + const [reloadKey, setReloadKey] = useState(0); + + const range = useMemo(() => { + 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[] = [ + { label: t("DashEvent"), cell: (r) => {r.name} }, + ...(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[] = [ + { 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[] = [ + { 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 ( +
+
+ {presets.map(([key, label]) => ( + + ))} + {preset === "custom" && ( + <> + + + + )} +
+ {reversed &&

{t("DashRangeReversed")}

} + + {range && error && setReloadKey((k) => k + 1)} />} + {range && !error && !data && } + + {range && data && ( + <> +
+ + + + + + +
+ +
+ + {t("DashFunnel")} + +
    + {funnelRows.map(([key, label]) => { + const max = Math.max(1, ...Object.values(data.funnel)); + return ( +
  • + {label} + + {data.funnel[key]} +
  • + ); + })} +
+
+
+ + {t("DashTrend")} + + + ({ ...p, label: bucketLabel(p.bucket, data.bucket) }))}> + + + + } /> + + + + + + +
+ + r.eventUuid} /> + String(r.userId)} /> + String(r.interestId)} /> + + )} +
+ ); +} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index 29dc2d6..c887374 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -117,6 +117,36 @@ export const DEFAULT_MESSAGES: Record = { 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", diff --git a/solvway-admin-portal/app/lib/services/adminDashboard.test.ts b/solvway-admin-portal/app/lib/services/adminDashboard.test.ts new file mode 100644 index 0000000..ff977f4 --- /dev/null +++ b/solvway-admin-portal/app/lib/services/adminDashboard.test.ts @@ -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"); + }); +}); diff --git a/solvway-admin-portal/app/lib/services/adminDashboard.ts b/solvway-admin-portal/app/lib/services/adminDashboard.ts new file mode 100644 index 0000000..ba7c62d --- /dev/null +++ b/solvway-admin-portal/app/lib/services/adminDashboard.ts @@ -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 { + 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(`/api/dashboard/leads${s ? `?${s}` : ""}`); +} diff --git a/solvway-admin-portal/app/page.dashboard.test.tsx b/solvway-admin-portal/app/page.dashboard.test.tsx new file mode 100644 index 0000000..cc77082 --- /dev/null +++ b/solvway-admin-portal/app/page.dashboard.test.tsx @@ -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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + }); +}); diff --git a/solvway-admin-portal/app/page.test.tsx b/solvway-admin-portal/app/page.test.tsx index 5886188..1a30b7d 100644 --- a/solvway-admin-portal/app/page.test.tsx +++ b/solvway-admin-portal/app/page.test.tsx @@ -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"; diff --git a/solvway-admin-portal/app/page.tsx b/solvway-admin-portal/app/page.tsx index ca1ca3b..3e6b5df 100644 --- a/solvway-admin-portal/app/page.tsx +++ b/solvway-admin-portal/app/page.tsx @@ -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 ( -
-

{t("BackOfficeTitle")}

-

- {t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })} -

+
+
+

{t("BackOfficeTitle")}

+

+ {t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })} +

+
+ {hasModule("BO_DASHBOARD") && }
); }