diff --git a/apps/api/src/spin2note_api/clickhouse/client.py b/apps/api/src/spin2note_api/clickhouse/client.py index 2c7db03..c63d091 100644 --- a/apps/api/src/spin2note_api/clickhouse/client.py +++ b/apps/api/src/spin2note_api/clickhouse/client.py @@ -32,7 +32,7 @@ ], "tournaments": [ "tournament_id", "user_id", "name", "buy_in", "currency", "players", "prize_pool", - "multiplier", "started_at", "hero_place", "parsed_at", + "multiplier", "started_at", "hero_place", "hero_prize", "parsed_at", ], } diff --git a/apps/api/src/spin2note_api/clickhouse/queries.py b/apps/api/src/spin2note_api/clickhouse/queries.py index 0b2a0d3..e514b55 100644 --- a/apps/api/src/spin2note_api/clickhouse/queries.py +++ b/apps/api/src/spin2note_api/clickhouse/queries.py @@ -23,6 +23,31 @@ def _batched(items: list[Any], size: int = _ID_BATCH) -> list[list[Any]]: return [items[i : i + size] for i in range(0, len(items), size)] +def _iso(value: Any) -> str: + return value.isoformat() if hasattr(value, "isoformat") else str(value) + + +def _cumulative_timeline(rows: list[Any], max_points: int = 1500) -> list[dict[str, Any]]: + """Turn time-ordered ``(delta, at)`` rows into a downsampled cumulative series. + + Each point is ``{"idx", "at", "cumulative"}``. The running total is computed over *all* rows + (so the curve is exact), then thinned to at most ``max_points`` evenly-spaced points with the + last point always kept — bounds the payload when a hero has 100k+ hands. + """ + total = 0.0 + points: list[dict[str, Any]] = [] + for i, r in enumerate(rows, start=1): + total += float(r[0]) + points.append({"idx": i, "at": _iso(r[1]), "cumulative": round(total, 2)}) + if len(points) <= max_points: + return points + step = len(points) / max_points + sampled = [points[int(k * step)] for k in range(max_points)] + if sampled[-1] is not points[-1]: + sampled[-1] = points[-1] + return sampled + + async def user_has_rows(client: AsyncClient, table: str, user_id: UUID) -> bool: """Cheap check used to skip membership queries entirely on a user's first import.""" if table not in {"hands", "tournaments"}: @@ -104,11 +129,39 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[ for r in by_stack.result_rows ] + # Cumulative chips P&L over hero hands (time-ordered). Respects the format filter. + chips_series = await client.query( + f""" + SELECT hp.result AS result, h.played_at AS at + FROM hand_players AS hp + INNER JOIN hands AS h ON hp.hand_id = h.hand_id + WHERE hp.user_id = {{u:UUID}} AND hp.is_hero = 1{f_hands} + ORDER BY h.played_at + """, + parameters=params, + ) + chips_timeline = _cumulative_timeline(chips_series.result_rows) + + # Cumulative real-money P&L per tournament (net = hero_prize - buy_in), time-ordered. + # The tournaments table has no tournament_format column, so this series spans all formats. + dollars_series = await client.query( + """ + SELECT (hero_prize - buy_in) AS net, started_at AS at + FROM tournaments + WHERE user_id = {u:UUID} + ORDER BY started_at + """, + parameters={"u": str(user_id)}, + ) + dollars_timeline = _cumulative_timeline(dollars_series.result_rows) + return { "total_hands": total_hands, "total_tournaments": total_tournaments, "avg_multiplier": avg_multiplier, "by_stack": stacks, + "chips_timeline": chips_timeline, + "dollars_timeline": dollars_timeline, } diff --git a/apps/api/src/spin2note_api/domain/models.py b/apps/api/src/spin2note_api/domain/models.py index a2c2822..d20d717 100644 --- a/apps/api/src/spin2note_api/domain/models.py +++ b/apps/api/src/spin2note_api/domain/models.py @@ -83,4 +83,6 @@ class Tournament(BaseModel): multiplier: int = 0 started_at: datetime | None = None hero_place: int = 0 + # hero's actual cash won (from summary finishes); net $ = hero_prize - buy_in + hero_prize: float = 0.0 parsed_at: datetime = Field(default_factory=_now) diff --git a/apps/api/src/spin2note_api/http/stats.py b/apps/api/src/spin2note_api/http/stats.py index e83f5e4..4095b76 100644 --- a/apps/api/src/spin2note_api/http/stats.py +++ b/apps/api/src/spin2note_api/http/stats.py @@ -23,11 +23,19 @@ class StackBucket(BaseModel): winrate: float +class TimelinePoint(BaseModel): + idx: int # sequential hand# (chips) or tournament# (dollars) + at: str # ISO timestamp + cumulative: float # running total + + class Overview(BaseModel): total_hands: int total_tournaments: int avg_multiplier: float by_stack: list[StackBucket] + chips_timeline: list[TimelinePoint] + dollars_timeline: list[TimelinePoint] def _user_id(claims: dict[str, Any]) -> UUID: diff --git a/apps/api/src/spin2note_api/parser/mapping.py b/apps/api/src/spin2note_api/parser/mapping.py index a99559f..baa1701 100644 --- a/apps/api/src/spin2note_api/parser/mapping.py +++ b/apps/api/src/spin2note_api/parser/mapping.py @@ -133,13 +133,19 @@ def build_chunk_rows( return {"hands": hand_rows, "hand_players": player_rows, "actions": action_rows} +def _hero_prize(summary: dict[str, Any]) -> float: + """Hero's actual cash won, summed from the summary finish lines ("Nrd : Hero, $X").""" + return float(sum(f["prize"] for f in summary.get("finishes", []) if f["name"] == "Hero")) + + def build_tournament_rows( summaries: list[dict[str, Any]], user_id: UUID, parsed_at: datetime ) -> list[tuple[Any, ...]]: return [ ( s["tournament_id"], user_id, s["name"], s["buy_in"], s["currency"], s["players"], - s["prize_pool"], s["multiplier"], _dt(s["started_at"]), s["hero_place"], parsed_at, + s["prize_pool"], s["multiplier"], _dt(s["started_at"]), s["hero_place"], + _hero_prize(s), parsed_at, ) for s in summaries ] @@ -157,4 +163,5 @@ def build_tournament(summary: dict[str, Any], user_id: UUID) -> Tournament: multiplier=summary["multiplier"], started_at=_dt(summary["started_at"]), hero_place=summary["hero_place"], + hero_prize=_hero_prize(summary), ) diff --git a/apps/api/tests/test_api.py b/apps/api/tests/test_api.py index 2a7824d..7318fc4 100644 --- a/apps/api/tests/test_api.py +++ b/apps/api/tests/test_api.py @@ -31,6 +31,8 @@ async def fake_overview(_c: Any, _u: Any, _f: Any) -> dict[str, Any]: "total_tournaments": 2, "avg_multiplier": 2.5, "by_stack": [{"effective_stack_bb": 15, "hands": 10, "result": 120.0, "winrate": 0.6}], + "chips_timeline": [{"idx": 1, "at": "2026-01-07T22:54:43", "cumulative": 120.0}], + "dollars_timeline": [{"idx": 1, "at": "2026-01-07T22:54:43", "cumulative": -0.25}], } async def fake_recent(_c: Any, _u: Any, _l: int) -> list[dict[str, Any]]: diff --git a/apps/api/tests/test_parser.py b/apps/api/tests/test_parser.py index ddbec8a..5d675fc 100644 --- a/apps/api/tests/test_parser.py +++ b/apps/api/tests/test_parser.py @@ -101,3 +101,34 @@ def test_summary_mapping() -> None: assert t.multiplier == 3 assert t.players == 3 assert t.hero_place == 3 + assert t.hero_prize == 0.0 # finished 3rd, "$0" + + +def test_hero_prize_from_winning_summary() -> None: + # 6-max, Hero 1st for $4 on a $1 buy-in — prize pool is $6, so NOT winner-take-all: + # the real parsed prize is required for correct $ P&L. + raw = ( + "Tournament #283232820, Spin&Gold #11, Hold'em No Limit\n" + "Buy-in: $1\n6 Players\nTotal Prize Pool: $6\n" + "Tournament started 2026/05/07 03:14:26\n" + "1st : Hero, $4\nYou finished in 1st place.\n" + ) + summary = parse_summary(raw) + assert summary is not None + t = build_tournament(summary, USER) + assert t.buy_in == 1.0 + assert t.hero_prize == 4.0 # net $ = 4 - 1 = +3 + + +def test_build_tournament_rows_matches_table_columns() -> None: + from datetime import datetime + + from spin2note_api.clickhouse.client import TABLE_COLUMNS + from spin2note_api.parser import build_tournament_rows + + summary = parse_summary(_read("summary/sample.txt")) + assert summary is not None + rows = build_tournament_rows([summary], USER, datetime(2026, 1, 1)) + # Tuple arity is the contract with TABLE_COLUMNS; hero_prize sits before parsed_at. + assert len(rows[0]) == len(TABLE_COLUMNS["tournaments"]) + assert rows[0][TABLE_COLUMNS["tournaments"].index("hero_prize")] == 0.0 diff --git a/apps/api/tests/test_queries.py b/apps/api/tests/test_queries.py index 4fb6d12..18a7bad 100644 --- a/apps/api/tests/test_queries.py +++ b/apps/api/tests/test_queries.py @@ -33,3 +33,21 @@ async def test_existing_hand_ids_empty() -> None: client = CountingClient() assert await existing_hand_ids(client, uuid4(), []) == set() # type: ignore[arg-type] assert client.calls == 0 + + +def test_cumulative_timeline_running_total_and_index() -> None: + rows = [(100.0, "2026-01-01T00:00:00"), (-30.0, "2026-01-02T00:00:00"), + (50.0, "2026-01-03T00:00:00")] + series = queries._cumulative_timeline(rows) # type: ignore[arg-type] + assert [p["idx"] for p in series] == [1, 2, 3] + assert [p["cumulative"] for p in series] == [100.0, 70.0, 120.0] + + +def test_cumulative_timeline_downsamples_and_keeps_last() -> None: + rows = [(1.0, f"2026-01-01T00:00:{i:02d}") for i in range(50)] + series = queries._cumulative_timeline(rows, max_points=10) # type: ignore[arg-type] + assert len(series) == 10 + # Index is monotonic and the final cumulative (sum of all 50) is preserved. + assert [p["idx"] for p in series] == sorted(p["idx"] for p in series) + assert series[-1]["idx"] == 50 + assert series[-1]["cumulative"] == 50.0 diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index cbb51f2..4672b40 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -3,6 +3,7 @@ import * as React from "react"; import { ResultByStack } from "@/components/charts/result-by-stack"; +import { CumulativeResult } from "@/components/charts/cumulative-result"; import { AppShell } from "@/components/app-shell"; import { Uploader } from "@/components/uploader"; import { Badge } from "@/components/ui/badge"; @@ -11,7 +12,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Table, TBody, TD, TH, THead, TR } from "@/components/ui/table"; import { getOverview, getRecentHands, type Overview, type RecentHand } from "@/lib/api"; import { useAuth } from "@/lib/auth"; -import { formatChips } from "@/lib/utils"; +import { formatChips, formatUsd } from "@/lib/utils"; type Format = "3max" | "6max" | undefined; @@ -96,6 +97,35 @@ function Dashboard() { +
+ + + Net result over time (chips) + + + {overview && overview.chips_timeline.length > 0 ? ( + + ) : ( +

No hands yet — upload a hand history.

+ )} +
+
+ + + + Net result over time ($) +

