player card added

This commit is contained in:
2026-05-12 13:35:19 +05:30
parent 40ee0df6d9
commit 13d4414c37
13 changed files with 924 additions and 37 deletions
+12
View File
@@ -0,0 +1,12 @@
"use server";
import { fetchPlayerCardData } from "@/lib/player-card-server";
import { createAdminSupabase } from "@/lib/supabase/admin";
export async function loadPlayerCardAction(userId: number) {
const supabase = createAdminSupabase();
if (!supabase) {
return { ok: false as const, error: "Supabase is not configured." };
}
return fetchPlayerCardData(supabase, userId);
}
+4 -1
View File
@@ -1,5 +1,6 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import { PlayerCardRoot } from "@/components/player-card-root";
import "./globals.css"; import "./globals.css";
const geistSans = Geist({ const geistSans = Geist({
@@ -27,7 +28,9 @@ export default function RootLayout({
lang="en" lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`} className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
> >
<body className="min-h-full flex flex-col">{children}</body> <body className="flex min-h-full flex-col">
<PlayerCardRoot>{children}</PlayerCardRoot>
</body>
</html> </html>
); );
} }
+26 -3
View File
@@ -18,7 +18,13 @@ import {
type MatchmakerLogSource, type MatchmakerLogSource,
} from "@/lib/matchmaker-log-source"; } from "@/lib/matchmaker-log-source";
import { readMatchmakerLogFile } from "@/lib/matchmaker-logs-server"; import { readMatchmakerLogFile } from "@/lib/matchmaker-logs-server";
import type { DbMatch, DbTransaction, DbUser } from "@/types/database"; import { fetchEntryHoldPerPlayerCoinsByMatchIds } from "@/lib/match-entry-hold-from-ledger";
import type {
AdminMatchRow,
DbMatch,
DbTransaction,
DbUser,
} from "@/types/database";
import { import {
normalizeLedgerPage, normalizeLedgerPage,
normalizeLedgerPageSize, normalizeLedgerPageSize,
@@ -79,7 +85,7 @@ export default async function Home({
const supabase = createAdminSupabase(); const supabase = createAdminSupabase();
let users: DbUser[] = []; let users: DbUser[] = [];
let matches: DbMatch[] = []; let matches: AdminMatchRow[] = [];
let configError: string | null = null; let configError: string | null = null;
let usersError: string | null = null; let usersError: string | null = null;
let matchesError: string | null = null; let matchesError: string | null = null;
@@ -137,7 +143,24 @@ export default async function Home({
if (matchesRes.error) { if (matchesRes.error) {
matchesError = matchesRes.error.message; matchesError = matchesRes.error.message;
} else { } else {
matches = (matchesRes.data ?? []) as DbMatch[]; const rawMatches = (matchesRes.data ?? []) as DbMatch[];
const holdByMatch = await fetchEntryHoldPerPlayerCoinsByMatchIds(
supabase,
rawMatches
.map((m) => Number(m.id))
.filter((id) => Number.isFinite(id)),
);
matches = rawMatches.map((m) => {
const idNum = Number(m.id);
const hold = Number.isFinite(idNum)
? holdByMatch.get(idNum)
: undefined;
return {
...m,
entryHoldPerPlayerCoins:
hold !== undefined ? hold.toString() : null,
};
});
} }
statsBundle = await loadDashboardStatsBundle(supabase); statsBundle = await loadDashboardStatsBundle(supabase);
+36 -13
View File
@@ -2,6 +2,7 @@
import Link from "next/link"; import Link from "next/link";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { ClickableUserId } from "@/components/clickable-user-id";
import { AdminLedger } from "@/components/admin-ledger"; import { AdminLedger } from "@/components/admin-ledger";
import { MatchHistoryBattleCard } from "@/components/match-history-battle-card"; import { MatchHistoryBattleCard } from "@/components/match-history-battle-card";
import type { DashboardStatsBundle } from "@/lib/dashboard-stats"; import type { DashboardStatsBundle } from "@/lib/dashboard-stats";
@@ -11,8 +12,16 @@ import {
type AdminDashboardTab, type AdminDashboardTab,
} from "@/lib/dashboard-search-url"; } from "@/lib/dashboard-search-url";
import type { MatchmakerLogSource } from "@/lib/matchmaker-log-source"; import type { MatchmakerLogSource } from "@/lib/matchmaker-log-source";
import type { DbMatch, DbTransaction, DbUser } from "@/types/database"; import type {
import type { SerializedLedgerGlobalSummary } from "@/lib/ledger-integrity"; AdminMatchRow,
DbMatch,
DbTransaction,
DbUser,
} from "@/types/database";
import {
txAmountToBigInt,
type SerializedLedgerGlobalSummary,
} from "@/lib/ledger-integrity";
import type { LedgerSortKey, LedgerSortOrder } from "@/lib/ledger-table-view"; import type { LedgerSortKey, LedgerSortOrder } from "@/lib/ledger-table-view";
/** Bigint columns often arrive as strings from PostgREST / JSON. */ /** Bigint columns often arrive as strings from PostgREST / JSON. */
@@ -56,9 +65,24 @@ function formatTs(value: string | null): string {
} }
} }
function matchEntryFeeCoinString(v: DbMatch["entry_fee"]): string | null {
if (v == null) return null;
return txAmountToBigInt(v).toString();
}
function formatPrizeCcChip(v: DbMatch["prize_cc"]): string {
if (v == null) return "—";
const b = txAmountToBigInt(v);
try {
return b.toLocaleString("en-US");
} catch {
return String(v);
}
}
type Props = { type Props = {
users: DbUser[]; users: DbUser[];
matches: DbMatch[]; matches: AdminMatchRow[];
usersError: string | null; usersError: string | null;
matchesError: string | null; matchesError: string | null;
transactionsError: string | null; transactionsError: string | null;
@@ -378,12 +402,8 @@ export function AdminDashboard({
{i + 1} {i + 1}
</td> </td>
<td className="px-4 py-2"> <td className="px-4 py-2">
<Link <span className="font-mono text-xs">
href={`/?tab=players&highlight=${row.userId}`} <ClickableUserId id={row.userId} />
className="font-mono text-xs text-sky-700 underline decoration-sky-400/60 underline-offset-2 hover:text-sky-900 dark:text-sky-300 dark:hover:text-sky-100"
scroll={false}
>
{row.userId}
{row.username != null && row.username !== "" ? ( {row.username != null && row.username !== "" ? (
<span className="text-zinc-700 dark:text-zinc-300"> <span className="text-zinc-700 dark:text-zinc-300">
{" "} {" "}
@@ -392,7 +412,7 @@ export function AdminDashboard({
) : ( ) : (
<span className="text-zinc-500"> ()</span> <span className="text-zinc-500"> ()</span>
)} )}
</Link> </span>
</td> </td>
<td className="px-4 py-2 text-right font-mono tabular-nums"> <td className="px-4 py-2 text-right font-mono tabular-nums">
{row.totalPrizeCc.toLocaleString("en-US")} {row.totalPrizeCc.toLocaleString("en-US")}
@@ -448,7 +468,9 @@ export function AdminDashboard({
: "text-zinc-800 dark:text-zinc-200" : "text-zinc-800 dark:text-zinc-200"
} }
> >
<td className="px-4 py-2 font-mono text-xs">{u.id}</td> <td className="px-4 py-2 font-mono text-xs">
<ClickableUserId id={u.id} />
</td>
<td className="px-4 py-2">{u.username ?? "—"}</td> <td className="px-4 py-2">{u.username ?? "—"}</td>
<td className="px-4 py-2">{u.cc ?? "—"}</td> <td className="px-4 py-2">{u.cc ?? "—"}</td>
<td className="px-4 py-2">{u.rc ?? "—"}</td> <td className="px-4 py-2">{u.rc ?? "—"}</td>
@@ -622,8 +644,9 @@ export function AdminDashboard({
matchId={m.id} matchId={m.id}
statusLabel={statusLabel(m.status)} statusLabel={statusLabel(m.status)}
createdAtLabel={formatTs(m.created_at)} createdAtLabel={formatTs(m.created_at)}
entryFee={m.entry_fee} entryFeeCoins={matchEntryFeeCoinString(m.entry_fee)}
prizeCc={m.prize_cc} entryHoldPerPlayerCoins={m.entryHoldPerPlayerCoins}
prizeCcLabel={formatPrizeCcChip(m.prize_cc)}
winnerId={m.winner_id} winnerId={m.winner_id}
left={{ left={{
id: redId, id: redId,
+2 -11
View File
@@ -2,6 +2,7 @@
import Link from "next/link"; import Link from "next/link";
import { useMemo } from "react"; import { useMemo } from "react";
import { ClickableUserId } from "@/components/clickable-user-id";
import { buildDashboardHref } from "@/lib/dashboard-search-url"; import { buildDashboardHref } from "@/lib/dashboard-search-url";
import { formatRcLabelFromCoinsBigInt } from "@/lib/coins-rc"; import { formatRcLabelFromCoinsBigInt } from "@/lib/coins-rc";
import { auditMatchEconomics } from "@/lib/ledger-match-audit"; import { auditMatchEconomics } from "@/lib/ledger-match-audit";
@@ -199,17 +200,7 @@ export function AdminLedger({
const un = usernameById.get(id); const un = usernameById.get(id);
return ( return (
<span className="font-mono text-xs"> <span className="font-mono text-xs">
<Link <ClickableUserId id={id} />
href={buildDashboardHref({
tab: "players",
highlightId: String(id),
participantRaw,
})}
className="text-sky-700 underline decoration-sky-400/60 underline-offset-2 hover:text-sky-900 dark:text-sky-300 dark:hover:text-sky-100"
scroll={false}
>
{id}
</Link>
{un != null && un !== "" ? ( {un != null && un !== "" ? (
<span className="text-zinc-600 dark:text-zinc-400"> ({un})</span> <span className="text-zinc-600 dark:text-zinc-400"> ({un})</span>
) : null} ) : null}
+26
View File
@@ -0,0 +1,26 @@
"use client";
import type { ReactNode } from "react";
import { usePlayerCard } from "@/components/player-card-context";
const defaultClass =
"cursor-pointer border-0 bg-transparent p-0 text-left font-mono text-sky-700 underline decoration-sky-400/60 underline-offset-2 hover:text-sky-900 dark:text-sky-300 dark:hover:text-sky-100";
type Props = {
id: number;
className?: string;
children?: ReactNode;
};
export function ClickableUserId({ id, className, children }: Props) {
const { openPlayerCard } = usePlayerCard();
return (
<button
type="button"
className={className ?? defaultClass}
onClick={() => openPlayerCard(id)}
>
{children ?? id}
</button>
);
}
+67 -9
View File
@@ -1,4 +1,8 @@
"use client";
import Link from "next/link"; import Link from "next/link";
import { ClickableUserId } from "@/components/clickable-user-id";
import { formatRcLabelFromCoinsBigInt } from "@/lib/coins-rc";
type PlayerSide = { type PlayerSide = {
id: number | null; id: number | null;
@@ -12,14 +16,47 @@ type Props = {
matchId: number; matchId: number;
statusLabel: string; statusLabel: string;
createdAtLabel: string; createdAtLabel: string;
entryFee: number | null; /** `matches.entry_fee` as coin string (bigint); RC shown in footer. */
prizeCc: number | null; entryFeeCoins: string | null;
/** Ledger `entry_hold` / player as coin string; null if unknown. */
entryHoldPerPlayerCoins: string | null;
/** Preformatted `prize_cc` for display (e.g. with grouping). */
prizeCcLabel: string;
left: PlayerSide; left: PlayerSide;
right: PlayerSide; right: PlayerSide;
/** May be string when `bigint` is JSON-serialized. */ /** May be string when `bigint` is JSON-serialized. */
winnerId: number | string | null; winnerId: number | string | null;
}; };
function rcLabelFromCoinString(s: string | null): string {
if (s == null || String(s).trim() === "") return "—";
try {
return formatRcLabelFromCoinsBigInt(BigInt(String(s).trim()));
} catch {
return "—";
}
}
function entryTotalRcLabel(
feeCoins: string | null,
holdCoins: string | null,
): string {
if (
feeCoins == null ||
holdCoins == null ||
String(feeCoins).trim() === "" ||
String(holdCoins).trim() === ""
) {
return "—";
}
try {
const sum = BigInt(String(feeCoins).trim()) + BigInt(String(holdCoins).trim());
return formatRcLabelFromCoinsBigInt(sum);
} catch {
return "—";
}
}
function idsMatch( function idsMatch(
a: number | string | null | undefined, a: number | string | null | undefined,
b: number | string | null | undefined, b: number | string | null | undefined,
@@ -110,7 +147,17 @@ function PlayerPanel({
{playerLabel(side)} {playerLabel(side)}
</p> </p>
<p className={`text-[11px] font-semibold tabular-nums ${s.score}`}> <p className={`text-[11px] font-semibold tabular-nums ${s.score}`}>
ID: {side.id ?? ""} ID:{" "}
{side.id != null ? (
<ClickableUserId
id={side.id}
className="cursor-pointer border-0 bg-transparent p-0 text-[11px] font-semibold text-inherit underline decoration-white/50 underline-offset-2 hover:decoration-white"
>
{side.id}
</ClickableUserId>
) : (
"—"
)}
</p> </p>
</div> </div>
</div> </div>
@@ -131,12 +178,17 @@ export function MatchHistoryBattleCard({
matchId, matchId,
statusLabel, statusLabel,
createdAtLabel, createdAtLabel,
entryFee, entryFeeCoins,
prizeCc, entryHoldPerPlayerCoins,
prizeCcLabel,
left, left,
right, right,
winnerId, winnerId,
}: Props) { }: Props) {
const entryRc = entryTotalRcLabel(entryFeeCoins, entryHoldPerPlayerCoins);
const entryFeeRc = rcLabelFromCoinString(entryFeeCoins);
const entryHoldRc = rcLabelFromCoinString(entryHoldPerPlayerCoins);
const prizeCcDisplay = prizeCcLabel.trim() === "" ? "—" : prizeCcLabel;
const hasWinner = const hasWinner =
winnerId != null && winnerId != null &&
winnerId !== "" && winnerId !== "" &&
@@ -181,15 +233,21 @@ export function MatchHistoryBattleCard({
</div> </div>
<div className="mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-zinc-300/80 pt-1.5 text-xs font-medium text-zinc-700 dark:border-zinc-700 dark:text-zinc-300"> <div className="mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-zinc-300/80 pt-1.5 text-xs font-medium text-zinc-700 dark:border-zinc-700 dark:text-zinc-300">
<div className="flex flex-wrap gap-2"> <div className="flex min-w-0 flex-1 flex-wrap gap-2">
<span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10"> <span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10">
Entry {entryFee ?? "—"} Time {createdAtLabel}
</span> </span>
<span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10"> <span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10">
Prize {prizeCc ?? "—"} CC Entry {entryRc}
</span> </span>
<span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10"> <span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10">
{createdAtLabel} Entry hold {entryHoldRc}
</span>
<span className="rounded bg-zinc-900/10 px-2 py-1 dark:bg-zinc-100/10">
Prize {prizeCcDisplay} CC
</span>
<span className="rounded-md border border-emerald-200/90 bg-emerald-50 px-2 py-1 text-[11px] font-medium text-emerald-600 dark:border-emerald-300/35 dark:bg-emerald-400/15 dark:text-emerald-200">
Entry fee {entryFeeRc}
</span> </span>
</div> </div>
<Link <Link
+54
View File
@@ -0,0 +1,54 @@
"use client";
import {
createContext,
useCallback,
useContext,
useMemo,
useState,
type ReactNode,
} from "react";
type Ctx = {
openPlayerCard: (userId: number) => void;
closePlayerCard: () => void;
cardUserId: number | null;
};
const PlayerCardContext = createContext<Ctx | null>(null);
export function PlayerCardProvider({ children }: { children: ReactNode }) {
const [cardUserId, setCardUserId] = useState<number | null>(null);
const openPlayerCard = useCallback((userId: number) => {
if (!Number.isFinite(userId) || userId < 1) return;
setCardUserId(Math.trunc(userId));
}, []);
const closePlayerCard = useCallback(() => {
setCardUserId(null);
}, []);
const value = useMemo(
() => ({
openPlayerCard,
closePlayerCard,
cardUserId,
}),
[openPlayerCard, closePlayerCard, cardUserId],
);
return (
<PlayerCardContext.Provider value={value}>
{children}
</PlayerCardContext.Provider>
);
}
export function usePlayerCard(): Ctx {
const ctx = useContext(PlayerCardContext);
if (!ctx) {
throw new Error("usePlayerCard must be used within PlayerCardProvider");
}
return ctx;
}
+335
View File
@@ -0,0 +1,335 @@
"use client";
import {
useCallback,
useEffect,
useState,
type MouseEvent,
} from "react";
import Link from "next/link";
import { loadPlayerCardAction } from "@/app/actions/load-player-card";
import type {
PlayerCardData,
PlayerCardMatchHistoryRow,
} from "@/lib/player-card-server";
import {
formatRcLabelFromCoinsBigInt,
rcToCoins,
} from "@/lib/coins-rc";
import { usePlayerCard } from "@/components/player-card-context";
function formatTsUtc(value: string | null): string {
if (!value) return "—";
try {
const d = new Date(value);
if (Number.isNaN(d.getTime())) return value;
return d.toISOString().replace("T", " ").slice(0, 19) + " UTC";
} catch {
return value;
}
}
function rcFromStr(s: string): bigint {
try {
return BigInt(s);
} catch {
return BigInt(0);
}
}
function formatCcBalance(cc: number | null): string {
if (cc == null || !Number.isFinite(cc)) return "—";
return cc.toLocaleString("en-US");
}
/** `users.rc` is stored as display RC; show ledger-style RC plus coin units in brackets. */
function formatRcBalanceWithCoins(rc: number | null): string {
if (rc == null || !Number.isFinite(rc)) return "—";
const coins = rcToCoins(rc);
if (coins != null) {
const rcLabel = formatRcLabelFromCoinsBigInt(BigInt(coins));
return `${rcLabel} (${coins.toLocaleString("en-US")})`;
}
return `${rc.toFixed(1)} RC`;
}
function outcomeClass(outcome: PlayerCardMatchHistoryRow["outcomeLabel"]): string {
if (outcome === "Win") {
return "font-semibold text-emerald-700 dark:text-emerald-400";
}
if (outcome === "Loss") {
return "font-semibold text-rose-700 dark:text-rose-400";
}
return "font-medium text-zinc-500 dark:text-zinc-400";
}
function opponentLine(m: PlayerCardMatchHistoryRow): string {
if (m.opponentId == null) return "Open slot";
const name =
m.opponentUsername != null && m.opponentUsername.trim() !== ""
? m.opponentUsername.trim()
: "—";
return `${name} (${m.opponentId})`;
}
type LoadState =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; message: string }
| { status: "ok"; data: PlayerCardData };
export function PlayerCardModal() {
const { cardUserId, closePlayerCard } = usePlayerCard();
const [load, setLoad] = useState<LoadState>({ status: "idle" });
useEffect(() => {
if (cardUserId == null) {
setLoad({ status: "idle" });
return;
}
let cancelled = false;
setLoad({ status: "loading" });
void (async () => {
const res = await loadPlayerCardAction(cardUserId);
if (cancelled) return;
if (res.ok) {
setLoad({ status: "ok", data: res.data });
} else {
setLoad({ status: "error", message: res.error });
}
})();
return () => {
cancelled = true;
};
}, [cardUserId]);
const onBackdrop = useCallback(
(e: MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) closePlayerCard();
},
[closePlayerCard],
);
useEffect(() => {
if (cardUserId == null) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") closePlayerCard();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [cardUserId, closePlayerCard]);
if (cardUserId == null) return null;
const hold = load.status === "ok" ? rcFromStr(load.data.rcSpentHoldCoins) : BigInt(0);
const fee = load.status === "ok" ? rcFromStr(load.data.rcSpentFeeCoins) : BigInt(0);
const spentEntry = hold + fee;
return (
<div
className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/40 p-4"
role="dialog"
aria-modal="true"
aria-labelledby="player-card-title"
onMouseDown={onBackdrop}
>
<div
className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-y-auto rounded-xl border border-zinc-200 bg-white shadow-xl dark:border-zinc-700 dark:bg-zinc-900"
onMouseDown={(e) => e.stopPropagation()}
>
<div className="shrink-0 border-b border-zinc-200 px-5 py-4 dark:border-zinc-700">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h2
id="player-card-title"
className="truncate text-xl font-semibold tracking-tight text-zinc-900 dark:text-zinc-50"
>
{load.status === "ok"
? load.data.username?.trim()
? load.data.username
: `Player ${load.data.id}`
: `Player ${cardUserId}`}
</h2>
<p className="mt-1 font-mono text-xs text-zinc-500 dark:text-zinc-400">
ID {cardUserId}
</p>
</div>
<button
type="button"
onClick={closePlayerCard}
className="shrink-0 rounded-lg border border-zinc-300 bg-white px-3 py-1.5 text-sm font-medium text-zinc-800 shadow-sm transition hover:bg-zinc-50 dark:border-zinc-600 dark:bg-zinc-950 dark:text-zinc-100 dark:hover:bg-zinc-800"
>
Close
</button>
</div>
{load.status === "ok" ? (
<div className="mt-3 grid gap-1 text-sm text-zinc-600 dark:text-zinc-400">
<div className="flex flex-wrap justify-between gap-x-4 gap-y-0.5">
<span>Account created</span>
<span className="font-mono text-zinc-800 dark:text-zinc-200">
{formatTsUtc(load.data.createdAt)}
</span>
</div>
<div className="flex flex-wrap justify-between gap-x-4 gap-y-0.5">
<span>Last seen</span>
<span className="font-mono text-zinc-800 dark:text-zinc-200">
{formatTsUtc(load.data.lastSeen)}
</span>
</div>
</div>
) : null}
</div>
<div className="min-h-0 shrink-0 overflow-y-auto px-5 py-4">
{load.status === "loading" ? (
<p className="text-sm text-zinc-500 dark:text-zinc-400">Loading</p>
) : load.status === "error" ? (
<p className="text-sm text-red-600 dark:text-red-400" role="alert">
{load.message}
</p>
) : load.status === "ok" ? (
<div className="space-y-3">
<div className="grid grid-cols-3 gap-2 sm:gap-3">
<Stat
label="Matches played"
value={String(load.data.matchesPlayed)}
/>
<Stat
label="Matches won"
value={String(load.data.matchesWon)}
/>
<Stat
label="Win rate"
value={
load.data.winRatePercent == null
? "—"
: `${load.data.winRatePercent.toLocaleString("en-US", {
maximumFractionDigits: 1,
minimumFractionDigits: 0,
})}%`
}
/>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Stat
label="RC balance"
value={formatRcBalanceWithCoins(load.data.rcBalance)}
/>
<Stat
label="CC balance"
value={formatCcBalance(load.data.ccBalance)}
/>
<Stat
label="RC purchased"
value={formatRcLabelFromCoinsBigInt(
rcFromStr(load.data.rcPurchasedCoins),
)}
/>
<Stat
label="RC won (reward)"
value={formatRcLabelFromCoinsBigInt(
rcFromStr(load.data.rcRewardCoins),
)}
/>
<Stat
label="RC spent (entry_hold + entry_fee)"
value={formatRcLabelFromCoinsBigInt(spentEntry)}
/>
<Stat
label="RC spent on fees (entry_fee)"
value={formatRcLabelFromCoinsBigInt(
rcFromStr(load.data.rcSpentFeeCoins),
)}
/>
</div>
</div>
) : null}
</div>
{load.status === "ok" ? (
<section
className="shrink-0 border-t border-zinc-200 bg-zinc-50/30 px-5 pb-4 pt-3 dark:border-zinc-700 dark:bg-zinc-950/20"
aria-label="Match history"
>
<h3 className="text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:text-zinc-400">
Match history
{load.data.matchesPlayed > load.data.matchHistory.length ? (
<span className="ml-1.5 font-normal normal-case text-zinc-400 dark:text-zinc-500">
(latest {load.data.matchHistory.length} of{" "}
{load.data.matchesPlayed})
</span>
) : null}
</h3>
<div className="mt-2 max-h-60 overflow-y-auto rounded-lg border border-zinc-200 bg-white sm:max-h-72 dark:border-zinc-700 dark:bg-zinc-900/80">
{load.data.matchHistory.length === 0 ? (
<p className="px-3 py-6 text-center text-sm text-zinc-500 dark:text-zinc-400">
No matches yet.
</p>
) : (
<ul className="divide-y divide-zinc-100 dark:divide-zinc-800">
{load.data.matchHistory.map((m) => (
<li key={m.matchId}>
<div className="flex flex-col gap-1 px-3 py-2.5">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<span className="min-w-0 text-xs text-zinc-800 dark:text-zinc-200">
<Link
href={`/match-logs/${m.matchId}`}
target="_blank"
rel="noopener noreferrer"
className="font-mono font-semibold text-sky-700 underline decoration-sky-400/50 underline-offset-2 hover:text-sky-900 dark:text-sky-300 dark:hover:text-sky-100"
>
M{m.matchId}
</Link>
<span className="text-zinc-500 dark:text-zinc-400">
{" "}
· {formatTsUtc(m.createdAt)}
</span>
</span>
<span
className={`shrink-0 text-xs tabular-nums ${outcomeClass(m.outcomeLabel)}`}
>
{m.outcomeLabel}
</span>
</div>
<p className="text-[11px] leading-snug text-zinc-600 dark:text-zinc-400">
<span className="font-medium text-zinc-700 dark:text-zinc-300">
{m.sideLabel}
</span>
{" · "}
vs {opponentLine(m)}
{" · "}
Entry{" "}
{formatRcLabelFromCoinsBigInt(
rcFromStr(m.entryTotalCoins),
)}
{" · "}
Entry fee{" "}
{formatRcLabelFromCoinsBigInt(
rcFromStr(m.entryFeeCoins),
)}
</p>
</div>
</li>
))}
</ul>
)}
</div>
</section>
) : null}
</div>
</div>
);
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="min-w-0 rounded-lg border border-zinc-100 bg-zinc-50/80 px-3 py-2 dark:border-zinc-800 dark:bg-zinc-950/50">
<p className="text-xs font-medium uppercase tracking-wide text-zinc-500 dark:text-zinc-400">
{label}
</p>
<p className="mt-0.5 font-mono text-sm font-semibold tabular-nums text-zinc-900 dark:text-zinc-50">
{value}
</p>
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
"use client";
import { PlayerCardProvider } from "@/components/player-card-context";
import { PlayerCardModal } from "@/components/player-card-modal";
export function PlayerCardRoot({ children }: { children: React.ReactNode }) {
return (
<PlayerCardProvider>
{children}
<PlayerCardModal />
</PlayerCardProvider>
);
}
+56
View File
@@ -0,0 +1,56 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import type { DbTransaction } from "@/types/database";
import { txAmountToBigInt } from "@/lib/ledger-integrity";
function normRemark(r: string | null | undefined): string {
return (r ?? "").toLowerCase().trim();
}
/**
* For each match_id, average `entry_hold` debit amount (same per player when
* both rows exist; sum/count handles odd counts).
*/
export async function fetchEntryHoldPerPlayerCoinsByMatchIds(
supabase: SupabaseClient,
matchIds: number[],
): Promise<Map<number, bigint>> {
const out = new Map<number, bigint>();
if (matchIds.length === 0) return out;
const { data, error } = await supabase
.from("transactions")
.select("match_id, amount, remarks")
.in("match_id", matchIds);
if (error) {
return out;
}
const sums = new Map<number, bigint>();
const counts = new Map<number, number>();
for (const row of (data ?? []) as Pick<
DbTransaction,
"match_id" | "amount" | "remarks"
>[]) {
if (normRemark(row.remarks) !== "entry_hold") {
continue;
}
const midRaw = row.match_id;
if (midRaw == null) continue;
const mid =
typeof midRaw === "number" ? midRaw : Math.trunc(Number(midRaw));
if (!Number.isFinite(mid)) continue;
const a = txAmountToBigInt(row.amount);
if (a === BigInt(0)) continue;
sums.set(mid, (sums.get(mid) ?? BigInt(0)) + a);
counts.set(mid, (counts.get(mid) ?? 0) + 1);
}
for (const [mid, sum] of sums) {
const c = counts.get(mid) ?? 0;
if (c > 0) out.set(mid, sum / BigInt(c));
}
return out;
}
+287
View File
@@ -0,0 +1,287 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import type { DbMatch, DbTransaction } from "@/types/database";
import { txAmountToBigInt } from "@/lib/ledger-integrity";
const TX_PAGE = 5000;
/** Recent matches listed on the player card (newest first). */
const MATCH_HISTORY_LIMIT = 200;
export type PlayerCardMatchHistoryRow = {
matchId: number;
createdAt: string;
sideLabel: "Red" | "Blue";
opponentId: number | null;
opponentUsername: string | null;
outcomeLabel: "Win" | "Loss" | "Pending";
/** Coins debited: entry_hold + entry_fee for this user on this match. */
entryTotalCoins: string;
/** Coins debited: entry_fee only for this user on this match. */
entryFeeCoins: string;
};
export type PlayerCardData = {
id: number;
username: string | null;
createdAt: string | null;
lastSeen: string | null;
rcBalance: number | null;
ccBalance: number | null;
matchesPlayed: number;
matchesWon: number;
winRatePercent: number | null;
rcPurchasedCoins: string;
rcRewardCoins: string;
rcSpentHoldCoins: string;
rcSpentFeeCoins: string;
matchHistory: PlayerCardMatchHistoryRow[];
};
function cellUserId(v: number | string | null | undefined): number | null {
if (v == null) return null;
const n = typeof v === "number" ? v : Number(v);
return Number.isFinite(n) ? Math.trunc(n) : null;
}
function sameUser(
cell: number | string | null | undefined,
userId: number,
): boolean {
return cellUserId(cell) === userId;
}
function normRemark(r: string | null | undefined): string {
return (r ?? "").toLowerCase().trim();
}
function winnerRecorded(winnerId: DbMatch["winner_id"]): boolean {
const w = cellUserId(winnerId);
return w != null && w > 0;
}
function outcomeForParticipant(
userId: number,
winnerId: DbMatch["winner_id"],
opponentId: number | null,
): "Win" | "Loss" | "Pending" {
if (!winnerRecorded(winnerId)) return "Pending";
const wid = cellUserId(winnerId);
if (wid === userId) return "Win";
if (opponentId != null && wid === opponentId) return "Loss";
return "Pending";
}
export async function fetchPlayerCardData(
supabase: SupabaseClient,
userId: number,
): Promise<
| { ok: true; data: PlayerCardData }
| { ok: false; error: string }
> {
if (!Number.isInteger(userId) || userId < 1) {
return { ok: false, error: "Invalid player id." };
}
const { data: userRow, error: userErr } = await supabase
.from("users")
.select("id, username, created_at, last_logged_at, rc, cc")
.eq("id", userId)
.maybeSingle();
if (userErr) {
return { ok: false, error: userErr.message };
}
if (!userRow) {
return { ok: false, error: "Player not found." };
}
const [
{ count: playedCount, error: playedErr },
{ count: wonCount, error: wonErr },
matchesListRes,
] = await Promise.all([
supabase
.from("matches")
.select("id", { count: "exact", head: true })
.or(`user_red.eq.${userId},user_blue.eq.${userId}`),
supabase
.from("matches")
.select("id", { count: "exact", head: true })
.eq("winner_id", userId),
supabase
.from("matches")
.select("id, created_at, user_red, user_blue, winner_id")
.or(`user_red.eq.${userId},user_blue.eq.${userId}`)
.order("id", { ascending: false })
.limit(MATCH_HISTORY_LIMIT),
]);
if (playedErr) {
return { ok: false, error: playedErr.message };
}
if (wonErr) {
return { ok: false, error: wonErr.message };
}
if (matchesListRes.error) {
return { ok: false, error: matchesListRes.error.message };
}
const rawMatches = (matchesListRes.data ?? []) as Pick<
DbMatch,
"id" | "created_at" | "user_red" | "user_blue" | "winner_id"
>[];
const matchIds = rawMatches.map((m) => m.id as number);
const entryByMatch = new Map<number, { hold: bigint; fee: bigint }>();
for (const mid of matchIds) {
entryByMatch.set(mid, { hold: BigInt(0), fee: BigInt(0) });
}
if (matchIds.length > 0) {
const { data: entryTxRows, error: entryTxErr } = await supabase
.from("transactions")
.select("match_id, amount, remarks")
.eq("from", userId)
.in("match_id", matchIds);
if (entryTxErr) {
return { ok: false, error: entryTxErr.message };
}
for (const row of entryTxRows ?? []) {
const midRaw = row.match_id;
if (midRaw == null) continue;
const midNum =
typeof midRaw === "number" ? midRaw : Number(midRaw);
if (!Number.isFinite(midNum)) continue;
const mid = Math.trunc(midNum);
const a = txAmountToBigInt(row.amount);
if (a === BigInt(0)) continue;
const rmk = normRemark(row.remarks);
const cur = entryByMatch.get(mid) ?? {
hold: BigInt(0),
fee: BigInt(0),
};
if (rmk === "entry_hold") {
cur.hold += a;
} else if (rmk === "entry_fee") {
cur.fee += a;
}
entryByMatch.set(mid, cur);
}
}
const opponentIds = new Set<number>();
for (const m of rawMatches) {
const red = cellUserId(m.user_red);
const blue = cellUserId(m.user_blue);
if (red === userId && blue != null) opponentIds.add(blue);
else if (blue === userId && red != null) opponentIds.add(red);
}
const nameById = new Map<number, string | null>();
if (opponentIds.size > 0) {
const { data: nameRows, error: nameErr } = await supabase
.from("users")
.select("id, username")
.in("id", [...opponentIds]);
if (nameErr) {
return { ok: false, error: nameErr.message };
}
for (const row of nameRows ?? []) {
nameById.set(row.id as number, (row.username as string | null) ?? null);
}
}
const matchHistory: PlayerCardMatchHistoryRow[] = rawMatches.map((m) => {
const red = cellUserId(m.user_red);
const blue = cellUserId(m.user_blue);
const onRed = red === userId;
const opponentId = onRed ? blue : red;
const opponentUsername =
opponentId != null ? nameById.get(opponentId) ?? null : null;
const mid = m.id as number;
const e = entryByMatch.get(mid) ?? { hold: BigInt(0), fee: BigInt(0) };
const entryTotal = e.hold + e.fee;
return {
matchId: mid,
createdAt: m.created_at as string,
sideLabel: onRed ? "Red" : "Blue",
opponentId,
opponentUsername,
outcomeLabel: outcomeForParticipant(userId, m.winner_id, opponentId),
entryTotalCoins: entryTotal.toString(),
entryFeeCoins: e.fee.toString(),
};
});
const matchesPlayed = playedCount ?? 0;
const matchesWon = wonCount ?? 0;
const winRatePercent =
matchesPlayed > 0
? Math.round((matchesWon / matchesPlayed) * 1000) / 10
: null;
let purchased = BigInt(0);
let reward = BigInt(0);
let holdSpend = BigInt(0);
let feeSpend = BigInt(0);
let offset = 0;
for (;;) {
const { data: batch, error: txErr } = await supabase
.from("transactions")
.select("amount, remarks, from, to")
.or(`from.eq.${userId},to.eq.${userId}`)
.order("id", { ascending: true })
.range(offset, offset + TX_PAGE - 1);
if (txErr) {
return { ok: false, error: txErr.message };
}
const rows = (batch ?? []) as Pick<
DbTransaction,
"amount" | "remarks" | "from" | "to"
>[];
if (rows.length === 0) break;
for (const row of rows) {
const a = txAmountToBigInt(row.amount);
if (a === BigInt(0)) continue;
const rmk = normRemark(row.remarks);
if (sameUser(row.to, userId) && rmk === "purchase") {
purchased += a;
}
if (sameUser(row.to, userId) && rmk === "reward") {
reward += a;
}
if (sameUser(row.from, userId) && rmk === "entry_hold") {
holdSpend += a;
}
if (sameUser(row.from, userId) && rmk === "entry_fee") {
feeSpend += a;
}
}
offset += rows.length;
if (rows.length < TX_PAGE) break;
}
return {
ok: true,
data: {
id: userRow.id as number,
username: (userRow.username as string | null) ?? null,
createdAt: (userRow.created_at as string) ?? null,
lastSeen: (userRow.last_logged_at as string | null) ?? null,
rcBalance: (userRow.rc as number | null) ?? null,
ccBalance: (userRow.cc as number | null) ?? null,
matchesPlayed,
matchesWon,
winRatePercent,
rcPurchasedCoins: purchased.toString(),
rcRewardCoins: reward.toString(),
rcSpentHoldCoins: holdSpend.toString(),
rcSpentFeeCoins: feeSpend.toString(),
matchHistory,
},
};
}
+6
View File
@@ -25,6 +25,12 @@ export type DbMatch = {
winner_id: number | string | null; winner_id: number | string | null;
}; };
/** `matches` row plus ledger-derived fields for the admin matches tab. */
export type AdminMatchRow = DbMatch & {
/** Per-player `entry_hold` debit in coins (stringified bigint); null if unknown. */
entryHoldPerPlayerCoins: string | null;
};
/** Mirrors `public.settings` (key/value config rows). */ /** Mirrors `public.settings` (key/value config rows). */
export type DbSetting = { export type DbSetting = {
key: string; key: string;