Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/api/src/spin2note_api/clickhouse/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
],
}

Expand Down
53 changes: 53 additions & 0 deletions apps/api/src/spin2note_api/clickhouse/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}:
Expand Down Expand Up @@ -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,
}


Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/spin2note_api/domain/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
8 changes: 8 additions & 0 deletions apps/api/src/spin2note_api/http/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 8 additions & 1 deletion apps/api/src/spin2note_api/parser/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
]
Expand All @@ -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),
)
2 changes: 2 additions & 0 deletions apps/api/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]:
Expand Down
31 changes: 31 additions & 0 deletions apps/api/tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
18 changes: 18 additions & 0 deletions apps/api/tests/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 31 additions & 1 deletion apps/web/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;

Expand Down Expand Up @@ -96,6 +97,35 @@ function Dashboard() {
</CardContent>
</Card>

<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Net result over time (chips)</CardTitle>
</CardHeader>
<CardContent>
{overview && overview.chips_timeline.length > 0 ? (
<CumulativeResult data={overview.chips_timeline} format={formatChips} />
) : (
<p className="py-12 text-center text-sm text-muted-foreground">No hands yet — upload a hand history.</p>
)}
</CardContent>
</Card>

<Card>
<CardHeader>
<CardTitle>Net result over time ($)</CardTitle>
<p className="text-xs text-muted-foreground">Real-money P&amp;L across all formats.</p>
</CardHeader>
<CardContent>
{overview && overview.dollars_timeline.length > 0 ? (
<CumulativeResult data={overview.dollars_timeline} format={formatUsd} />
) : (
<p className="py-12 text-center text-sm text-muted-foreground">No tournament summaries yet — upload one.</p>
)}
</CardContent>
</Card>
</div>

<Card>
<CardHeader>
<CardTitle>Recent hands</CardTitle>
Expand Down
66 changes: 66 additions & 0 deletions apps/web/src/components/charts/cumulative-result.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<ResponsiveContainer width="100%" height={260}>
<AreaChart data={data} margin={{ top: 8, right: 8, bottom: 8, left: 8 }}>
<defs>
<linearGradient id="cumFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="hsl(152 70% 45%)" stopOpacity={0.35} />
<stop offset="100%" stopColor="hsl(152 70% 45%)" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(217 33% 17%)" vertical={false} />
<XAxis dataKey="idx" tick={{ fill: "hsl(215 20% 65%)", fontSize: 12 }} />
<YAxis
tick={{ fill: "hsl(215 20% 65%)", fontSize: 12 }}
tickFormatter={(v) => format(Number(v))}
width={72}
/>
<ReferenceLine y={0} stroke="hsl(217 33% 30%)" />
<Tooltip
contentStyle={{
background: "hsl(222 40% 8%)",
border: "1px solid hsl(217 33% 17%)",
borderRadius: 8,
color: "hsl(210 40% 96%)",
}}
formatter={(value: number) => [format(Number(value)), "Cumulative"]}
labelFormatter={(idx) => `#${idx}`}
/>
<Area
type="monotone"
dataKey="cumulative"
stroke="hsl(152 70% 45%)"
strokeWidth={2}
fill="url(#cumFill)"
dot={false}
isAnimationActive={false}
/>
</AreaChart>
</ResponsiveContainer>
);
}
1 change: 1 addition & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
13 changes: 13 additions & 0 deletions apps/web/src/lib/api/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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 */
Expand Down
9 changes: 9 additions & 0 deletions apps/web/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
3 changes: 3 additions & 0 deletions migrations/clickhouse/0003_tournament_hero_prize.sql
Original file line number Diff line number Diff line change
@@ -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;
Loading