Real-money P&L across all formats.

+
+ + {overview && overview.dollars_timeline.length > 0 ? ( + + ) : ( +

No tournament summaries yet — upload one.

+ )} +
+
+
+ Recent hands diff --git a/apps/web/src/components/charts/cumulative-result.tsx b/apps/web/src/components/charts/cumulative-result.tsx new file mode 100644 index 0000000..91f84dd --- /dev/null +++ b/apps/web/src/components/charts/cumulative-result.tsx @@ -0,0 +1,66 @@ +"use client"; + +import { + Area, + AreaChart, + CartesianGrid, + ReferenceLine, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; + +import type { TimelinePoint } from "@/lib/api"; + +/** + * Cumulative "winnings graph" (PokerTracker/HM style): X is the sequential hand/tournament index, + * Y is the running net total. `format` renders the Y value (chips or USD) in ticks and tooltip. + */ +export function CumulativeResult({ + data, + format, +}: { + data: TimelinePoint[]; + format: (value: number) => string; +}) { + return ( + + + + + + + + + + + format(Number(v))} + width={72} + /> + + [format(Number(value)), "Cumulative"]} + labelFormatter={(idx) => `#${idx}`} + /> + + + + ); +} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 3ff788b..70cc94c 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -3,6 +3,7 @@ import type { components } from "./api/schema"; // Types come straight from the backend OpenAPI spec (regenerate via `npm run generate-client`). export type Overview = components["schemas"]["Overview"]; export type StackBucket = components["schemas"]["StackBucket"]; +export type TimelinePoint = components["schemas"]["TimelinePoint"]; export type RecentHand = components["schemas"]["RecentHand"]; export type UploadResult = components["schemas"]["UploadResult"]; export type ImportSummary = components["schemas"]["ImportSummary"]; diff --git a/apps/web/src/lib/api/schema.ts b/apps/web/src/lib/api/schema.ts index 2291f54..5052757 100644 --- a/apps/web/src/lib/api/schema.ts +++ b/apps/web/src/lib/api/schema.ts @@ -197,6 +197,10 @@ export interface components { avg_multiplier: number; /** By Stack */ by_stack: components["schemas"]["StackBucket"][]; + /** Chips Timeline */ + chips_timeline: components["schemas"]["TimelinePoint"][]; + /** Dollars Timeline */ + dollars_timeline: components["schemas"]["TimelinePoint"][]; }; /** RecentHand */ RecentHand: { @@ -226,6 +230,15 @@ export interface components { /** Winrate */ winrate: number; }; + /** TimelinePoint */ + TimelinePoint: { + /** Idx */ + idx: number; + /** At */ + at: string; + /** Cumulative */ + cumulative: number; + }; /** UploadResult */ UploadResult: { /** Object Key */ diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts index 22b32e1..04c7c30 100644 --- a/apps/web/src/lib/utils.ts +++ b/apps/web/src/lib/utils.ts @@ -9,3 +9,12 @@ export function formatChips(value: number): string { const sign = value > 0 ? "+" : ""; return `${sign}${value.toLocaleString("en-US")}`; } + +export function formatUsd(value: number): string { + const sign = value > 0 ? "+" : value < 0 ? "-" : ""; + const abs = Math.abs(value).toLocaleString("en-US", { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }); + return `${sign}$${abs}`; +} diff --git a/migrations/clickhouse/0003_tournament_hero_prize.sql b/migrations/clickhouse/0003_tournament_hero_prize.sql new file mode 100644 index 0000000..ee9f48d --- /dev/null +++ b/migrations/clickhouse/0003_tournament_hero_prize.sql @@ -0,0 +1,3 @@ +-- Persist hero's actual cash prize per tournament (parsed from summary finishes). +-- Enables real-money P&L: net_dollars = hero_prize - buy_in. Idempotent. +ALTER TABLE tournaments ADD COLUMN IF NOT EXISTS hero_prize Float64 AFTER hero_place;