Files
co-lite/solvway-admin-portal/app/components/events/EventCharts.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

216 lines
9.5 KiB
TypeScript

"use client";
import type { ReactNode } from "react";
import { Bar, BarChart, Cell, XAxis, YAxis } from "recharts";
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/app/components/ui/chart";
import { formatRM } from "@/app/lib/format";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { cn } from "@/app/lib/utils";
// Event charts shared by the Event dashboard and Event summary (feedback 2026-10-26: "make the
// dashboard interactive, use charts for visual comparison"). Every chart carries its numbers as text
// too — a legend with amounts, or a screen-reader table — so colour and shape are never the only
// signal (DASHBOARD-STANDARD §5, §6).
/** Segment colours in order: dusty blue, teal, violet, amber, rose, brown. All are chart tokens. */
const SEGMENT_BG = ["bg-contrast", "bg-chart-2", "bg-chart-4", "bg-chart-3", "bg-chart-5", "bg-chart-1"];
/** The small label above a chart, saying what it compares. */
export function ChartCaption({ children }: { children: ReactNode }) {
return <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{children}</p>;
}
const pct = (part: number, whole: number) => (whole > 0 ? Math.round((part / whole) * 100) : 0);
/**
* One stacked bar of how a total split across payment methods, with a legend of each method's
* amount and share. Hovering a segment names it (title), and the legend states every figure.
*/
export function TenderMix({ lines, caption, className }: { lines: { label: string; amount: number }[]; caption?: string; className?: string }) {
const total = lines.reduce((sum, l) => sum + l.amount, 0);
if (lines.length === 0) return null;
return (
<div className={cn("space-y-2.5", className)}>
{caption && <ChartCaption>{caption}</ChartCaption>}
<div aria-hidden="true" className="flex h-2.5 w-full gap-0.5 overflow-hidden rounded-full bg-muted">
{total > 0 && lines.map((l, i) => (
<span
key={l.label}
title={`${l.label}: ${formatRM(l.amount)} (${pct(l.amount, total)}%)`}
className={cn("h-full transition-[filter] first:rounded-l-full last:rounded-r-full hover:brightness-110", SEGMENT_BG[i % SEGMENT_BG.length])}
style={{ width: `${(l.amount / total) * 100}%` }}
/>
))}
</div>
{/* One column: in a narrow card a second column squeezed the method names to nothing. */}
<dl className="space-y-1.5 text-sm">
{lines.map((l, i) => (
<div key={l.label} className="flex min-w-0 items-baseline justify-between gap-2">
<dt className="flex min-w-0 items-center gap-2 text-muted-foreground">
<span aria-hidden="true" className={cn("size-2.5 shrink-0 rounded-sm", SEGMENT_BG[i % SEGMENT_BG.length])} />
<span className="truncate">{l.label}</span>
</dt>
<dd className="tabular shrink-0">
{formatRM(l.amount)} <span className="text-xs text-muted-foreground">{pct(l.amount, total)}%</span>
</dd>
</div>
))}
</dl>
</div>
);
}
/**
* A two-part bar (members vs walk-ins, you vs the rest of the team): left part dusty blue, right
* part teal, each with its label and share printed under it.
*/
export function SplitBar({
left,
right,
caption,
}: {
left: { label: string; value: number; detail?: string };
right: { label: string; value: number; detail?: string };
caption?: string;
}) {
const total = left.value + right.value;
const leftPct = pct(left.value, total);
return (
<div className="space-y-2">
{caption && <ChartCaption>{caption}</ChartCaption>}
<div aria-hidden="true" className="flex h-3 w-full gap-0.5 overflow-hidden rounded-full bg-muted">
{total > 0 && (
<>
<span className="h-full rounded-l-full bg-contrast" style={{ width: `${leftPct}%` }} />
<span className="h-full flex-1 rounded-r-full bg-chart-2" />
</>
)}
</div>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="min-w-0">
<p className="flex items-center gap-1.5 text-muted-foreground">
<span aria-hidden="true" className="size-2.5 shrink-0 rounded-sm bg-contrast" />
<span className="min-w-0">{left.label}</span>
</p>
<p className="tabular mt-0.5 font-semibold">
{leftPct}%{left.detail && <span className="ml-1.5 font-normal text-muted-foreground">{left.detail}</span>}
</p>
</div>
<div className="min-w-0 text-right">
<p className="flex items-center justify-end gap-1.5 text-muted-foreground">
<span aria-hidden="true" className="size-2.5 shrink-0 rounded-sm bg-chart-2" />
<span className="min-w-0">{right.label}</span>
</p>
<p className="tabular mt-0.5 font-semibold">
{total > 0 ? 100 - leftPct : 0}%{right.detail && <span className="ml-1.5 font-normal text-muted-foreground">{right.detail}</span>}
</p>
</div>
</div>
</div>
);
}
export interface HourPoint { hour: number; orders: number; revenue: number }
/**
* An event's daily trading hours from its sales window ("2026-10-27T10:00" … "2026-10-30T22:00" →
* 10 to 21, the last hour that opens before closing). Null when the times don't describe a trading
* day (a midnight start or a close before the open), so the chart falls back to the sales it has.
*/
export function tradingHours(salesFrom?: string | null, salesTo?: string | null): { open: number; close: number } | null {
if (!salesFrom || !salesTo) return null;
const open = Number(salesFrom.slice(11, 13));
const closeH = Number(salesTo.slice(11, 13));
const closeM = Number(salesTo.slice(14, 16)) || 0;
if (Number.isNaN(open) || Number.isNaN(closeH) || open === 0) return null;
const close = closeM > 0 ? closeH : closeH - 1;
return close > open ? { open, close } : null;
}
const hourConfig = { revenue: { label: "revenue", color: "var(--contrast)" } } satisfies ChartConfig;
/**
* Sales by hour as responsive bars: dusty blue, with the busiest hour in amber and named in text.
* Hours between the first and last sale (widened to `fromHour` / `throughHour`) with no sales are
* filled in as zero, so the axis is honest.
* The tooltip shows revenue and orders; a screen-reader table carries the same numbers.
*/
export function HourlyBars({
byHour,
className,
compact = false,
fromHour,
throughHour,
}: {
byHour: HourPoint[];
className?: string;
compact?: boolean;
/** Start the axis at this hour (e.g. the event's opening hour), so a quiet morning shows as zero. */
fromHour?: number;
/** End the axis at this hour (the closing hour, or now for a day still trading). */
throughHour?: number;
}) {
const t = useT();
const hourLabel = (h: number) => t(h < 12 ? "EvtHourAm" : "EvtHourPm", { hour: h % 12 || 12 });
const orders = (n: number) => t(n === 1 ? "EvtOrderOne" : "EvtOrderMany", { count: n });
if (byHour.length === 0) return null;
const byKey = new Map(byHour.map(h => [h.hour, h]));
const first = Math.min(fromHour ?? 23, ...byHour.map(h => h.hour));
const last = Math.max(throughHour ?? 0, ...byHour.map(h => h.hour));
const points = Array.from({ length: last - first + 1 }, (_, i) => {
const hour = first + i;
const h = byKey.get(hour);
return { hour, label: hourLabel(hour), revenue: h?.revenue ?? 0, orders: h?.orders ?? 0 };
});
const peak = points.reduce((a, b) => (b.revenue > a.revenue ? b : a), points[0]);
return (
<div className={className}>
<ChartContainer config={hourConfig} className={cn("aspect-auto w-full", compact ? "h-[150px]" : "h-[220px]")}>
<BarChart data={points} margin={{ left: 0, right: 4, top: 8, bottom: 0 }}>
<XAxis dataKey="label" tickLine={false} axisLine={false} interval="preserveStartEnd" minTickGap={12} />
<YAxis hide domain={[0, "dataMax"]} />
<ChartTooltip
cursor={{ className: "fill-muted" }}
content={({ active, payload }) => {
const p = active && payload?.[0]?.payload as (typeof points)[number] | undefined;
if (!p) return null;
return (
<div className="rounded-lg border bg-background px-3 py-2 text-xs shadow-md">
<p className="font-semibold">{t("EvtHourRange", { from: p.label, to: hourLabel((p.hour + 1) % 24) })}</p>
<p className="tabular">{formatRM(p.revenue)}</p>
<p className="tabular text-muted-foreground">{orders(p.orders)}</p>
</div>
);
}}
/>
<Bar dataKey="revenue" radius={[4, 4, 0, 0]} maxBarSize={36}>
{points.map(p => (
<Cell key={p.hour} fill={p.hour === peak.hour && peak.revenue > 0 ? "var(--chart-3)" : "var(--color-revenue)"} />
))}
</Bar>
</BarChart>
</ChartContainer>
{peak.revenue > 0 && (
<p className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">
<span aria-hidden="true" className="size-2.5 rounded-sm bg-chart-3" />
{t("EvtBusiestHour", { from: peak.label, to: hourLabel((peak.hour + 1) % 24) })}
</p>
)}
<table className="sr-only">
<caption>{t("EvtSalesByHour")}</caption>
<tbody>
{points.map(p => (
<tr key={p.hour}>
<th scope="row">{p.label}</th>
<td>{formatRM(p.revenue)}</td>
<td>{orders(p.orders)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}