Files
co-lite/solvway-admin-portal/app/components/dashboard/EventDashboard.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

507 lines
22 KiB
TypeScript

"use client";
import { useEffect, useState, type ReactNode } from "react";
import Link from "next/link";
import { AlertTriangle, CalendarDays, CheckCircle2, Clock, PackageX, RefreshCw, Store, User } from "lucide-react";
import { DrillLink } from "@/app/components/dashboard/drill-link";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/app/components/ui/card";
import { PageHeader } from "@/app/components/ui/page-header";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { tenderLines } from "@/app/lib/eventTenders";
import { dayMonth, eventState } from "@/app/lib/eventState";
import { malaysiaToday } from "@/app/lib/malaysiaPeriod";
import { getEventSummary } from "@/app/lib/services/adminEventSummary";
import { ChartCaption, HourlyBars, SplitBar, TenderMix, tradingHours, type HourPoint } from "@/app/components/events/EventCharts";
import { RunProgress } from "@/app/components/events/RunProgress";
import { cn } from "@/app/lib/utils";
import { formatRM } from "@/app/lib/format";
import { listEventProducts, listSellableEvents } from "@/app/lib/services/adminPos";
import { getEventDashboard } from "@/app/lib/services/adminDashboard";
import type { EventDashboardData, EventSalesTotals } from "@/app/lib/services/adminDashboard";
import type { PosEventProduct, PosSellableEvent } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Shared with the Event POS page (app/pos/page.tsx): the event chosen here is the one the POS opens on.
const LAST_EVENT_STORAGE_KEY = "pos.lastEventId";
// Holds the server message or a fallback message CODE; rendered through t(), which passes server text through.
const errorText = (err: unknown, fallback: string) => (err instanceof Error ? err.message : fallback);
/** The current hour of the day in Malaysia (UTC+8, no daylight saving). */
const malaysiaHour = () => new Date(Date.now() + 8 * 3_600_000).getUTCHours();
/** "Updated 10:24" in Malaysia time, whatever the browser's zone. */
const clock = (d: Date) =>
new Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit", hour12: false, timeZone: "Asia/Kuala_Lumpur" }).format(d);
/**
* A period's figures (feedback 2026-10-26): revenue, orders and average order, then the payment mix
* as one stacked bar with a legend of every method's amount. `lead` makes it the page's main figure.
*/
function TotalsCard({
title,
totals,
labels,
t,
lead = false,
href,
className,
children,
}: {
title: string;
totals: EventSalesTotals;
labels: Record<string, string>;
t: ReturnType<typeof useT>;
lead?: boolean;
/** Where the headline figure drills to; omitted leaves it plain. */
href?: string;
className?: string;
children?: ReactNode;
}) {
const figure = (
<p className={cn("tabular font-heading leading-tight font-semibold whitespace-nowrap", lead ? "text-4xl" : "text-3xl")}>
{formatRM(totals.revenue)}
</p>
);
return (
<Card role="region" aria-label={title} className={cn("gap-4", lead && "border-contrast/30", className)}>
<CardHeader className="gap-1">
<CardTitle className="text-sm font-semibold tracking-wide text-muted-foreground uppercase">{title}</CardTitle>
{href ? (
<DrillLink href={href} className="w-fit">
{figure}
</DrillLink>
) : (
figure
)}
<CardDescription className="flex flex-wrap gap-x-3">
<span>{totals.orders === 1 ? t("DashOrderCountOne") : t("DashOrderCountMany", { count: totals.orders })}</span>
{totals.orders > 0 && <span className="tabular">{t("DashEventAvgOrder", { amount: formatRM(totals.revenue / totals.orders) })}</span>}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{children}
{totals.byTender.length > 0 && <TenderMix caption={t("DashEventPaymentMix")} lines={tenderLines(totals.byTender, labels, t)} />}
</CardContent>
</Card>
);
}
function FiguresSkeleton() {
return (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
{Array.from({ length: 4 }).map((_, i) => (
<Card key={i} className="py-4">
<CardContent className="space-y-2 px-4">
<Skeleton className="h-3 w-24" />
<Skeleton className="h-7 w-32" />
</CardContent>
</Card>
))}
</div>
);
}
/** Homepage dashboard for an event operator (BO_DASHBOARD_EVENT): a way into Event POS and the day's figures. */
export function EventDashboard({ switcher }: { switcher?: ReactNode }) {
const { hasModule } = useAdminAuth();
const t = useT();
const canSeeSummary = hasModule("BO_EVENT_SUMMARY");
const [events, setEvents] = useState<PosSellableEvent[] | null>(null);
const [eventsError, setEventsError] = useState<string | null>(null);
const [eventsKey, setEventsKey] = useState(0);
const [eventId, setEventId] = useState("");
const [data, setData] = useState<EventDashboardData | null>(null);
const [error, setError] = useState<string | null>(null);
const [alerts, setAlerts] = useState<PosEventProduct[] | null>(null);
const [alertsError, setAlertsError] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
// Today's sales by hour, from the Event summary endpoint. Only fetched for a user who also holds
// BO_EVENT_SUMMARY: an event manager without it gets only this event's dashboard and products
// (owner, 2026-10-28: "make sure only event data is going out"). null hides the chart.
const [hourly, setHourly] = useState<HourPoint[] | null>(null);
// The sellable events, defaulting like Event POS: the only one, else the one last used on this browser.
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets the error ahead of the eventsKey-triggered fetch below.
setEventsError(null);
listSellableEvents()
.then(all => {
if (cancelled) return;
const evs = all.filter(e => e.sellable); // add-event-summary: the feed also lists upcoming and ended events
setEvents(evs);
if (evs.length === 1) {
setEventId(evs[0].id);
return;
}
let stored: string | null = null;
try {
stored = localStorage.getItem(LAST_EVENT_STORAGE_KEY);
} catch {
stored = null;
}
if (stored && evs.some(e => e.id === stored)) setEventId(stored);
})
.catch((err: unknown) => {
if (!cancelled) setEventsError(errorText(err, "DashEventLoadEventsFailed"));
});
return () => {
cancelled = true;
};
}, [eventsKey]);
// The chosen event's figures and stock alerts; Refresh and Retry bump reloadKey.
useEffect(() => {
if (!eventId) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- clears the previous event's figures ahead of the fetch below.
setData(null);
setError(null);
setAlerts(null);
setAlertsError(false);
setHourly(null);
getEventDashboard(eventId)
.then(result => {
if (cancelled) return;
setData(result);
setUpdatedAt(new Date());
})
.catch((err: unknown) => {
if (!cancelled) setError(errorText(err, "DashEventLoadFailed"));
});
listEventProducts(eventId)
.then(products => {
if (!cancelled) setAlerts(products.filter(p => p.availability === "SOLD_OUT" || p.availability === "PRE_ORDER"));
})
.catch(() => {
if (!cancelled) setAlertsError(true);
});
const ev = events?.find(e => e.id === eventId);
if (canSeeSummary && ev && eventState(ev, t).kind === "live") {
const today = malaysiaToday();
getEventSummary(eventId, { from: today, to: today })
.then(summary => {
if (!cancelled) setHourly(summary.byHour);
})
.catch(() => {
// A refused or failed summary only hides the chart; the dashboard's own figures stand.
if (!cancelled) setHourly(null);
});
}
return () => {
cancelled = true;
};
// events/t are read for the live check only; a new events list always comes with a new eventId.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [eventId, reloadKey, canSeeSummary]);
const chooseEvent = (id: string) => {
setEventId(id);
try {
localStorage.setItem(LAST_EVENT_STORAGE_KEY, id);
} catch {
// Storage may be unavailable (private mode, quota): the pick still works this session.
}
};
const header = (
<PageHeader
title={t("BO_DASHBOARD_EVENT")}
description={
data
? t("DashEventSignedInAs", { operator: data.operator })
: t("DashEventNote")
}
actions={
<>
{switcher}
{events && events.length > 0 && (
<Select value={eventId} onValueChange={chooseEvent}>
<SelectTrigger aria-label={t("DashEvent")} className="h-9 w-full sm:w-72">
<SelectValue placeholder={t("DashEventChoose")} />
</SelectTrigger>
<SelectContent>
{events.map(e => (
<SelectItem key={e.id} value={e.id}>
<span className="truncate" title={e.name}>
{e.name}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
)}
{eventId && (
<div className="flex items-center gap-2">
{updatedAt && data && (
<span className="inline-flex items-center gap-1 text-xs whitespace-nowrap text-muted-foreground">
<Clock aria-hidden="true" className="size-3.5" />
{t("DashEventUpdated", { time: clock(updatedAt) })}
</span>
)}
<Button type="button" variant="outline" size="sm" className="h-9" onClick={() => setReloadKey(k => k + 1)}>
<RefreshCw />
{t("DashEventRefresh")}
</Button>
</div>
)}
</>
}
/>
);
let body: ReactNode;
if (eventsError) {
body = <ErrorState message={t(eventsError)} onRetry={() => setEventsKey(k => k + 1)} />;
} else if (events === null) {
body = <FiguresSkeleton />;
} else if (events.length === 0) {
body = <EmptyState title={t("DashEventNone")} />;
} else if (!eventId) {
body = <EmptyState title={t("DashEventPick")} />;
} else if (error) {
body = <ErrorState message={t(error)} onRetry={() => setReloadKey(k => k + 1)} />;
} else if (!data) {
body = <FiguresSkeleton />;
} else {
const chosen = events.find(e => e.id === eventId);
const lines = (totals: EventSalesTotals) => tenderLines(totals.byTender, data.tenderLabels, t);
// One row per product (first-appearance order); a row without a productCode stays single.
const byProduct = (availability: string) => {
const groups = new Map<string, { key: string; code: string | null; title: string; variants: string[] }>();
for (const p of alerts?.filter(a => a.availability === availability) ?? []) {
const key = p.productCode ? `code:${p.productCode}` : `row:${p.pPricingId}`;
const g = groups.get(key) ?? { key, code: p.productCode ?? null, title: p.productName || p.label, variants: [] };
const v = p.variantName?.trim();
if (v && v !== "DEFAULT") g.variants.push(v);
groups.set(key, g);
}
return [...groups.values()];
};
const soldOut = byProduct("SOLD_OUT");
const preOrder = byProduct("PRE_ORDER");
const pending = data.pendingOrders > 0;
const today = malaysiaToday();
const since = chosen?.salesFrom?.slice(0, 10);
const summaryHref = (from: string) => `/events/summary?event=${eventId}&from=${from}&to=${today}`;
body = (
<div className="grid gap-4 lg:grid-cols-3 [&>*]:min-w-0">
{/* The lead: today's event sales, with today by hour when the summary is available. */}
<TotalsCard title={t("DashEventToday")} totals={data.today} labels={data.tenderLabels} t={t} lead href={summaryHref(today)} className="lg:col-span-2 lg:row-span-2">
{hourly && hourly.length > 0 && (
<div className="space-y-1">
<ChartCaption>{t("DashEventTodayByHour")}</ChartCaption>
<HourlyBars
byHour={hourly}
compact
fromHour={tradingHours(chosen?.salesFrom, chosen?.salesTo)?.open}
throughHour={malaysiaHour()}
/>
</div>
)}
</TotalsCard>
<TotalsCard title={t("DashEventToDate")} totals={data.toDate} labels={data.tenderLabels} t={t} href={since ? summaryHref(since) : undefined}>
{data.toDate.revenue > 0 && (
<SplitBar
caption={t("DashEventTodayVsEarlier")}
left={{ label: t("DashEventTodayLabel"), value: data.today.revenue }}
right={{ label: t("DashEventEarlierDays"), value: Math.max(0, data.toDate.revenue - data.today.revenue) }}
/>
)}
</TotalsCard>
<Card
role="region"
aria-label={t("DashEventPending")}
className={cn("gap-2", pending && "border-warning/40 bg-warning/10")}
>
<CardHeader className="gap-1">
<CardTitle className="text-sm font-semibold tracking-wide text-muted-foreground uppercase">{t("DashEventPending")}</CardTitle>
<CardDescription>{t("DashEventPendingHint")}</CardDescription>
</CardHeader>
<CardContent className="flex items-center gap-3">
<DrillLink href={`/orders/web?type=EVENT&status=P&event=${eventId}`} className="w-fit">
<p className="tabular font-heading text-3xl font-semibold">{data.pendingOrders}</p>
</DrillLink>
{pending ? (
<span className="inline-flex items-center gap-1 rounded-full bg-warning/15 px-2.5 py-0.5 text-xs font-semibold text-warning">
<AlertTriangle aria-hidden="true" className="size-3.5" />
{t("SetupNeedsAttention")}
</span>
) : (
<CheckCircle2 aria-hidden="true" className="size-5 text-positive" />
)}
</CardContent>
</Card>
{/* The operator's own share of today, instead of a card that often repeats Event today. */}
<Card role="region" aria-label={t("DashEventMineToday")} className="gap-4">
<CardHeader className="gap-1">
<CardTitle className="flex items-center gap-2 text-sm font-semibold tracking-wide text-muted-foreground uppercase">
<User aria-hidden="true" className="size-4" />
{t("DashEventMineToday")}
</CardTitle>
<DrillLink href={`/orders/web?type=EVENT&status=Y&event=${eventId}&mine=Y&from=${today}&to=${today}`} className="w-fit">
<p className="tabular font-heading text-3xl leading-tight font-semibold whitespace-nowrap">{formatRM(data.mine.revenue)}</p>
</DrillLink>
<CardDescription>{data.mine.orders === 1 ? t("DashOrderCountOne") : t("DashOrderCountMany", { count: data.mine.orders })}</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{data.today.revenue > 0 && (
<SplitBar
caption={t("DashEventShareOfToday")}
left={{ label: t("DashEventYou"), value: data.mine.revenue }}
right={{ label: t("DashEventRestOfTeam"), value: Math.max(0, data.today.revenue - data.mine.revenue) }}
/>
)}
{data.mine.byTender.length > 0 && <TenderMix caption={t("DashEventPaymentMix")} lines={lines(data.mine)} />}
</CardContent>
</Card>
<Card role="region" aria-label={t("DashEventStockAlerts")} className="gap-3 lg:col-span-2">
<CardHeader className="gap-1">
<CardTitle className="flex items-center gap-2 text-sm font-semibold tracking-wide text-muted-foreground uppercase">
<PackageX aria-hidden="true" className="size-4" />
{t("DashEventStockAlerts")}
</CardTitle>
<CardDescription>{t("DashEventStockAlertsHint")}</CardDescription>
</CardHeader>
<CardContent>
{alertsError ? (
<p className="text-sm text-muted-foreground">{t("DashEventStockLoadFailed")}</p>
) : alerts === null ? (
<Skeleton className="h-5 w-48" />
) : alerts.length === 0 ? (
<p className="flex items-center gap-2 text-sm text-positive">
<CheckCircle2 aria-hidden="true" className="size-4" />
{t("DashEventAllInStock")}
</p>
) : (
<div className="grid gap-4 sm:grid-cols-2">
{[
{ key: "sold", label: t("DashEventSoldOut"), items: soldOut, tone: "negative" as const },
{ key: "pre", label: t("DashEventPreOrder"), items: preOrder, tone: "warning" as const },
].map(group => (
<section key={group.key} aria-label={group.label} className="min-w-0">
<h3 className="mb-1.5 flex items-center gap-2 text-sm font-semibold">
<span className={cn("size-2 rounded-full", group.tone === "negative" ? "bg-negative" : "bg-warning")} aria-hidden="true" />
<span>{group.label}</span>
<span
className={cn(
"tabular rounded-full px-2 text-xs font-semibold",
group.tone === "negative" ? "bg-negative/10 text-negative" : "bg-warning/15 text-warning",
)}
>
{group.items.length}
</span>
</h3>
{group.items.length === 0 ? (
<p className="text-sm text-muted-foreground">—</p>
) : (
<ul className="divide-y text-sm">
{group.items.map(g => {
const body = (
<>
<span className="block truncate">{g.title}</span>
{g.variants.length > 0 && (
<span className="block truncate text-xs text-muted-foreground" title={g.variants.join(", ")}>
{g.variants.join(", ")}
</span>
)}
</>
);
return (
<li key={g.key} className="min-w-0" title={g.title}>
{g.code ? (
<DrillLink href={`/products?si.q=${encodeURIComponent(g.code)}`} className="block min-w-0 py-1.5">
{body}
</DrillLink>
) : (
<div className="py-1.5">{body}</div>
)}
</li>
);
})}
</ul>
)}
</section>
))}
</div>
)}
</CardContent>
</Card>
</div>
);
}
// The event band (feedback 2026-10-26): which event, where it is in its run, and the operator's
// main action. Open Event POS only with BO_POS; the band is then the "Event POS" region.
const selectedEvent = events?.find(e => e.id === eventId);
const hasPos = hasModule("BO_POS");
const state = selectedEvent ? eventState(selectedEvent, t) : null;
const band =
events && events.length > 0 && (hasPos || selectedEvent) ? (
<section
{...(hasPos ? { role: "region", "aria-label": t("BO_POS") } : {})}
className="mb-4 flex flex-col gap-4 rounded-2xl bg-primary p-5 text-primary-foreground shadow-md sm:flex-row sm:items-center sm:justify-between lg:p-6"
>
<div className="min-w-0 flex-1 space-y-2">
{state && (
<span
className={cn(
"inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-semibold",
state.kind === "live"
? "bg-accent text-accent-foreground dark:bg-primary-foreground dark:text-primary"
: "bg-primary-foreground/15",
)}
>
{state.kind === "live" && <span aria-hidden="true" className="size-1.5 animate-pulse rounded-full bg-current motion-reduce:animate-none" />}
{state.line}
</span>
)}
<p className="min-w-0 truncate font-heading text-xl font-semibold lg:text-2xl" title={selectedEvent?.name}>
{selectedEvent?.name ?? t("DashEventChoose")}
</p>
{selectedEvent?.salesFrom && selectedEvent.salesTo && (
<p className="flex items-center gap-1.5 text-sm text-primary-foreground/85">
<CalendarDays aria-hidden="true" className="size-4" />
{t("DashEventDates", { from: dayMonth(selectedEvent.salesFrom, t), to: dayMonth(selectedEvent.salesTo, t) })}
</p>
)}
{state?.day && state.days && (
<RunProgress
day={state.day}
days={state.days}
className="max-w-md pt-1"
filledClassName="bg-accent dark:bg-primary-foreground"
restClassName="bg-primary-foreground/20"
/>
)}
</div>
{hasPos && (
<Button asChild size="lg" className="w-full bg-accent text-accent-foreground hover:bg-accent/90 sm:w-auto dark:bg-primary-foreground dark:text-primary dark:hover:bg-primary-foreground/90">
<Link href="/pos">
<Store />
{t("DashEventOpenPos")}
</Link>
</Button>
)}
</section>
) : null;
return (
<>
{header}
{band}
{body}
</>
);
}