Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
642 lines
29 KiB
TypeScript
642 lines
29 KiB
TypeScript
"use client";
|
||
|
||
import { Suspense, useCallback, useEffect, useState, type ReactNode } from "react";
|
||
import Link from "next/link";
|
||
import { Area, AreaChart, CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
|
||
import { Apple, CircleDollarSign, Gift, ShoppingBag, UserPlus } from "lucide-react";
|
||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||
import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent } from "@/app/components/ui/chart";
|
||
import type { ChartConfig } from "@/app/components/ui/chart";
|
||
import { Button } from "@/app/components/ui/button";
|
||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||
import { ErrorState } from "@/app/components/ui/states";
|
||
import { PageHeader } from "@/app/components/ui/page-header";
|
||
import { DrillLink } from "@/app/components/dashboard/drill-link";
|
||
import { ActionStrip } from "@/app/components/dashboard/action-strip";
|
||
import { HeroBand } from "@/app/components/dashboard/hero-band";
|
||
import { ChartCard } from "@/app/components/dashboard/chart-card";
|
||
import { EventDashboard } from "@/app/components/dashboard/EventDashboard";
|
||
import { LineChartSkeleton } from "@/app/components/ui/chart-skeleton";
|
||
import type { DashboardData } from "@/app/lib/services/adminDashboard";
|
||
import { CATEGORY_TONE_COLOR, channelRows, dashboardLinks, getDashboard, rewardLabel } from "@/app/lib/services/adminDashboard";
|
||
import { formatMonth } from "@/app/lib/services/period";
|
||
import { compactRM, formatPoints, formatRM } from "@/app/lib/format";
|
||
import { MEMBER_RANK_LABEL_CODES, MEMBER_STATUS_LABEL_CODES, memberStatusLabelCode } from "@/app/lib/memberLabels";
|
||
import type { AdminMemberStatus } from "@/app/lib/types";
|
||
import { cn } from "@/app/lib/utils";
|
||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||
import { useAclSidebar } from "@/app/lib/useAclSidebar";
|
||
import { useSellableCountry } from "@/app/lib/hooks/useSellableCountry";
|
||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||
import type { Translate } from "@/app/lib/i18n/t";
|
||
import type { SidebarLink } from "@/app/lib/aclSidebar";
|
||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||
import { DateRangePicker } from "@/app/components/ui/date-range-picker";
|
||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
||
import { periodRange } from "@/app/lib/malaysiaPeriod";
|
||
import { formatDmy } from "@/app/lib/date-input";
|
||
|
||
// Series labels show in chart tooltips, so they are translated when the chart renders.
|
||
// Revenue in the contrast colour (owner request, 2026-10-23: more dusty blue / teal on the dashboard).
|
||
const revenueConfig = (t: Translate) => ({ amount: { label: t("DashRevenue"), color: "var(--contrast)" } }) satisfies ChartConfig;
|
||
|
||
// Fixed chart tokens as classes.
|
||
const SERIES_BG = ["bg-chart-1", "bg-chart-2", "bg-chart-3", "bg-chart-4", "bg-chart-5"];
|
||
|
||
// Five tiles, one row on wide screens; shared by the tiles and the loading skeleton.
|
||
/** The hero band's secondary tiles (orders, new members, Apples, Acorns). */
|
||
const HERO_STAT_COUNT = 4;
|
||
|
||
// babyboo's ranks, always listed (a rank with no members is 0, not missing).
|
||
const RANKS = ["OTTER", "SQUIRREL", "GIRAFFE"] as const;
|
||
const rankLabel = (rank: (typeof RANKS)[number], t: Translate) => t(MEMBER_RANK_LABEL_CODES[rank]);
|
||
|
||
// One Member growth line per rank, in the Rank mix colours; labels show in the legend and tooltip.
|
||
const growthConfig = (t: Translate) =>
|
||
Object.fromEntries(RANKS.map((rank, i) => [rank, { label: rankLabel(rank, t), color: `var(--chart-${i + 1})` }])) satisfies ChartConfig;
|
||
|
||
/** Fractional change against the previous period; null when the previous figure is zero (no base). */
|
||
const change = (current: number, previous: number) => (previous === 0 ? null : (current - previous) / previous);
|
||
|
||
/** "2026-10-03" -> "03/10", for dense date axes. */
|
||
const shortDate = (date: string) => `${date.slice(8, 10)}/${date.slice(5, 7)}`;
|
||
|
||
const STATUS_FILL: Record<string, string> = { Y: "bg-positive", N: "bg-warning", S: "bg-negative" };
|
||
|
||
type DashPreset = "month" | "lastMonth" | "custom";
|
||
const PRESETS: { value: DashPreset; label: string }[] = [
|
||
{ value: "month", label: "DashThisMonth" },
|
||
{ value: "lastMonth", label: "DashLastMonth" },
|
||
{ value: "custom", label: "DashPresetCustom" },
|
||
];
|
||
|
||
/**
|
||
* "Aug 2026" for a whole calendar month, or for the default period (this month to today); otherwise the dates,
|
||
* e.g. "01/08/2026 – 10/08/2026".
|
||
*/
|
||
function periodLabel(from: string, to: string, isDefault: boolean): string {
|
||
const [y, m] = from.split("-").map(Number);
|
||
const monthEnd = new Date(Date.UTC(y, m, 0)).toISOString().slice(0, 10);
|
||
return from.endsWith("-01") && (to === monthEnd || (isDefault && from.slice(0, 7) === to.slice(0, 7)))
|
||
? formatMonth(from.slice(0, 7))
|
||
: `${formatDmy(from)} – ${formatDmy(to)}`;
|
||
}
|
||
|
||
/** Homepage dashboards in default order, each gated by its own module (add-dashboard-switcher-event). */
|
||
const DASHBOARDS = [
|
||
{ key: "general", module: "BO_DASHBOARD", label: "DashGeneral" },
|
||
{ key: "event", module: "BO_DASHBOARD_EVENT", label: "DashEvent" },
|
||
] as const;
|
||
type DashboardKey = (typeof DASHBOARDS)[number]["key"];
|
||
|
||
function DashboardSkeleton() {
|
||
return (
|
||
<div className="space-y-4">
|
||
{/* Mirrors the hero band: the lead figure, then four stat tiles. */}
|
||
<div className="grid gap-6 rounded-2xl bg-muted p-6 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] lg:p-8">
|
||
<div className="space-y-4">
|
||
<Skeleton className="h-4 w-32" />
|
||
<Skeleton className="h-12 w-56" />
|
||
<Skeleton className="h-12 w-full" />
|
||
</div>
|
||
<div className="grid gap-3 sm:grid-cols-2">
|
||
{Array.from({ length: HERO_STAT_COUNT }).map((_, i) => (
|
||
<div key={i} className="space-y-2 rounded-xl bg-card p-4">
|
||
<Skeleton className="h-3 w-24" />
|
||
<Skeleton className="h-7 w-28" />
|
||
</div>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<div className="grid gap-4 lg:grid-cols-3">
|
||
<Card className="lg:col-span-2">
|
||
<CardHeader>
|
||
<Skeleton className="h-5 w-40" />
|
||
</CardHeader>
|
||
<CardContent className="h-[300px]">
|
||
<LineChartSkeleton />
|
||
</CardContent>
|
||
</Card>
|
||
<Card>
|
||
<CardHeader>
|
||
<Skeleton className="h-5 w-32" />
|
||
</CardHeader>
|
||
<CardContent className="space-y-4">
|
||
{[0, 1, 2].map((i) => (
|
||
<div key={i} className="space-y-1.5">
|
||
<Skeleton className="h-4 w-full" />
|
||
<Skeleton className="h-1.5 w-full" />
|
||
</div>
|
||
))}
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Horizontal proportion bar with the figure always present as text. */
|
||
function ProportionRow({ label, value, share, barClass, barColor, href }: { label: string; value: string; share: number; barClass?: string; barColor?: string; href?: string }) {
|
||
const row = (
|
||
<div className="space-y-1.5">
|
||
<div className="flex items-baseline justify-between gap-2 text-sm">
|
||
<span className="truncate">{label}</span>
|
||
<span className="tabular shrink-0 text-muted-foreground">{value}</span>
|
||
</div>
|
||
<div className="h-1.5 overflow-hidden rounded-full bg-muted" aria-hidden="true">
|
||
<div className={cn("h-full rounded-full transition-[width] duration-500", barClass)} style={{ width: `${share}%`, backgroundColor: barColor }} />
|
||
</div>
|
||
</div>
|
||
);
|
||
return href ? (
|
||
<DrillLink href={href} className="-mx-2 px-2 py-1">
|
||
{row}
|
||
</DrillLink>
|
||
) : (
|
||
row
|
||
);
|
||
}
|
||
|
||
/** Leaf links of the sidebar, in sidebar order (groups are flattened). */
|
||
const leafLinks = (links: SidebarLink[]): SidebarLink[] => links.flatMap(l => (l.url === "" ? leafLinks(l.children) : [l]));
|
||
|
||
/** Homepage for an admin whose role is granted no dashboard module: who they are and where they can go. No figures. */
|
||
function WelcomePage() {
|
||
const { name, roles } = useAdminAuth();
|
||
const t = useT();
|
||
const tiles = leafLinks(useAclSidebar()).filter(l => l.url !== "/");
|
||
return (
|
||
<>
|
||
<PageHeader title={t("DashWelcome", { name: name ?? t("DashWelcomeFallbackName") })} description={roles.map(r => r.name).join(", ")} />
|
||
<nav aria-label={t("DashYourModules")} className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||
{tiles.map(l => (
|
||
<Link key={l.url} href={l.url} className="rounded-xl border bg-card px-4 py-4 text-sm font-medium hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||
{t(l.name)}
|
||
</Link>
|
||
))}
|
||
</nav>
|
||
</>
|
||
);
|
||
}
|
||
|
||
export default function HomePage() {
|
||
const { loading, hasModule } = useAdminAuth();
|
||
if (loading) return null;
|
||
const granted = DASHBOARDS.filter(d => hasModule(d.module)).map(d => d.key);
|
||
if (granted.length === 0) return <WelcomePage />;
|
||
return (
|
||
<Suspense fallback={null}>
|
||
<Dashboards granted={granted} />
|
||
</Suspense>
|
||
);
|
||
}
|
||
|
||
/** Shows the chosen granted dashboard; with two or more granted, a header select switches between them. */
|
||
function Dashboards({ granted }: { granted: DashboardKey[] }) {
|
||
const t = useT();
|
||
const searchParams = useSearchParams();
|
||
const router = useRouter();
|
||
const pathname = usePathname();
|
||
const asked = searchParams.get("dashboard");
|
||
const current = granted.find(k => k === asked) ?? granted[0];
|
||
|
||
const choose = (key: DashboardKey) => {
|
||
// A fresh query: the other dashboard's params (the General period) do not carry over.
|
||
router.replace(key === granted[0] ? pathname : `${pathname}?dashboard=${key}`);
|
||
};
|
||
|
||
const switcher =
|
||
granted.length > 1 ? (
|
||
<Select value={current} onValueChange={v => choose(v as DashboardKey)}>
|
||
<SelectTrigger aria-label={t("BO_DASHBOARD")} className="h-9 w-[140px]">
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{DASHBOARDS.filter(d => granted.includes(d.key)).map(d => (
|
||
<SelectItem key={d.key} value={d.key}>
|
||
{t(d.label)}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
) : null;
|
||
|
||
return current === "event" ? <EventDashboard switcher={switcher} /> : <DashboardPage switcher={switcher} />;
|
||
}
|
||
|
||
function DashboardPage({ switcher }: { switcher?: ReactNode }) {
|
||
const t = useT();
|
||
const [reportingPre, reportingPost] = t("DashReportingPeriod").split("{period}");
|
||
const [data, setData] = useState<DashboardData | null>(null);
|
||
const [loading, setLoading] = useState(true);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [reloadKey, setReloadKey] = useState(0);
|
||
const { countries, showPicker, code, setCode, country, currency } = useSellableCountry();
|
||
|
||
const retry = useCallback(() => setReloadKey(k => k + 1), []);
|
||
|
||
const searchParams = useSearchParams();
|
||
const router = useRouter();
|
||
const pathname = usePathname();
|
||
const from = searchParams.get("from") ?? "";
|
||
const to = searchParams.get("to") ?? "";
|
||
// A half-picked custom range and an explicit "Custom range" choice live here, tied to the URL period they were
|
||
// made on: any URL change (a pick, or the sidebar link back to "/") discards them. The URL only ever holds a
|
||
// whole period.
|
||
const urlKey = `${from}|${to}`;
|
||
const [local, setLocal] = useState<{ key: string; draft: { from: string; to: string } | null; custom: boolean }>({
|
||
key: urlKey,
|
||
draft: null,
|
||
custom: false,
|
||
});
|
||
if (local.key !== urlKey) setLocal({ key: urlKey, draft: null, custom: false }); // reset during render, not in an effect
|
||
const { draft, custom: customPicked } = local.key === urlKey ? local : { draft: null, custom: false };
|
||
const setDraft = (d: { from: string; to: string } | null) => setLocal(l => ({ ...l, draft: d }));
|
||
const setCustomPicked = (c: boolean) => setLocal(l => ({ ...l, custom: c }));
|
||
|
||
const setPeriod = useCallback(
|
||
(range: { from: string; to: string }) => {
|
||
const q = new URLSearchParams(searchParams.toString());
|
||
if (range.from && range.to) {
|
||
q.set("from", range.from);
|
||
q.set("to", range.to);
|
||
} else {
|
||
q.delete("from");
|
||
q.delete("to");
|
||
}
|
||
const query = q.toString();
|
||
router.replace(query ? `${pathname}?${query}` : pathname);
|
||
},
|
||
[searchParams, router, pathname],
|
||
);
|
||
|
||
const last = periodRange("lastMonth");
|
||
const preset: DashPreset = customPicked
|
||
? "custom"
|
||
: !from && !to
|
||
? "month"
|
||
: from === last.from && to === last.to
|
||
? "lastMonth"
|
||
: "custom";
|
||
|
||
const choosePreset = (value: DashPreset) => {
|
||
setDraft(null);
|
||
setCustomPicked(value === "custom");
|
||
if (value === "month") setPeriod({ from: "", to: "" });
|
||
if (value === "lastMonth") setPeriod(last);
|
||
};
|
||
const chooseRange = (range: { from: string; to: string }) => {
|
||
if (range.from && !range.to) {
|
||
setDraft(range);
|
||
return;
|
||
}
|
||
setDraft(null);
|
||
setPeriod(range); // the new URL period decides the preset (a non-preset range shows "Custom range")
|
||
};
|
||
|
||
useEffect(() => {
|
||
let cancelled = false;
|
||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the reloadKey-triggered fetch below, which is the actual synchronization.
|
||
setLoading(true);
|
||
setError(null);
|
||
getDashboard({ from: from || undefined, to: to || undefined, country })
|
||
.then(result => {
|
||
if (!cancelled) setData(result);
|
||
})
|
||
.catch((err: unknown) => {
|
||
if (!cancelled) setError(err instanceof Error ? err.message : "DashLoadFailed");
|
||
})
|
||
.finally(() => {
|
||
if (!cancelled) setLoading(false);
|
||
});
|
||
return () => {
|
||
cancelled = true;
|
||
};
|
||
}, [reloadKey, from, to, country]);
|
||
|
||
const pickerValue = draft ?? { from: from || data?.from || "", to: to || data?.to || "" };
|
||
const header = (
|
||
<>
|
||
<PageHeader
|
||
title={t("BO_DASHBOARD")}
|
||
description={
|
||
data && !loading && !error ? (
|
||
<>
|
||
{reportingPre}<span className="tabular">{periodLabel(data.from, data.to, !from && !to)}</span>{reportingPost}
|
||
</>
|
||
) : undefined
|
||
}
|
||
actions={
|
||
<>
|
||
{switcher}
|
||
{showPicker && (
|
||
<Select value={code} onValueChange={setCode}>
|
||
<SelectTrigger aria-label={t("Country")} className="h-9 w-[150px]">
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{countries.map(c => (
|
||
<SelectItem key={c.code} value={c.code}>
|
||
{c.name}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
)}
|
||
<Select value={preset} onValueChange={v => choosePreset(v as DashPreset)}>
|
||
<SelectTrigger aria-label={t("DashPeriod")} className="h-9 w-[150px]">
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{PRESETS.map(p => (
|
||
<SelectItem key={p.value} value={p.value}>
|
||
{t(p.label)}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
<DateRangePicker value={pickerValue} onChange={chooseRange} fromLabel={t("DashFromDate")} toLabel={t("DashToDate")} />
|
||
</>
|
||
}
|
||
/>
|
||
<ActionStrip />
|
||
</>
|
||
);
|
||
|
||
if (loading) {
|
||
return (
|
||
<>
|
||
{header}
|
||
<DashboardSkeleton />
|
||
</>
|
||
);
|
||
}
|
||
|
||
if (error || !data) {
|
||
return (
|
||
<>
|
||
{header}
|
||
<ErrorState message={t(error ?? "DashLoadFailed")} onRetry={retry} />
|
||
</>
|
||
);
|
||
}
|
||
|
||
const { members, sales, rewardTotals, topEarners, previous } = data;
|
||
const label = periodLabel(data.from, data.to, !from && !to);
|
||
const versus = t("DashKpiVsPrevious", { period: periodLabel(previous.from, previous.to, false) });
|
||
const credited = (totals: typeof rewardTotals, wallet: string) =>
|
||
totals.filter(r => r.walletType === wallet).reduce((sum, r) => sum + r.total, 0);
|
||
const links = dashboardLinks(data.from, data.to);
|
||
const apples = credited(rewardTotals, "APPLE");
|
||
const acorns = credited(rewardTotals, "ACORN");
|
||
const newMembers = members.newPerDay.reduce((n, g) => n + Object.values(g.byRank).reduce((a, b) => a + b, 0), 0);
|
||
const emptyMonth = !from && !to && !sales.periodRevenue && !sales.periodOrders && !newMembers && !apples && !acorns;
|
||
|
||
// `date` is the full date for the tooltip: a range can cross a year end, so the short tick alone is ambiguous.
|
||
const revenueData = sales.daily.map(r => ({ day: shortDate(r.date), date: formatDmy(r.date), amount: r.revenue }));
|
||
const growthData = members.newPerDay.map(g => ({ day: shortDate(g.date), date: formatDmy(g.date), ...g.byRank }));
|
||
const tooltipDate = (_: unknown, payload: readonly { payload?: { date?: string } }[]) => payload[0]?.payload?.date ?? "";
|
||
const channels = channelRows(sales.byChannel);
|
||
const channelMax = Math.max(...channels.map(c => c.revenue), 1);
|
||
|
||
const rankMax = Math.max(...RANKS.map(r => members.byRank[r] ?? 0), 1);
|
||
const statusEntries = Object.entries(members.byStatus);
|
||
const statusTotal = statusEntries.reduce((a, [, n]) => a + n, 0) || 1;
|
||
const rewardMax = Math.max(...rewardTotals.map(r => r.total), 1);
|
||
const topMax = topEarners[0]?.total ?? 0;
|
||
|
||
return (
|
||
<>
|
||
{header}
|
||
|
||
<div className="space-y-4">
|
||
{emptyMonth && (
|
||
<div role="status" className="flex flex-wrap items-center justify-between gap-2 rounded-lg border bg-muted/40 px-4 py-2 text-sm text-muted-foreground">
|
||
<span>{t("DashNoActivityYet")}</span>
|
||
<Button variant="outline" size="sm" onClick={() => choosePreset("lastMonth")}>{t("DashViewLastMonth")}</Button>
|
||
</div>
|
||
)}
|
||
<HeroBand
|
||
ariaLabel={t("DashKpiSection")}
|
||
lead={{ label: t("DashKpiRevenue"), value: formatRM(sales.periodRevenue, currency), delta: change(sales.periodRevenue, previous.sales.periodRevenue), icon: CircleDollarSign, href: links.revenue }}
|
||
// The ticket's order after revenue: Apples, Acorns, New members, Orders.
|
||
stats={[
|
||
{ label: t("DashKpiApples"), value: formatPoints(apples), delta: change(apples, credited(previous.rewardTotals, "APPLE")), icon: Apple, href: links.apples },
|
||
{ label: t("DashKpiAcorns"), value: formatPoints(acorns), delta: change(acorns, credited(previous.rewardTotals, "ACORN")), icon: Gift, href: links.acorns },
|
||
{ label: t("DashNewMembers"), value: String(members.newThisMonth), delta: change(members.newThisMonth, previous.members.newThisMonth), icon: UserPlus, href: links.newMembers },
|
||
{ label: t("DashKpiOrders"), value: String(sales.periodOrders), delta: change(sales.periodOrders, previous.sales.periodOrders), icon: ShoppingBag, href: links.orders },
|
||
]}
|
||
comparisonLabel={versus}
|
||
noComparisonLabel={t("DashKpiNoPrevious")}
|
||
trend={sales.daily.map(r => r.revenue)}
|
||
/>
|
||
|
||
<div className="grid gap-4 lg:grid-cols-3 [&>*]:min-w-0">
|
||
<ChartCard
|
||
className="lg:col-span-2"
|
||
title={t("DashRevenueTrend")}
|
||
description={t("DashSettledPeriod", { period: label })}
|
||
dataTable={{
|
||
caption: t("DashRevenueTrendDailyCaption"),
|
||
columns: [t("Date"), t("DashRevenue")],
|
||
rows: sales.daily.map(r => ({ label: formatDmy(r.date), value: formatRM(r.revenue, currency) })),
|
||
}}
|
||
>
|
||
<ChartContainer config={revenueConfig(t)} className="h-[300px] w-full">
|
||
<AreaChart data={revenueData} margin={{ left: 4, right: 12, top: 8 }}>
|
||
<defs>
|
||
<linearGradient id="revenueFill" x1="0" y1="0" x2="0" y2="1">
|
||
<stop offset="0%" stopColor="var(--color-amount)" stopOpacity={0.35} />
|
||
<stop offset="100%" stopColor="var(--color-amount)" stopOpacity={0.02} />
|
||
</linearGradient>
|
||
</defs>
|
||
<CartesianGrid vertical={false} stroke="var(--border)" />
|
||
<XAxis dataKey="day" tickLine={false} axisLine={false} tickMargin={8} interval="equidistantPreserveStart" minTickGap={0} angle={-90} textAnchor="end" height={48} />
|
||
<YAxis domain={[0, "auto"]} tickLine={false} axisLine={false} width={64} tickFormatter={(v: number) => compactRM(v, currency)} />
|
||
<ChartTooltip content={<ChartTooltipContent labelFormatter={tooltipDate} />} />
|
||
<Area dataKey="amount" type="linear" stroke="var(--color-amount)" strokeWidth={2.5} fill="url(#revenueFill)" dot={false} activeDot={{ r: 4 }} />
|
||
</AreaChart>
|
||
</ChartContainer>
|
||
</ChartCard>
|
||
|
||
<Card className="gap-3">
|
||
<CardHeader className="gap-1">
|
||
<CardTitle className="text-base">{t("DashRevenueByChannel")}</CardTitle>
|
||
<CardDescription>{t("DashSettledPeriod", { period: label })}</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-3">
|
||
{channels.map(c => (
|
||
<ProportionRow
|
||
key={c.type}
|
||
label={t(c.labelCode)}
|
||
value={formatRM(c.revenue, currency)}
|
||
share={(c.revenue / channelMax) * 100}
|
||
barColor={CATEGORY_TONE_COLOR[c.tone]}
|
||
href={c.type === "OTHER" ? undefined : links.channel(c.type)}
|
||
/>
|
||
))}
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
|
||
<div className="grid gap-4 lg:grid-cols-3 [&>*]:min-w-0">
|
||
<ChartCard
|
||
className="lg:col-span-2"
|
||
title={t("DashMemberGrowth")}
|
||
description={t("DashNewMembersPerDay", { period: label })}
|
||
dataTable={{
|
||
caption: t("DashNewMembersByDay"),
|
||
columns: [t("Date"), ...RANKS.map(r => rankLabel(r, t))],
|
||
rows: members.newPerDay.map(g => ({ label: formatDmy(g.date), value: RANKS.map(r => String(g.byRank[r] ?? 0)) })),
|
||
}}
|
||
>
|
||
<ChartContainer config={growthConfig(t)} className="h-[260px] w-full">
|
||
<LineChart data={growthData} margin={{ left: 4, right: 12, top: 8 }}>
|
||
<CartesianGrid vertical={false} stroke="var(--border)" />
|
||
<XAxis dataKey="day" tickLine={false} axisLine={false} tickMargin={8} interval="equidistantPreserveStart" minTickGap={0} angle={-90} textAnchor="end" height={48} />
|
||
<YAxis domain={[0, "auto"]} allowDecimals={false} tickLine={false} axisLine={false} width={40} />
|
||
<ChartTooltip content={<ChartTooltipContent labelFormatter={tooltipDate} />} />
|
||
{/* itemSorter null: legend in rank order, not recharts' default alphabetical order */}
|
||
<ChartLegend itemSorter={null} content={<ChartLegendContent />} />
|
||
{RANKS.map(rank => (
|
||
<Line key={rank} dataKey={rank} type="linear" stroke={`var(--color-${rank})`} strokeWidth={2.5} dot={false} activeDot={{ r: 4 }} />
|
||
))}
|
||
</LineChart>
|
||
</ChartContainer>
|
||
</ChartCard>
|
||
|
||
<Card className="gap-3">
|
||
<CardHeader className="gap-1">
|
||
<CardTitle className="text-base">{t("DashTopEarnersApple")}</CardTitle>
|
||
<CardDescription>{t("DashRewardsCredited", { period: label })}</CardDescription>
|
||
</CardHeader>
|
||
<CardContent>
|
||
{topEarners.length === 0 ? (
|
||
<p className="text-sm text-muted-foreground">{t("DashNoEarners")}</p>
|
||
) : (
|
||
<ol className="space-y-3">
|
||
{topEarners.map((earner, index) => (
|
||
<li key={earner.memberCode} className="space-y-1.5">
|
||
<div className="flex items-baseline justify-between gap-2 text-sm">
|
||
<Link
|
||
href={`/members/${earner.memberCode}`}
|
||
className="flex min-w-0 items-center gap-2 font-medium hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
|
||
>
|
||
<span
|
||
aria-hidden="true"
|
||
className={cn(
|
||
"flex size-5 shrink-0 items-center justify-center rounded text-[10px] font-semibold",
|
||
index === 0 ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground",
|
||
)}
|
||
>
|
||
{index + 1}
|
||
</span>
|
||
<span data-testid="top-earner-name" className="truncate">
|
||
{earner.name || earner.memberCode}
|
||
</span>
|
||
</Link>
|
||
<span className="tabular shrink-0 text-muted-foreground">{formatPoints(earner.total)}</span>
|
||
</div>
|
||
<div className="h-1.5 overflow-hidden rounded-full bg-muted" aria-hidden="true">
|
||
<div className="h-full rounded-full bg-chart-2" style={{ width: `${topMax > 0 ? (earner.total / topMax) * 100 : 0}%` }} />
|
||
</div>
|
||
</li>
|
||
))}
|
||
</ol>
|
||
)}
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
|
||
<div className="grid gap-4 lg:grid-cols-3 [&>*]:min-w-0">
|
||
<Card className="gap-3">
|
||
<CardHeader className="gap-1">
|
||
<CardTitle className="text-base">{t("DashRankMix")}</CardTitle>
|
||
<CardDescription>{t("DashRankMixHint")}</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-3">
|
||
{RANKS.map((rank, index) => (
|
||
<ProportionRow
|
||
key={rank}
|
||
label={rankLabel(rank, t)}
|
||
value={String(members.byRank[rank] ?? 0)}
|
||
share={((members.byRank[rank] ?? 0) / rankMax) * 100}
|
||
barClass={SERIES_BG[index % SERIES_BG.length]}
|
||
href={links.rank(rank)}
|
||
/>
|
||
))}
|
||
</CardContent>
|
||
</Card>
|
||
|
||
<Card className="gap-3">
|
||
<CardHeader className="gap-1">
|
||
<CardTitle className="text-base">{t("DashMemberStatus")}</CardTitle>
|
||
<CardDescription>{t("DashMemberStatusHint")}</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-3">
|
||
<div className="flex h-3 w-full overflow-hidden rounded-full bg-muted" aria-hidden="true">
|
||
{statusEntries.map(([status, count]) => (
|
||
<div
|
||
key={status}
|
||
className={cn("h-full first:rounded-l-full last:rounded-r-full", STATUS_FILL[status] ?? "bg-muted-foreground")}
|
||
style={{ width: `${(count / statusTotal) * 100}%` }}
|
||
/>
|
||
))}
|
||
</div>
|
||
<ul className="space-y-2">
|
||
{statusEntries.map(([status, count]) => {
|
||
const name = status in MEMBER_STATUS_LABEL_CODES ? t(memberStatusLabelCode(status as AdminMemberStatus) ?? status) : status;
|
||
const row = (
|
||
<div className="flex items-baseline gap-2 text-sm">
|
||
<span aria-hidden="true" className={cn("size-2 shrink-0 rounded-full", STATUS_FILL[status] ?? "bg-muted-foreground")} />
|
||
<span>{name}</span>
|
||
<span className="tabular ml-auto text-muted-foreground">
|
||
{count}
|
||
<span className="ml-1.5 text-xs">({((count / statusTotal) * 100).toFixed(0)}%)</span>
|
||
</span>
|
||
</div>
|
||
);
|
||
return (
|
||
<li key={status}>
|
||
{status === "Y" || status === "N" ? (
|
||
<DrillLink href={links.status(status)} className="-mx-2 px-2 py-1">
|
||
{row}
|
||
</DrillLink>
|
||
) : (
|
||
row
|
||
)}
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
</CardContent>
|
||
</Card>
|
||
|
||
<Card className="gap-3">
|
||
<CardHeader className="gap-1">
|
||
<CardTitle className="text-base">{t("DashRewardsByType")}</CardTitle>
|
||
<CardDescription>{t("DashCreditedIn", { period: label })}</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-3">
|
||
{rewardTotals.length === 0 ? (
|
||
<p className="text-sm text-muted-foreground">{t("DashNoRewards")}</p>
|
||
) : (
|
||
rewardTotals.map((entry, index) => (
|
||
<ProportionRow
|
||
key={entry.rewardCode}
|
||
label={rewardLabel(entry.rewardCode, t)}
|
||
value={formatPoints(entry.total)}
|
||
share={(entry.total / rewardMax) * 100}
|
||
barClass={SERIES_BG[index % SERIES_BG.length]}
|
||
href={links.reward(entry.rewardCode)}
|
||
/>
|
||
))
|
||
)}
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|