Add championship hub with derived stats and progression views

New /api/v1/championship/hub endpoint aggregates official standings with
wins, podiums, poles, recent form, teammate head-to-head, and per-round
cumulative points. ChampionshipPage renders drivers, constructors, and
progression views.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 00:09:47 -04:00
parent 91e2d13ab7
commit 2220d5d30a
10 changed files with 1762 additions and 1 deletions

View File

@@ -597,6 +597,292 @@ func (s *Server) handleChampionshipTeams(w http.ResponseWriter, r *http.Request)
writeJSON(w, teams)
}
// --- /api/v1/championship/hub ---
// Aggregated championship view: official points/positions enriched with derived
// stats (wins, podiums, poles, recent form, teammate head-to-head) and a
// per-round cumulative-points series, computed from season race results.
type champHubDriver struct {
DriverNumber int `json:"driver_number"`
NameAcronym string `json:"name_acronym"`
FullName string `json:"full_name"`
TeamName string `json:"team_name"`
TeamColour string `json:"team_colour"`
Points float64 `json:"points"`
Position int `json:"position"`
Wins int `json:"wins"`
Podiums int `json:"podiums"`
Poles int `json:"poles"`
Form []float64 `json:"form"` // last 5 races' points
Cumulative []float64 `json:"cumulative"` // running total per completed round
TeammateWins int `json:"teammate_wins"`
TeammateLosses int `json:"teammate_losses"`
}
type champHubTeam struct {
TeamName string `json:"team_name"`
TeamColour string `json:"team_colour"`
Points float64 `json:"points"`
Position int `json:"position"`
Wins int `json:"wins"`
}
type champHubResponse struct {
Season int `json:"season"`
Round int `json:"round"`
TotalRounds int `json:"total_rounds"`
RoundsLeft int `json:"rounds_left"`
LastRace string `json:"last_race"`
RoundLabels []string `json:"round_labels"`
Drivers []champHubDriver `json:"drivers"`
Teams []champHubTeam `json:"teams"`
}
// meetingRace bundles a GP meeting with its (already-fetched) race results and grid.
type meetingRace struct {
Meeting models.Meeting
RaceSessionKey int
Results []models.SessionResult
Grid []models.StartingGrid
}
func (s *Server) handleChampionshipHub(w http.ResponseWriter, r *http.Request) {
year, _ := strconv.Atoi(r.URL.Query().Get("year"))
if year == 0 {
year = time.Now().Year()
}
meetings, err := s.client.GetMeetingsForYear(year)
if err != nil {
writeError(w, err, http.StatusInternalServerError, s.client.LastResponseWasStale())
return
}
champ, err := s.client.GetDriverChampionshipForYear(year)
if err != nil {
writeError(w, err, http.StatusInternalServerError, s.client.LastResponseWasStale())
return
}
if len(champ) == 0 {
writeJSON(w, champHubResponse{Season: year, RoundLabels: []string{}, Drivers: []champHubDriver{}, Teams: []champHubTeam{}})
return
}
teams, _ := s.client.GetTeamChampionshipForYear(year)
driverInfo := map[int]models.Driver{}
if ds, derr := s.client.GetDriversForSession(champ[0].SessionKey); derr == nil {
driverInfo = buildDriverMapFirst(ds)
}
sort.Slice(meetings, func(i, j int) bool { return meetings[i].DateStart < meetings[j].DateStart })
races := make([]meetingRace, 0, len(meetings))
for _, m := range meetings {
sessions, serr := s.client.GetSessionsForMeeting(int(m.MeetingKey))
if serr != nil {
continue
}
raceKey := 0
for _, sess := range sessions {
if strings.EqualFold(sess.SessionName, "Race") {
raceKey = sess.SessionKey
break
}
}
if raceKey == 0 {
continue // not a GP meeting (e.g. pre-season testing)
}
results, _ := s.client.GetSessionResult(raceKey)
grid, _ := s.client.GetStartingGrid(raceKey)
races = append(races, meetingRace{Meeting: m, RaceSessionKey: raceKey, Results: results, Grid: grid})
}
writeJSON(w, aggregateChampionshipHub(year, races, champ, teams, driverInfo))
}
// aggregateChampionshipHub is the pure aggregation core (no network) so it can be
// unit-tested with synthetic data. races must be ordered ascending by date and
// contain only GP meetings (those with a Race session).
func aggregateChampionshipHub(
year int,
races []meetingRace,
champ []models.ChampionshipDriver,
teams []models.ChampionshipTeam,
driverInfo map[int]models.Driver,
) champHubResponse {
type acc struct {
wins, podiums, poles int
form []float64
finishByRound map[int]int
}
accs := map[int]*acc{}
getAcc := func(num int) *acc {
a := accs[num]
if a == nil {
a = &acc{finishByRound: map[int]int{}}
accs[num] = a
}
return a
}
completed := 0
lastRace := ""
roundPoints := []map[int]float64{} // per completed round: driver -> race points
for _, mr := range races {
if len(mr.Results) == 0 {
continue // round not completed yet
}
completed++
lastRace = mr.Meeting.MeetingName
for _, g := range mr.Grid {
if g.Position == 1 {
getAcc(g.DriverNumber).poles++
}
}
rp := map[int]float64{}
for _, res := range mr.Results {
a := getAcc(res.DriverNumber)
if res.Position == 1 {
a.wins++
}
if res.Position >= 1 && res.Position <= 3 {
a.podiums++
}
a.form = append(a.form, res.Points)
a.finishByRound[completed] = res.Position
rp[res.DriverNumber] += res.Points
}
roundPoints = append(roundPoints, rp)
}
roundLabels := make([]string, 0, completed)
for i := 1; i <= completed; i++ {
roundLabels = append(roundLabels, fmt.Sprintf("R%d", i))
}
// Official totals are authoritative; reconcile the cumulative endpoint to them.
champPts := map[int]float64{}
for _, c := range champ {
champPts[c.DriverNumber] = c.PointsCurrent
}
cumulative := map[int][]float64{}
for num := range accs {
running := 0.0
series := make([]float64, 0, completed)
for i := 0; i < completed; i++ {
running += roundPoints[i][num]
series = append(series, running)
}
if completed > 0 {
if off, ok := champPts[num]; ok {
series[completed-1] = off
}
}
cumulative[num] = series
}
// Teammate head-to-head: per round, the teammate finishing ahead wins.
teamOf := func(num int) string { return driverInfo[num].TeamName }
byTeam := map[string][]int{}
for num := range accs {
byTeam[teamOf(num)] = append(byTeam[teamOf(num)], num)
}
twins := map[int]int{}
tloss := map[int]int{}
for team, members := range byTeam {
if team == "" || len(members) < 2 {
continue
}
for round := 1; round <= completed; round++ {
for i := 0; i < len(members); i++ {
for j := i + 1; j < len(members); j++ {
p1, ok1 := accs[members[i]].finishByRound[round]
p2, ok2 := accs[members[j]].finishByRound[round]
if !ok1 || !ok2 {
continue
}
if p1 < p2 {
twins[members[i]]++
tloss[members[j]]++
} else if p2 < p1 {
twins[members[j]]++
tloss[members[i]]++
}
}
}
}
}
sortedChamp := make([]models.ChampionshipDriver, len(champ))
copy(sortedChamp, champ)
sort.Slice(sortedChamp, func(i, j int) bool { return sortedChamp[i].PositionCurrent < sortedChamp[j].PositionCurrent })
drivers := make([]champHubDriver, 0, len(sortedChamp))
for _, c := range sortedChamp {
a := accs[c.DriverNumber]
if a == nil {
a = &acc{}
}
form := a.form
if len(form) > 5 {
form = form[len(form)-5:]
}
info := driverInfo[c.DriverNumber]
drivers = append(drivers, champHubDriver{
DriverNumber: c.DriverNumber,
NameAcronym: info.NameAcronym,
FullName: info.FullName,
TeamName: info.TeamName,
TeamColour: info.TeamColour,
Points: c.PointsCurrent,
Position: c.PositionCurrent,
Wins: a.wins,
Podiums: a.podiums,
Poles: a.poles,
Form: form,
Cumulative: cumulative[c.DriverNumber],
TeammateWins: twins[c.DriverNumber],
TeammateLosses: tloss[c.DriverNumber],
})
}
teamWins := map[string]int{}
teamColour := map[string]string{}
for num, a := range accs {
teamWins[teamOf(num)] += a.wins
if col := driverInfo[num].TeamColour; col != "" {
teamColour[teamOf(num)] = col
}
}
sortedTeams := make([]models.ChampionshipTeam, len(teams))
copy(sortedTeams, teams)
sort.Slice(sortedTeams, func(i, j int) bool { return sortedTeams[i].PositionCurrent < sortedTeams[j].PositionCurrent })
teamsOut := make([]champHubTeam, 0, len(sortedTeams))
for _, t := range sortedTeams {
teamsOut = append(teamsOut, champHubTeam{
TeamName: t.TeamName,
TeamColour: teamColour[t.TeamName],
Points: t.PointsCurrent,
Position: t.PositionCurrent,
Wins: teamWins[t.TeamName],
})
}
totalRounds := len(races)
return champHubResponse{
Season: year,
Round: completed,
TotalRounds: totalRounds,
RoundsLeft: totalRounds - completed,
LastRace: lastRace,
RoundLabels: roundLabels,
Drivers: drivers,
Teams: teamsOut,
}
}
// --- /api/v1/track-outline ---
// Accepts circuit_key and year (the frontend has both from meeting+session data).

