Compare commits

..
Author SHA1 Message Date
AmanTahilianiandCursor a1e6b6af35 feat(#105): design Preview circuit-outline unavailable state
Keep the Circuit card when GPS outline is missing: show meeting identity and an honest local-cache explanation instead of a one-line empty section.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 15:36:19 -04:00
15 changed files with 195 additions and 455 deletions

No files matched your search

@@ -10,7 +10,6 @@ import {
projectStandings, projectStandings,
} from '../lib/simulator' } from '../lib/simulator'
import type { Scenario } from '../lib/simulator' import type { Scenario } from '../lib/simulator'
import { maxPointsLeft } from '../lib/titleMath'
const STORAGE_PREFIX = 'box-box.champ.sim' const STORAGE_PREFIX = 'box-box.champ.sim'
@@ -61,8 +60,8 @@ export function ChampionshipSimulator({ hub }: { hub: ChampionshipHub }) {
}, [hub.season, scenario]) }, [hub.season, scenario])
const projected = useMemo( const projected = useMemo(
() => projectStandings(hub.drivers, scenario, hub.rounds_left, maxPointsLeft(hub)), () => projectStandings(hub.drivers, scenario, hub.rounds_left),
[hub, scenario], [hub.drivers, scenario, hub.rounds_left],
) )
if (hub.rounds_left <= 0 || hub.drivers.length === 0 || scenario.length === 0) { if (hub.rounds_left <= 0 || hub.drivers.length === 0 || scenario.length === 0) {
+1 -4
View File
@@ -122,14 +122,11 @@ export function pointsGapMeaning(
gapToAhead: number | null | undefined, gapToAhead: number | null | undefined,
roundsLeft: number, roundsLeft: number,
driverAhead?: string | null, driverAhead?: string | null,
maxPointsLeft?: number,
): MeaningAnnotation | null { ): MeaningAnnotation | null {
if (gapToAhead == null || !Number.isFinite(gapToAhead) || gapToAhead <= 0) return null if (gapToAhead == null || !Number.isFinite(gapToAhead) || gapToAhead <= 0) return null
if (!Number.isFinite(roundsLeft) || roundsLeft <= 0) return null if (!Number.isFinite(roundsLeft) || roundsLeft <= 0) return null
// Prefer the sprint-aware ceiling when the caller has it. const maxCatchable = roundsLeft * MAX_POINTS_PER_ROUND
const maxCatchable =
maxPointsLeft != null && Number.isFinite(maxPointsLeft) ? maxPointsLeft : roundsLeft * MAX_POINTS_PER_ROUND
const ahead = driverAhead?.trim() || 'ahead' const ahead = driverAhead?.trim() || 'ahead'
if (gapToAhead > maxCatchable) { if (gapToAhead > maxCatchable) {
+1 -6
View File
@@ -127,8 +127,6 @@ export function projectStandings(
drivers: ReadonlyArray<ChampHubDriver>, drivers: ReadonlyArray<ChampHubDriver>,
scenario: Scenario, scenario: Scenario,
roundsLeft: number, roundsLeft: number,
/** Sprint-aware points ceiling; defaults to race wins only. */
maxPointsLeft?: number,
): ProjectedDriver[] { ): ProjectedDriver[] {
if (drivers.length === 0) return [] if (drivers.length === 0) return []
@@ -136,10 +134,7 @@ export function projectStandings(
const ordered = championshipOrder(drivers) const ordered = championshipOrder(drivers)
const leader = ordered[0] const leader = ordered[0]
const leaderProjected = leader.points + (extras.get(leader.driver_number) ?? 0) const leaderProjected = leader.points + (extras.get(leader.driver_number) ?? 0)
const maxRemaining = const maxRemaining = MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
maxPointsLeft != null && Number.isFinite(maxPointsLeft)
? Math.max(0, maxPointsLeft)
: MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
const rows = ordered.map((driver, i) => { const rows = ordered.map((driver, i) => {
const simPoints = extras.get(driver.driver_number) ?? 0 const simPoints = extras.get(driver.driver_number) ?? 0
-74
View File
@@ -1,74 +0,0 @@
// Title math shared by the championship views. Pure functions only.
import type { ChampHubDriver, ChampionshipHub } from '../types'
/** Max points one driver can take from a Grand Prix / a Sprint (2025+ rules). */
export const MAX_RACE_POINTS = 25
export const MAX_SPRINT_POINTS = 8
/**
* Most points any one driver can still score this season. Prefers the
* server's sprint-aware `max_points_left`; falls back to race wins only for
* older API responses that do not carry it.
*/
export function maxPointsLeft(hub: Pick<ChampionshipHub, 'rounds_left' | 'max_points_left' | 'sprints_left'>): number {
if (typeof hub.max_points_left === 'number' && Number.isFinite(hub.max_points_left)) {
return Math.max(0, hub.max_points_left)
}
const rounds = Math.max(0, hub.rounds_left || 0)
const sprints = Math.max(0, hub.sprints_left || 0)
return rounds * MAX_RACE_POINTS + sprints * MAX_SPRINT_POINTS
}
/** Grand Prix finishing-position counts (position -> count) from round_positions. */
function finishCounts(positions: ReadonlyArray<number> | undefined): Map<number, number> {
const counts = new Map<number, number>()
for (const p of positions ?? []) {
if (p > 0) counts.set(p, (counts.get(p) ?? 0) + 1)
}
return counts
}
/**
* True only when `leader` is guaranteed to beat `rival` on countback if the
* rival wins every remaining Grand Prix and the leader scores nothing (the
* only way the two can finish level when the gap equals the points left).
* The leader's remaining finishes are unknown but outside the points, so a
* countback decided in the leader's favour cannot be overturned by them.
*/
function leaderWinsWorstCaseCountback(leader: ChampHubDriver, rival: ChampHubDriver, roundsLeft: number): boolean {
const lead = finishCounts(leader.round_positions)
const riv = finishCounts(rival.round_positions)
riv.set(1, (riv.get(1) ?? 0) + Math.max(0, roundsLeft))
const maxPos = Math.max(0, ...lead.keys(), ...riv.keys())
for (let p = 1; p <= maxPos; p++) {
const diff = (lead.get(p) ?? 0) - (riv.get(p) ?? 0)
if (diff !== 0) return diff > 0
}
return false
}
/**
* The champion once the title is mathematically decided, else null.
* `drivers` must be in championship order (ties already resolved by the
* server's countback). Decided when the season is over, or when no rival can
* catch the leader: every rival is further behind than the points left, or
* exactly that far behind but certain to lose the countback.
*/
export function decidedChampion(
drivers: ReadonlyArray<ChampHubDriver>,
maxLeft: number,
roundsLeft = 0,
): ChampHubDriver | null {
const [leader, ...rivals] = drivers
if (!leader) return null
if (maxLeft <= 0) return leader
if (rivals.length === 0) return null
for (const rival of rivals) {
const gap = leader.points - rival.points
if (gap > maxLeft) continue
if (gap === maxLeft && leaderWinsWorstCaseCountback(leader, rival, roundsLeft)) continue
return null
}
return leader
}
+11 -29
View File
@@ -10,7 +10,6 @@ import { Meaning } from '../components/Meaning'
import { TeammateH2H } from '../components/TeammateH2H' import { TeammateH2H } from '../components/TeammateH2H'
import { teammatePairs } from '../lib/h2h' import { teammatePairs } from '../lib/h2h'
import { pointsGapMeaning } from '../lib/meaning' import { pointsGapMeaning } from '../lib/meaning'
import { decidedChampion, maxPointsLeft } from '../lib/titleMath'
type View = 'drivers' | 'constructors' | 'progression' | 'rivalry' | 'simulator' type View = 'drivers' | 'constructors' | 'progression' | 'rivalry' | 'simulator'
@@ -131,9 +130,7 @@ interface BodyProps {
function ChampionshipBody({ hub, view, setView }: BodyProps) { function ChampionshipBody({ hub, view, setView }: BodyProps) {
const { drivers, teams } = hub const { drivers, teams } = hub
const leader = drivers[0] const leader = drivers[0]
const remaining = maxPointsLeft(hub) const remaining = hub.rounds_left * 25
const champion = decidedChampion(drivers, remaining, hub.rounds_left)
const sprintsLeft = hub.sprints_left ?? 0
const enriched = useMemo<EnrichedDriver[]>( const enriched = useMemo<EnrichedDriver[]>(
() => () =>
@@ -152,31 +149,21 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
spark: sparkPoints(d.form), spark: sparkPoints(d.form),
h2h: `${d.teammate_wins}–${d.teammate_losses}`, h2h: `${d.teammate_wins}–${d.teammate_losses}`,
h2hWin: d.teammate_wins >= d.teammate_losses, h2hWin: d.teammate_wins >= d.teammate_losses,
aliveLabel: i === 0 ? (champion ? 'CHAMPION' : 'LEADS') : alive && !champion ? 'ALIVE' : 'OUT', aliveLabel: i === 0 ? 'LEADS' : alive ? 'ALIVE' : 'OUT',
aliveColor: i === 0 ? GOLD : alive && !champion ? 'var(--green)' : 'var(--text-3)', aliveColor: i === 0 ? GOLD : alive ? 'var(--green)' : 'var(--text-3)',
} }
}), }),
[drivers, leader, remaining, champion], [drivers, leader, remaining],
) )
const aliveCount = enriched.filter((e) => e.aliveLabel === 'ALIVE' || e.aliveLabel === 'LEADS').length const aliveCount = enriched.filter((e) => e.aliveLabel === 'ALIVE' || e.aliveLabel === 'LEADS').length
const roundsLeftText = `${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'}` const titleMath =
const sprintsLeftText = sprintsLeft > 0 ? ` + ${sprintsLeft} sprint${sprintsLeft === 1 ? '' : 's'}` : '' `${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
const leadText = `With ${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'} left (max ${remaining} pts), ` +
`${leader.name_acronym} leads ` +
(drivers[1] ? `${drivers[1].name_acronym} by ${fmtPts(leader.points - drivers[1].points)}` : 'the field') + (drivers[1] ? `${drivers[1].name_acronym} by ${fmtPts(leader.points - drivers[1].points)}` : 'the field') +
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}` : '') (drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}.` : '.')
const titleMath = champion
? hub.rounds_left > 0
? `${champion.full_name || champion.name_acronym} has clinched the ${hub.season} Drivers' Championship. ` +
`${champion.name_acronym} leads ${leadText} with only ${fmtPts(remaining)} pts left ` +
`(${roundsLeftText}${sprintsLeftText}).`
: `${champion.full_name || champion.name_acronym} is the ${hub.season} World Champion, ` +
`finishing ahead of ${leadText}.`
: `${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
`With ${roundsLeftText}${sprintsLeftText} left (max ${fmtPts(remaining)} pts), ` +
`${leader.name_acronym} leads ${leadText}.`
const topTeam = teams[0] const topTeam = teams[0]
const teamGap = teams[1] ? topTeam.points - teams[1].points : 0 const teamGap = teams[1] ? topTeam.points - teams[1].points : 0
@@ -190,9 +177,7 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
sub: teams[1] ? `+${fmtPts(teamGap)} ahead` : 'Sole entry', sub: teams[1] ? `+${fmtPts(teamGap)} ahead` : 'Sole entry',
color: '#fff', color: '#fff',
}, },
champion { label: 'Title Fight', value: `${aliveCount} alive`, sub: `${hub.rounds_left} rounds remain`, color: 'var(--red)' },
? { label: 'Champion', value: champion.name_acronym, sub: hub.rounds_left > 0 ? `Clinched · ${roundsLeftText} to spare` : 'Season complete', color: GOLD }
: { label: 'Title Fight', value: `${aliveCount} alive`, sub: `${roundsLeftText} remain`, color: 'var(--red)' },
{ label: 'Season Progress', value: `${seasonPct}%`, sub: `Round ${hub.round}/${hub.total_rounds}`, color: '#fff' }, { label: 'Season Progress', value: `${seasonPct}%`, sub: `Round ${hub.round}/${hub.total_rounds}`, color: '#fff' },
] ]
@@ -269,7 +254,6 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
leaderPoints={leader.points} leaderPoints={leader.points}
titleMath={titleMath} titleMath={titleMath}
roundsLeft={hub.rounds_left} roundsLeft={hub.rounds_left}
maxPointsLeft={remaining}
drivers={drivers} drivers={drivers}
season={hub.season} season={hub.season}
/> />
@@ -302,7 +286,6 @@ function DriversView({
leaderPoints, leaderPoints,
titleMath, titleMath,
roundsLeft, roundsLeft,
maxPointsLeft,
drivers, drivers,
season, season,
}: { }: {
@@ -310,7 +293,6 @@ function DriversView({
leaderPoints: number leaderPoints: number
titleMath: string titleMath: string
roundsLeft: number roundsLeft: number
maxPointsLeft: number
drivers: ChampHubDriver[] drivers: ChampHubDriver[]
season: number season: number
}) { }) {
@@ -441,7 +423,7 @@ function DriversView({
<td className="r mono champ-td-muted">{e.gapLeader}</td> <td className="r mono champ-td-muted">{e.gapLeader}</td>
<td className="r mono champ-td-dim"> <td className="r mono champ-td-dim">
{(() => { {(() => {
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead, maxPointsLeft) const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead)
return ( return (
<Meaning <Meaning
value={e.gapAhead} value={e.gapAhead}
+46 -13
View File
@@ -58,35 +58,67 @@ function SectionState({
return <>{children}</> return <>{children}</>
} }
function circuitIdentity(meeting: Meeting): { name: string; place: string } {
const name = meeting.circuit_short_name?.trim() || meeting.meeting_name
const location = meeting.location?.trim() ?? ''
const country = meeting.country_name?.trim() ?? ''
const parts: string[] = []
if (location) parts.push(location)
if (country && country !== location) parts.push(country)
return { name, place: parts.join(' · ') }
}
function TrackOutlineCard({ function TrackOutlineCard({
meeting,
outline, outline,
loading, loading,
error, error,
accent, accent,
}: { }: {
meeting: Meeting
outline: TrackOutline | null | undefined outline: TrackOutline | null | undefined
loading: boolean loading: boolean
error: Error | null error: Error | null
accent: string accent: string
}) { }) {
const outlinePath = useMemo(() => buildOutlinePath(outline?.points ?? []), [outline]) const outlinePath = useMemo(() => buildOutlinePath(outline?.points ?? []), [outline])
const identity = circuitIdentity(meeting)
let body: ReactNode
if (loading) {
body = <div className="preview-section-state">Loading…</div>
} else if (error) {
body = (
<div className="preview-section-state error">
{error instanceof Error ? error.message : 'Failed to load'}
</div>
)
} else if (outlinePath) {
body = (
<div className="preview-track-stage" style={{ ['--preview-accent' as string]: accent }}>
<svg className="preview-track-svg" viewBox="0 0 100 100" role="img" aria-label="Circuit outline">
<path className="preview-track-shadow" d={outlinePath} />
<path className="preview-track-outline" d={outlinePath} />
</svg>
</div>
)
} else {
body = (
<div className="preview-track-fallback" data-testid="preview-track-fallback">
<div className="preview-track-fallback-glyph" aria-hidden />
<p className="preview-track-fallback-name">{identity.name}</p>
{identity.place && <p className="preview-track-fallback-place">{identity.place}</p>}
<p className="preview-track-fallback-hint">
A GPS track outline is not available in the local cache.
</p>
</div>
)
}
return ( return (
<section className="preview-card" data-testid="preview-track-card"> <section className="preview-card" data-testid="preview-track-card">
<h2 className="preview-card-title">Circuit</h2> <h2 className="preview-card-title">Circuit</h2>
<SectionState {body}
loading={loading}
error={error}
empty={!outline || !outlinePath}
emptyMessage="Track outline unavailable for this circuit"
>
<div className="preview-track-stage" style={{ ['--preview-accent' as string]: accent }}>
<svg className="preview-track-svg" viewBox="0 0 100 100" role="img" aria-label="Circuit outline">
<path className="preview-track-shadow" d={outlinePath} />
<path className="preview-track-outline" d={outlinePath} />
</svg>
</div>
</SectionState>
</section> </section>
) )
} }
@@ -408,6 +440,7 @@ export function RacePreviewPage() {
<div className="preview-grid"> <div className="preview-grid">
<TrackOutlineCard <TrackOutlineCard
meeting={previewMeeting}
outline={trackOutlineQuery.data} outline={trackOutlineQuery.data}
loading={trackOutlineQuery.isLoading} loading={trackOutlineQuery.isLoading}
error={trackOutlineQuery.isError ? (trackOutlineQuery.error as Error) : null} error={trackOutlineQuery.isError ? (trackOutlineQuery.error as Error) : null}
+41
View File
@@ -203,6 +203,47 @@
stroke-linejoin: round; stroke-linejoin: round;
} }
.preview-track-fallback {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
gap: var(--s2);
min-height: 180px;
padding: var(--s5);
}
.preview-track-fallback-glyph {
width: 88px;
height: 52px;
margin-bottom: var(--s2);
border: 2px dashed rgba(255, 255, 255, 0.14);
border-radius: 42% 50% 46% 54%;
}
.preview-track-fallback-name {
font-size: 1.2rem;
font-weight: 600;
color: var(--text-1);
margin: 0;
}
.preview-track-fallback-place {
font-size: 0.85rem;
color: var(--text-2);
margin: 0;
}
.preview-track-fallback-hint {
font-size: 0.8rem;
line-height: 1.5;
color: var(--text-3);
max-width: 22rem;
margin: var(--s2) 0 0;
}
.preview-podium { .preview-podium {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -118,31 +118,6 @@ describe('ChampionshipPage', () => {
expect(screen.getAllByText('~10 pts/round').length).toBeGreaterThan(0) expect(screen.getAllByText('~10 pts/round').length).toBeGreaterThan(0)
}) })
it('declares the champion once the gap exceeds the points left', async () => {
// VER leads NOR by 40 with one round (25 pts) left and no sprints.
mockFetchHub.mockResolvedValue({ ...hub, round: 9, rounds_left: 1, sprints_left: 0, max_points_left: 25 })
renderPage()
await waitFor(() => expect(screen.getByTestId('championship')).toBeInTheDocument())
const titleMath = screen.getByTestId('champ-titlemath')
expect(titleMath).toHaveTextContent('Max Verstappen has clinched the 2025 Drivers\' Championship')
expect(titleMath).not.toHaveTextContent('can still mathematically win')
expect(screen.getByText('CHAMPION')).toBeInTheDocument()
expect(screen.queryByText('ALIVE')).not.toBeInTheDocument()
})
it('keeps the title open while sprint points can still close the gap', async () => {
// 40-pt gap vs two rounds + a sprint (58 pts max): still open.
mockFetchHub.mockResolvedValue({ ...hub, round: 8, rounds_left: 2, sprints_left: 1, max_points_left: 58 })
renderPage()
await waitFor(() => expect(screen.getByTestId('championship')).toBeInTheDocument())
expect(screen.getByTestId('champ-titlemath')).toHaveTextContent('2 rounds + 1 sprint left (max 58 pts)')
expect(screen.queryByText('CHAMPION')).not.toBeInTheDocument()
})
it('switches to constructors and progression views', async () => { it('switches to constructors and progression views', async () => {
renderPage() renderPage()
@@ -223,6 +223,8 @@ describe('RacePreviewPage', () => {
expect(screen.getByTestId('preview-header')).toHaveTextContent('Monaco') expect(screen.getByTestId('preview-header')).toHaveTextContent('Monaco')
expect(screen.getByTestId('preview-schedule')).toHaveTextContent('FP1') expect(screen.getByTestId('preview-schedule')).toHaveTextContent('FP1')
expect(screen.getByTestId('preview-track-card')).toBeInTheDocument() expect(screen.getByTestId('preview-track-card')).toBeInTheDocument()
expect(screen.getByRole('img', { name: 'Circuit outline' })).toBeInTheDocument()
expect(screen.queryByTestId('preview-track-fallback')).not.toBeInTheDocument()
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('preview-last-year-card')).toHaveTextContent('VER') expect(screen.getByTestId('preview-last-year-card')).toHaveTextContent('VER')
@@ -273,5 +275,75 @@ describe('RacePreviewPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('preview-last-year-card')).toHaveTextContent('First time on the calendar') expect(screen.getByTestId('preview-last-year-card')).toHaveTextContent('First time on the calendar')
}) })
const fallback = screen.getByTestId('preview-track-fallback')
expect(screen.getByTestId('preview-track-card')).toContainElement(fallback)
expect(fallback).toHaveTextContent('Monaco')
expect(fallback).toHaveTextContent('A GPS track outline is not available in the local cache.')
expect(screen.queryByRole('img', { name: 'Circuit outline' })).not.toBeInTheDocument()
})
it('shows a designed circuit fallback when the track outline is unavailable', async () => {
const italianGp: Meeting = {
...upcomingMeeting,
meeting_name: 'Italian Grand Prix',
meeting_official_name: 'Formula 1 Pirelli Gran Premio d\'Italia',
location: 'Monza',
country_name: 'Italy',
country_code: 'ITA',
circuit_short_name: 'Monza',
}
mockFetchMeetings.mockImplementation(async (year: number) => {
if (year === 2099) return [italianGp]
if (year === 2098) return [{ ...italianGp, meeting_key: 90, year: 2098 }]
return []
})
mockFetchSessions.mockImplementation(async (meetingKey: number) => {
if (meetingKey === 100) return sessions
if (meetingKey === 90) return [priorRaceSession]
return []
})
mockFetchTrackOutline.mockResolvedValue(null)
renderPage()
await waitFor(() => {
expect(screen.getByTestId('preview-track-fallback')).toBeInTheDocument()
})
const card = screen.getByTestId('preview-track-card')
const fallback = screen.getByTestId('preview-track-fallback')
expect(card).toContainElement(fallback)
expect(card).toHaveTextContent('Circuit')
expect(fallback).toHaveTextContent('Monza')
expect(fallback).toHaveTextContent('Italy')
expect(fallback).toHaveTextContent('A GPS track outline is not available in the local cache.')
expect(fallback).not.toHaveTextContent(/unknown/i)
expect(screen.queryByRole('img', { name: 'Circuit outline' })).not.toBeInTheDocument()
expect(card).not.toHaveTextContent('Track outline unavailable for this circuit')
})
it('keeps a thrown outline request distinct from the designed unavailable state', async () => {
mockFetchMeetings.mockImplementation(async (year: number) => {
if (year === 2099) return [upcomingMeeting]
if (year === 2098) return [priorMeeting]
return []
})
mockFetchSessions.mockImplementation(async (meetingKey: number) => {
if (meetingKey === 100) return sessions
if (meetingKey === 90) return [priorRaceSession]
return []
})
mockFetchTrackOutline.mockRejectedValue(new Error('outline request failed'))
renderPage()
await waitFor(() => {
expect(screen.getByTestId('preview-track-card')).toHaveTextContent('outline request failed')
})
expect(screen.queryByTestId('preview-track-fallback')).not.toBeInTheDocument()
expect(screen.queryByRole('img', { name: 'Circuit outline' })).not.toBeInTheDocument()
}) })
}) })
-41
View File
@@ -1,41 +0,0 @@
import { describe, expect, it } from 'vitest'
import { decidedChampion, maxPointsLeft } from '../lib/titleMath'
import type { ChampHubDriver } from '../types'
const d = (driver_number: number, points: number, round_positions: number[] = []) =>
({ driver_number, points, round_positions }) as ChampHubDriver
describe('maxPointsLeft', () => {
it('prefers the server ceiling', () => {
expect(maxPointsLeft({ rounds_left: 4, sprints_left: 1, max_points_left: 100 })).toBe(100)
})
it('falls back to races plus sprints for older responses', () => {
expect(maxPointsLeft({ rounds_left: 4 })).toBe(100)
expect(maxPointsLeft({ rounds_left: 4, sprints_left: 2 })).toBe(116)
})
})
describe('decidedChampion', () => {
it('clinches when P2 cannot catch the leader', () => {
// 2026 after Mexico City: ANT 380, VER 261, 4 rounds / no sprints left.
expect(decidedChampion([d(12, 380), d(1, 261)], 100)?.driver_number).toBe(12)
})
it('stays open when the gap is reachable', () => {
expect(decidedChampion([d(12, 380), d(1, 261)], 150)).toBeNull()
// P2 is out of reach but P3 is not.
expect(decidedChampion([d(12, 380), d(1, 261), d(44, 300)], 100)).toBeNull()
})
it('clinches on an exact gap when the leader wins the worst-case countback', () => {
// 25-pt lead, one race left. Even if the rival wins it (3 wins) the leader has 5.
expect(decidedChampion([d(12, 125, [1, 1, 1, 1, 1]), d(1, 100, [1, 1, 2, 2, 2])], 25, 1)?.driver_number).toBe(12)
})
it('stays open on an exact gap when the rival could win the countback', () => {
// Rival would reach 3 wins vs the leader's 2.
expect(decidedChampion([d(12, 125, [1, 1, 2, 2, 2]), d(1, 100, [1, 1, 3, 3, 3])], 25, 1)).toBeNull()
// Level on wins and every other place: still open.
expect(decidedChampion([d(12, 125, [1, 1, 2]), d(1, 100, [1, 2])], 25, 1)).toBeNull()
})
it('crowns the leader once nothing is left', () => {
expect(decidedChampion([d(12, 400), d(1, 400)], 0)?.driver_number).toBe(12)
})
})
-4
View File
@@ -444,10 +444,6 @@ export interface ChampionshipHub {
round: number round: number
total_rounds: number total_rounds: number
rounds_left: number rounds_left: number
/** Sprint sessions still to run (absent on older servers). */
sprints_left?: number
/** Most points one driver can still score, races + sprints (absent on older servers). */
max_points_left?: number
last_race: string last_race: string
round_labels: string[] round_labels: string[]
drivers: ChampHubDriver[] drivers: ChampHubDriver[]
+2 -56
View File
@@ -15,11 +15,6 @@ type ChampionshipRace struct {
RaceSessionKey int RaceSessionKey int
Results []models.SessionResult Results []models.SessionResult
Grid []models.StartingGrid Grid []models.StartingGrid
// HasSprint reports whether the meeting has a (non-cancelled) Sprint
// session; SprintDone whether that sprint already has results. Together
// they let the hub count the sprint points still available.
HasSprint bool
SprintDone bool
} }
// ChampionshipInputs are local-first inputs for the championship hub aggregation. // ChampionshipInputs are local-first inputs for the championship hub aggregation.
@@ -54,19 +49,11 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
} }
pointsByDriver := map[int]float64{} pointsByDriver := map[int]float64{}
// Grand Prix finishing-position counts per driver, for countback.
finishesByDriver := map[int]map[int]int{}
pointsByTeam := map[string]float64{} pointsByTeam := map[string]float64{}
latestSessionKey := 0 latestSessionKey := 0
latestMeetingKey := 0 latestMeetingKey := 0
for _, meeting := range meetings { for _, meeting := range meetings {
// Cancelled meetings (e.g. 2026 Bahrain/Saudi) are not championship
// rounds: counting them inflates total/remaining rounds and the
// title-math "max points left" bound.
if meeting.IsCancelled {
continue
}
sessions, err := s.ListSessionsByMeeting(int(meeting.MeetingKey)) sessions, err := s.ListSessionsByMeeting(int(meeting.MeetingKey))
if err != nil { if err != nil {
return ChampionshipInputs{}, err return ChampionshipInputs{}, err
@@ -75,9 +62,6 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
raceKey := 0 raceKey := 0
sprintKey := 0 sprintKey := 0
for _, sess := range sessions { for _, sess := range sessions {
if sess.IsCancelled {
continue
}
if strings.EqualFold(sess.SessionName, "Race") { if strings.EqualFold(sess.SessionName, "Race") {
raceKey = sess.SessionKey raceKey = sess.SessionKey
} else if strings.EqualFold(sess.SessionName, "Sprint") { } else if strings.EqualFold(sess.SessionName, "Sprint") {
@@ -114,14 +98,6 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
for _, entry := range grid { for _, entry := range grid {
race.Grid = append(race.Grid, gridToModel(entry)) race.Grid = append(race.Grid, gridToModel(entry))
} }
if sprintKey != 0 {
race.HasSprint = true
sprintResults, err := s.store.ListSessionResults(sprintKey)
if err != nil {
return ChampionshipInputs{}, err
}
race.SprintDone = len(sprintResults) > 0
}
inputs.Races = append(inputs.Races, race) inputs.Races = append(inputs.Races, race)
raceResults = race.Results raceResults = race.Results
@@ -137,12 +113,6 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
} }
for _, result := range results { for _, result := range results {
pointsByDriver[result.DriverNumber] += result.Points pointsByDriver[result.DriverNumber] += result.Points
if result.Position > 0 {
if finishesByDriver[result.DriverNumber] == nil {
finishesByDriver[result.DriverNumber] = map[int]int{}
}
finishesByDriver[result.DriverNumber][result.Position]++
}
team := inputs.DriverMap[result.DriverNumber].TeamName team := inputs.DriverMap[result.DriverNumber].TeamName
if team != "" { if team != "" {
pointsByTeam[team] += result.Points pointsByTeam[team] += result.Points
@@ -187,7 +157,7 @@ func (s *Service) GetChampionshipInputs(year int) (ChampionshipInputs, error) {
_ = raceGrid _ = raceGrid
} }
inputs.Champ = derivedDriverStandings(pointsByDriver, finishesByDriver, latestMeetingKey, latestSessionKey) inputs.Champ = derivedDriverStandings(pointsByDriver, latestMeetingKey, latestSessionKey)
inputs.Teams = derivedTeamStandings(pointsByTeam, latestMeetingKey, latestSessionKey) inputs.Teams = derivedTeamStandings(pointsByTeam, latestMeetingKey, latestSessionKey)
return inputs, nil return inputs, nil
} }
@@ -212,10 +182,7 @@ func (s *Service) driversForSession(sessionKey int) ([]models.Driver, error) {
return drivers, nil return drivers, nil
} }
// derivedDriverStandings orders drivers by points, breaking ties with the func derivedDriverStandings(points map[int]float64, meetingKey, sessionKey int) []models.ChampionshipDriver {
// FIA countback (most Grand Prix wins, then most P2s, and so on), then by
// driver number for a stable order when countback cannot separate them.
func derivedDriverStandings(points map[int]float64, finishes map[int]map[int]int, meetingKey, sessionKey int) []models.ChampionshipDriver {
drivers := make([]models.ChampionshipDriver, 0, len(points)) drivers := make([]models.ChampionshipDriver, 0, len(points))
for num, pts := range points { for num, pts := range points {
drivers = append(drivers, models.ChampionshipDriver{ drivers = append(drivers, models.ChampionshipDriver{
@@ -227,9 +194,6 @@ func derivedDriverStandings(points map[int]float64, finishes map[int]map[int]int
} }
sort.Slice(drivers, func(i, j int) bool { sort.Slice(drivers, func(i, j int) bool {
if drivers[i].PointsCurrent == drivers[j].PointsCurrent { if drivers[i].PointsCurrent == drivers[j].PointsCurrent {
if c := countbackCompare(finishes[drivers[i].DriverNumber], finishes[drivers[j].DriverNumber]); c != 0 {
return c > 0
}
return drivers[i].DriverNumber < drivers[j].DriverNumber return drivers[i].DriverNumber < drivers[j].DriverNumber
} }
return drivers[i].PointsCurrent > drivers[j].PointsCurrent return drivers[i].PointsCurrent > drivers[j].PointsCurrent
@@ -240,24 +204,6 @@ func derivedDriverStandings(points map[int]float64, finishes map[int]map[int]int
return drivers return drivers
} }
// countbackCompare returns >0 if a beats b on countback, <0 if b beats a and
// 0 if their finishing records are identical.
func countbackCompare(a, b map[int]int) int {
maxPos := 0
for p := range a {
maxPos = max(maxPos, p)
}
for p := range b {
maxPos = max(maxPos, p)
}
for p := 1; p <= maxPos; p++ {
if a[p] != b[p] {
return a[p] - b[p]
}
}
return 0
}
func derivedTeamStandings(points map[string]float64, meetingKey, sessionKey int) []models.ChampionshipTeam { func derivedTeamStandings(points map[string]float64, meetingKey, sessionKey int) []models.ChampionshipTeam {
teams := make([]models.ChampionshipTeam, 0, len(points)) teams := make([]models.ChampionshipTeam, 0, len(points))
for name, pts := range points { for name, pts := range points {
-61
View File
@@ -428,64 +428,3 @@ func TestGetChampionshipInputsIncludesSprintPoints(t *testing.T) {
t.Fatalf("Teams = %+v, want Red Bull 33", inputs.Teams) t.Fatalf("Teams = %+v, want Red Bull 33", inputs.Teams)
} }
} }
func TestGetChampionshipInputsSkipsCancelledAndFlagsPendingSprint(t *testing.T) {
svc := openTestService(t)
seedRaceHubData(t, svc.store)
upsert := func(m store.Meeting, sessions ...store.Session) {
t.Helper()
if err := svc.store.UpsertMeeting(m); err != nil {
t.Fatalf("UpsertMeeting() error = %v", err)
}
for _, s := range sessions {
if err := svc.store.UpsertSession(s); err != nil {
t.Fatalf("UpsertSession() error = %v", err)
}
}
}
upsert(store.Meeting{MeetingKey: 1230, MeetingName: "Cancelled GP", Year: 2025, DateStart: "2025-06-01T00:00:00+00:00", IsCancelled: true},
store.Session{SessionKey: 9480, MeetingKey: 1230, SessionName: "Race", SessionType: "Race", DateStart: "2025-06-01T13:00:00+00:00", IsCancelled: true})
upsert(store.Meeting{MeetingKey: 1231, MeetingName: "Sprint GP", Year: 2025, DateStart: "2025-07-01T00:00:00+00:00"},
store.Session{SessionKey: 9490, MeetingKey: 1231, SessionName: "Sprint", SessionType: "Race", DateStart: "2025-07-02T13:00:00+00:00"},
store.Session{SessionKey: 9491, MeetingKey: 1231, SessionName: "Race", SessionType: "Race", DateStart: "2025-07-03T13:00:00+00:00"})
inputs, err := svc.GetChampionshipInputs(2025)
if err != nil {
t.Fatalf("GetChampionshipInputs() error = %v", err)
}
if len(inputs.Races) != 2 {
t.Fatalf("Races = %d, want 2 (cancelled meeting skipped)", len(inputs.Races))
}
for _, r := range inputs.Races {
if r.Meeting.IsCancelled {
t.Fatalf("cancelled meeting %q counted as a round", r.Meeting.MeetingName)
}
}
if sprint := inputs.Races[1]; !sprint.HasSprint || sprint.SprintDone {
t.Fatalf("sprint round = HasSprint %v SprintDone %v, want true/false", sprint.HasSprint, sprint.SprintDone)
}
}
func TestDerivedDriverStandingsBreaksTiesOnCountback(t *testing.T) {
// VER #1 and ANT #12 level on points; ANT has more wins, so ANT leads
// despite the higher driver number.
points := map[int]float64{1: 400, 12: 400, 44: 300}
finishes := map[int]map[int]int{
1: {1: 5, 2: 10},
12: {1: 6, 2: 2},
44: {1: 1},
}
got := derivedDriverStandings(points, finishes, 0, 0)
if got[0].DriverNumber != 12 || got[1].DriverNumber != 1 || got[2].DriverNumber != 44 {
t.Fatalf("order = %d,%d,%d, want 12,1,44", got[0].DriverNumber, got[1].DriverNumber, got[2].DriverNumber)
}
if got[0].PositionCurrent != 1 || got[1].PositionCurrent != 2 {
t.Fatalf("positions = %d,%d, want 1,2", got[0].PositionCurrent, got[1].PositionCurrent)
}
// Equal on wins: decided by P2 count.
got = derivedDriverStandings(map[int]float64{1: 50, 12: 50}, map[int]map[int]int{1: {1: 1, 2: 2}, 12: {1: 1, 2: 1}}, 0, 0)
if got[0].DriverNumber != 1 {
t.Fatalf("P2 countback leader = %d, want 1", got[0].DriverNumber)
}
}
+19 -67
View File
@@ -697,19 +697,14 @@ type champHubTeam struct {
} }
type champHubResponse struct { type champHubResponse struct {
Season int `json:"season"` Season int `json:"season"`
Round int `json:"round"` Round int `json:"round"`
TotalRounds int `json:"total_rounds"` TotalRounds int `json:"total_rounds"`
RoundsLeft int `json:"rounds_left"` RoundsLeft int `json:"rounds_left"`
// SprintsLeft counts sprint sessions still to run in the remaining rounds. LastRace string `json:"last_race"`
SprintsLeft int `json:"sprints_left"` RoundLabels []string `json:"round_labels"`
// MaxPointsLeft is the most points any one driver can still score Drivers []champHubDriver `json:"drivers"`
// (race wins plus sprint wins). It is the bound for title math. Teams []champHubTeam `json:"teams"`
MaxPointsLeft float64 `json:"max_points_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. // meetingRace bundles a GP meeting with its (already-fetched) race results and grid.
@@ -718,17 +713,8 @@ type meetingRace struct {
RaceSessionKey int RaceSessionKey int
Results []models.SessionResult Results []models.SessionResult
Grid []models.StartingGrid Grid []models.StartingGrid
HasSprint bool // meeting has a non-cancelled Sprint session
SprintDone bool // that sprint already has results
} }
// Maximum points one driver can score per race / sprint under the current
// (2025+) regulations — no fastest-lap point.
const (
maxRacePoints = 25
maxSprintPoints = 8
)
// champHubWorkers bounds the concurrent per-meeting fetches for the hub. // champHubWorkers bounds the concurrent per-meeting fetches for the hub.
const champHubWorkers = 5 const champHubWorkers = 5
@@ -894,8 +880,6 @@ func (s *Server) localChampionshipHub(year int) (champHubResponse, bool, error)
RaceSessionKey: race.RaceSessionKey, RaceSessionKey: race.RaceSessionKey,
Results: race.Results, Results: race.Results,
Grid: race.Grid, Grid: race.Grid,
HasSprint: race.HasSprint,
SprintDone: race.SprintDone,
}) })
} }
return aggregateChampionshipHub(year, races, inputs.Champ, inputs.Teams, inputs.DriverMap), true, nil return aggregateChampionshipHub(year, races, inputs.Champ, inputs.Teams, inputs.DriverMap), true, nil
@@ -959,14 +943,6 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
return nil, false, err return nil, false, err
} }
sort.Slice(meetings, func(i, j int) bool { return meetings[i].DateStart < meetings[j].DateStart }) sort.Slice(meetings, func(i, j int) bool { return meetings[i].DateStart < meetings[j].DateStart })
active := meetings[:0:0]
for _, m := range meetings {
// Cancelled meetings are not championship rounds.
if !m.IsCancelled {
active = append(active, m)
}
}
meetings = active
var failed atomic.Bool var failed atomic.Bool
races = fetchMeetingRaces(meetings, champHubWorkers, func(m models.Meeting) (meetingRace, bool) { races = fetchMeetingRaces(meetings, champHubWorkers, func(m models.Meeting) (meetingRace, bool) {
@@ -976,15 +952,10 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
return meetingRace{}, false return meetingRace{}, false
} }
raceKey := 0 raceKey := 0
sprintKey := 0
for _, sess := range sessions { for _, sess := range sessions {
if sess.IsCancelled { if strings.EqualFold(sess.SessionName, "Race") {
continue
}
if strings.EqualFold(sess.SessionName, "Race") && raceKey == 0 {
raceKey = sess.SessionKey raceKey = sess.SessionKey
} else if strings.EqualFold(sess.SessionName, "Sprint") && sprintKey == 0 { break
sprintKey = sess.SessionKey
} }
} }
if raceKey == 0 { if raceKey == 0 {
@@ -1002,19 +973,7 @@ func fetchSeasonRaces(client *api.OpenF1Client, year int) (races []meetingRace,
if rerr != nil || gerr != nil { if rerr != nil || gerr != nil {
failed.Store(true) failed.Store(true)
} }
mr := meetingRace{Meeting: m, RaceSessionKey: raceKey, Results: results, Grid: grid} return meetingRace{Meeting: m, RaceSessionKey: raceKey, Results: results, Grid: grid}, true
if sprintKey != 0 {
mr.HasSprint = true
if len(results) > 0 {
// The sprint always runs before the race.
mr.SprintDone = true
} else if sprint, serr := client.GetSessionResult(sprintKey); serr == nil {
mr.SprintDone = len(sprint) > 0
}
// On error leave SprintDone false: overstating the points still
// available keeps title math conservative (never a false clinch).
}
return mr, true
}) })
return races, failed.Load(), nil return races, failed.Load(), nil
} }
@@ -1068,15 +1027,11 @@ func aggregateChampionshipHub(
} }
completed := 0 completed := 0
sprintsLeft := 0
lastRace := "" lastRace := ""
roundPoints := []map[int]float64{} // per completed round: driver -> race points roundPoints := []map[int]float64{} // per completed round: driver -> race points
for _, mr := range races { for _, mr := range races {
if len(mr.Results) == 0 { if len(mr.Results) == 0 {
if mr.HasSprint && !mr.SprintDone {
sprintsLeft++
}
continue // round not completed yet continue // round not completed yet
} }
completed++ completed++
@@ -1222,18 +1177,15 @@ func aggregateChampionshipHub(
} }
totalRounds := len(races) totalRounds := len(races)
roundsLeft := totalRounds - completed
return champHubResponse{ return champHubResponse{
Season: year, Season: year,
Round: completed, Round: completed,
TotalRounds: totalRounds, TotalRounds: totalRounds,
RoundsLeft: roundsLeft, RoundsLeft: totalRounds - completed,
SprintsLeft: sprintsLeft, LastRace: lastRace,
MaxPointsLeft: float64(maxRacePoints*roundsLeft + maxSprintPoints*sprintsLeft), RoundLabels: roundLabels,
LastRace: lastRace, Drivers: drivers,
RoundLabels: roundLabels, Teams: teamsOut,
Drivers: drivers,
Teams: teamsOut,
} }
} }
-72
View File
@@ -406,75 +406,3 @@ func TestChampHubCache(t *testing.T) {
t.Error("incomplete entry should expire after champHubIncompleteTTL") t.Error("incomplete entry should expire after champHubIncompleteTTL")
} }
} }
func TestFetchSeasonRacesSkipsCancelledMeetings(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/meetings":
_, _ = w.Write([]byte(`[{"meeting_key":1,"meeting_name":"Run GP","date_start":"2026-03-01"},{"meeting_key":2,"meeting_name":"Cancelled GP","date_start":"2026-04-01","is_cancelled":true},{"meeting_key":3,"meeting_name":"Sprint GP","date_start":"2026-05-01"}]`))
case "/v1/sessions":
switch r.URL.Query().Get("meeting_key") {
case "2":
_, _ = w.Write([]byte(`[{"session_key":20,"meeting_key":2,"session_name":"Race","is_cancelled":true}]`))
case "3":
_, _ = w.Write([]byte(`[{"session_key":30,"meeting_key":3,"session_name":"Sprint"},{"session_key":31,"meeting_key":3,"session_name":"Race"}]`))
default:
_, _ = w.Write([]byte(`[{"session_key":10,"meeting_key":1,"session_name":"Race"}]`))
}
case "/v1/session_result":
if r.URL.Query().Get("session_key") == "10" {
_, _ = w.Write([]byte(`[{"driver_number":1,"position":1,"points":25}]`))
return
}
_, _ = w.Write([]byte(`[]`))
case "/v1/starting_grid":
_, _ = w.Write([]byte(`[]`))
default:
http.NotFound(w, r)
}
}))
defer upstream.Close()
client := api.NewOpenF1Client(upstream.URL, 2*time.Second)
defer client.Close()
races, _, err := fetchSeasonRaces(client.Scoped(), 2026)
if err != nil {
t.Fatal(err)
}
if len(races) != 2 {
t.Fatalf("races = %d, want 2 (cancelled meeting must be skipped)", len(races))
}
for _, mr := range races {
if mr.Meeting.MeetingName == "Cancelled GP" {
t.Fatal("cancelled meeting was counted as a round")
}
}
if !races[1].HasSprint || races[1].SprintDone {
t.Fatalf("sprint meeting = HasSprint %v SprintDone %v, want true/false", races[1].HasSprint, races[1].SprintDone)
}
}
func TestAggregateChampionshipHubMaxPointsLeftIncludesSprints(t *testing.T) {
champ := []models.ChampionshipDriver{
{DriverNumber: 12, PointsCurrent: 380, PositionCurrent: 1},
{DriverNumber: 1, PointsCurrent: 261, PositionCurrent: 2},
}
done := []models.SessionResult{raceResult(12, 1, 25), raceResult(1, 2, 18)}
races := []meetingRace{
{Meeting: models.Meeting{MeetingName: "Done GP"}, Results: done, HasSprint: true, SprintDone: true},
{Meeting: models.Meeting{MeetingName: "Sprint Done Race Pending GP"}, HasSprint: true, SprintDone: true},
{Meeting: models.Meeting{MeetingName: "Sprint GP"}, HasSprint: true},
{Meeting: models.Meeting{MeetingName: "Plain GP"}},
}
resp := aggregateChampionshipHub(2026, races, champ, nil, map[int]models.Driver{})
if resp.TotalRounds != 4 || resp.RoundsLeft != 3 {
t.Fatalf("rounds = %d/%d left, want 4 total / 3 left", resp.TotalRounds, resp.RoundsLeft)
}
if resp.SprintsLeft != 1 {
t.Errorf("sprints left = %d, want 1", resp.SprintsLeft)
}
if resp.MaxPointsLeft != 3*25+8 {
t.Errorf("max points left = %v, want %d", resp.MaxPointsLeft, 3*25+8)
}
}