View File

@@ -0,0 +1,142 @@
package web
import (
"testing"
"github.com/AmanTahiliani/box-box/internal/models"
)
func raceResult(num, pos int, pts float64) models.SessionResult {
return models.SessionResult{DriverNumber: num, Position: pos, Points: pts}
}
func TestAggregateChampionshipHub(t *testing.T) {
driverInfo := map[int]models.Driver{
1: {DriverNumber: 1, NameAcronym: "VER", FullName: "Max Verstappen", TeamName: "Red Bull", TeamColour: "3671c6"},
2: {DriverNumber: 2, NameAcronym: "PER", FullName: "Sergio Perez", TeamName: "Red Bull", TeamColour: "3671c6"},
3: {DriverNumber: 3, NameAcronym: "HAM", FullName: "Lewis Hamilton", TeamName: "Mercedes", TeamColour: "27f4d2"},
}
champ := []models.ChampionshipDriver{
{DriverNumber: 1, PointsCurrent: 50, PositionCurrent: 1, SessionKey: 99},
{DriverNumber: 3, PointsCurrent: 33, PositionCurrent: 2, SessionKey: 99},
{DriverNumber: 2, PointsCurrent: 30, PositionCurrent: 3, SessionKey: 99},
}
teams := []models.ChampionshipTeam{
{TeamName: "Red Bull", PointsCurrent: 80, PositionCurrent: 1},
{TeamName: "Mercedes", PointsCurrent: 33, PositionCurrent: 2},
}
// Round 1: VER P1(25), HAM P2(18), PER P3(15). Pole: VER.
// Round 2: VER P1(25), PER P2(18), HAM P3(15). Pole: HAM.
races := []meetingRace{
{
Meeting: models.Meeting{MeetingName: "Bahrain GP"},
Results: []models.SessionResult{raceResult(1, 1, 25), raceResult(3, 2, 18), raceResult(2, 3, 15)},
Grid: []models.StartingGrid{{DriverNumber: 1, Position: 1}},
},
{
Meeting: models.Meeting{MeetingName: "Saudi GP"},
Results: []models.SessionResult{raceResult(1, 1, 25), raceResult(2, 2, 18), raceResult(3, 3, 15)},
Grid: []models.StartingGrid{{DriverNumber: 3, Position: 1}},
},
// Round 3: not yet run (no results) — should not count as completed.
{Meeting: models.Meeting{MeetingName: "Australia GP"}},
}
resp := aggregateChampionshipHub(2025, races, champ, teams, driverInfo)
if resp.Season != 2025 {
t.Errorf("season = %d, want 2025", resp.Season)
}
if resp.Round != 2 {
t.Errorf("completed rounds = %d, want 2", resp.Round)
}
if resp.TotalRounds != 3 {
t.Errorf("total rounds = %d, want 3", resp.TotalRounds)
}
if resp.RoundsLeft != 1 {
t.Errorf("rounds left = %d, want 1", resp.RoundsLeft)
}
if resp.LastRace != "Saudi GP" {
t.Errorf("last race = %q, want Saudi GP", resp.LastRace)
}
if len(resp.RoundLabels) != 2 || resp.RoundLabels[0] != "R1" || resp.RoundLabels[1] != "R2" {
t.Errorf("round labels = %v, want [R1 R2]", resp.RoundLabels)
}
// Drivers are sorted by official position: VER, HAM, PER.
if len(resp.Drivers) != 3 {
t.Fatalf("drivers = %d, want 3", len(resp.Drivers))
}
ver := resp.Drivers[0]
if ver.NameAcronym != "VER" || ver.Position != 1 {
t.Errorf("first driver = %s P%d, want VER P1", ver.NameAcronym, ver.Position)
}
if ver.Wins != 2 {
t.Errorf("VER wins = %d, want 2", ver.Wins)
}
if ver.Podiums != 2 {
t.Errorf("VER podiums = %d, want 2", ver.Podiums)
}
if ver.Poles != 1 {
t.Errorf("VER poles = %d, want 1", ver.Poles)
}
if len(ver.Form) != 2 || ver.Form[0] != 25 || ver.Form[1] != 25 {
t.Errorf("VER form = %v, want [25 25]", ver.Form)
}
// Cumulative reconciles final value to official total (50).
if len(ver.Cumulative) != 2 || ver.Cumulative[0] != 25 || ver.Cumulative[1] != 50 {
t.Errorf("VER cumulative = %v, want [25 50]", ver.Cumulative)
}
// VER beat teammate PER in both rounds.
if ver.TeammateWins != 2 || ver.TeammateLosses != 0 {
t.Errorf("VER h2h = %d-%d, want 2-0", ver.TeammateWins, ver.TeammateLosses)
}
// PER lost both intra-team battles to VER.
var per champHubDriver
for _, d := range resp.Drivers {
if d.NameAcronym == "PER" {
per = d
}
}
if per.TeammateWins != 0 || per.TeammateLosses != 2 {
t.Errorf("PER h2h = %d-%d, want 0-2", per.TeammateWins, per.TeammateLosses)
}
if per.Poles != 0 {
t.Errorf("PER poles = %d, want 0", per.Poles)
}
// HAM has no teammate in the data — no h2h recorded.
var ham champHubDriver
for _, d := range resp.Drivers {
if d.NameAcronym == "HAM" {
ham = d
}
}
if ham.TeammateWins != 0 || ham.TeammateLosses != 0 {
t.Errorf("HAM h2h = %d-%d, want 0-0 (no teammate)", ham.TeammateWins, ham.TeammateLosses)
}
if ham.Poles != 1 {
t.Errorf("HAM poles = %d, want 1", ham.Poles)
}
// Teams sorted by position; Red Bull wins = VER(2) + PER(0) = 2.
if len(resp.Teams) != 2 {
t.Fatalf("teams = %d, want 2", len(resp.Teams))
}
if resp.Teams[0].TeamName != "Red Bull" || resp.Teams[0].Wins != 2 {
t.Errorf("top team = %s wins %d, want Red Bull wins 2", resp.Teams[0].TeamName, resp.Teams[0].Wins)
}
if resp.Teams[0].TeamColour != "3671c6" {
t.Errorf("Red Bull colour = %q, want 3671c6", resp.Teams[0].TeamColour)
}
}
func TestAggregateChampionshipHubEmpty(t *testing.T) {
resp := aggregateChampionshipHub(2025, nil, nil, nil, map[int]models.Driver{})
if resp.Round != 0 || resp.TotalRounds != 0 || len(resp.Drivers) != 0 {
t.Errorf("empty aggregation should be zero-valued, got %+v", resp)
}
}

View File

@@ -81,6 +81,7 @@ func (s *Server) routes() (http.Handler, error) {
mux.HandleFunc("/api/v1/team-radio", s.handleTeamRadio)
mux.HandleFunc("/api/v1/championship/drivers", s.handleChampionshipDrivers)
mux.HandleFunc("/api/v1/championship/teams", s.handleChampionshipTeams)
mux.HandleFunc("/api/v1/championship/hub", s.handleChampionshipHub)
mux.HandleFunc("/api/v1/track-outline", s.handleTrackOutline)
mux.HandleFunc("/api/v1/strategy", s.handleStrategy)
mux.HandleFunc("/api/v1/live/state", s.handleLiveState)