mirror of
https://github.com/AmanTahiliani/box-box.git
synced 2026-08-08 04:06:18 -04:00
Compare commits
4 Commits
feat/issue
...
feat/issue
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
643af2355a | ||
|
|
45084558cd | ||
|
|
90c24ad6aa | ||
|
|
e028e3e3fe |
@@ -25,7 +25,8 @@ EOF
|
||||
|
||||
harness_claude() { # Claude Code — print mode, auto-accept edits
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && claude -p "$(cat "$prompt")" --permission-mode acceptEdits )
|
||||
local model="${BOXBOX_CLAUDE_MODEL:-opus}"
|
||||
( cd "$dir" && claude -p "$(cat "$prompt")" --model "$model" --effort high --permission-mode acceptEdits )
|
||||
}
|
||||
|
||||
harness_codex() { # OpenAI Codex CLI — non-interactive exec, full auto
|
||||
@@ -40,7 +41,8 @@ harness_opencode() { # opencode — non-interactive run
|
||||
|
||||
harness_cursor() { # Cursor CLI agent — composer-2.5, headless full-auto
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && cursor-agent -p "$(cat "$prompt")" --model composer-2.5 --force --trust )
|
||||
local model="${BOXBOX_CURSOR_MODEL:-composer-2.5}"
|
||||
( cd "$dir" && cursor-agent -p "$(cat "$prompt")" --model "$model" --force --trust )
|
||||
}
|
||||
|
||||
harness_agy() { # Antigravity CLI — disabled until headless is verified
|
||||
|
||||
32
docs/product/v0.4.0/README.md
Normal file
32
docs/product/v0.4.0/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# v0.4.0 — Current Weekend & Product Truth
|
||||
|
||||
Product research references for the v0.4.0 feature sprint.
|
||||
|
||||
## Direction
|
||||
|
||||
The sprint replaces route-first navigation with a state-aware Weekend experience:
|
||||
|
||||
- Weekend is the adaptive home for what happened, what is live, and what is next.
|
||||
- Preview content folds into Weekend before a session.
|
||||
- Live remains a stable deep link and becomes Weekend's active-session state.
|
||||
- Race Hub remains explicit completed-session analysis rather than a primary landing destination.
|
||||
- Championship and Briefing remain dedicated destinations.
|
||||
- Explore owns secondary discovery; Admin moves to operator utility.
|
||||
|
||||
## Mockups
|
||||
|
||||
- `mockups/weekend-between-races.png` — desktop between-races/post-weekend state.
|
||||
- `mockups/weekend-live.png` — desktop active-session state; the circuit is static sector context, not live GPS.
|
||||
- `mockups/weekend-between-sessions-mobile.png` — 390×844 between-session state.
|
||||
|
||||
These are directional references, not pixel-perfect specifications. Implementations must preserve the established box-box visual language, accessibility, data constraints, and responsive behavior while satisfying their issue acceptance criteria.
|
||||
|
||||
## Constraints
|
||||
|
||||
- No OpenF1 REST dependency during active sessions.
|
||||
- Public live GPS is not assumed to be available.
|
||||
- Championship round numbers exclude tests and cancelled meetings.
|
||||
- Connection health, live-session state, archive availability, and local-analysis readiness are separate concepts.
|
||||
- Future sessions must not render empty post-session analysis.
|
||||
|
||||
The authoritative product decisions and research packet are recorded in GitHub issue #71 under epic #70.
|
||||
BIN
docs/product/v0.4.0/mockups/weekend-between-races.png
Normal file
BIN
docs/product/v0.4.0/mockups/weekend-between-races.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
BIN
docs/product/v0.4.0/mockups/weekend-between-sessions-mobile.png
Normal file
BIN
docs/product/v0.4.0/mockups/weekend-between-sessions-mobile.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 366 KiB |
BIN
docs/product/v0.4.0/mockups/weekend-live.png
Normal file
BIN
docs/product/v0.4.0/mockups/weekend-live.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
@@ -1,17 +1,6 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { fetchLiveState } from '../api'
|
||||
import { isLiveSessionActive } from '../lib/live'
|
||||
|
||||
export function Nav() {
|
||||
const { data: liveState } = useQuery({
|
||||
queryKey: ['live-state'],
|
||||
queryFn: fetchLiveState,
|
||||
staleTime: 5_000,
|
||||
refetchInterval: 30_000,
|
||||
})
|
||||
const liveActive = isLiveSessionActive(liveState)
|
||||
|
||||
return (
|
||||
<nav className="app-nav">
|
||||
<Link to="/" className="nav-logo">
|
||||
@@ -21,16 +10,8 @@ export function Nav() {
|
||||
<Link to="/" activeProps={{ className: 'active' }} activeOptions={{ exact: true }}>
|
||||
Command
|
||||
</Link>
|
||||
<Link
|
||||
to="/live"
|
||||
className={liveActive ? 'nav-live nav-live-on' : 'nav-live'}
|
||||
activeProps={{ className: 'active' }}
|
||||
data-testid="nav-live"
|
||||
data-live-active={liveActive ? 'true' : 'false'}
|
||||
>
|
||||
{liveActive && <span className="nav-live-dot" aria-hidden="true" />}
|
||||
<Link to="/live" activeProps={{ className: 'active' }}>
|
||||
Live
|
||||
{liveActive && <span className="sr-only"> session active</span>}
|
||||
</Link>
|
||||
<Link to="/race-hub" search={{}} activeProps={{ className: 'active' }}>
|
||||
Race Hub
|
||||
|
||||
@@ -80,9 +80,7 @@ export function RaceControlFeed({ messages, driverInfo }: Props) {
|
||||
<section className="live-rc panel-glass">
|
||||
<div className="sec-header sticky-header">
|
||||
<span className="sec-title">Race Control</span>
|
||||
<span className="sec-meta" data-testid="rc-timezone">
|
||||
{messages.length > 0 ? `${messages.length} messages · ` : ''}times UTC
|
||||
</span>
|
||||
{messages.length > 0 && <span className="sec-meta">{messages.length} messages</span>}
|
||||
</div>
|
||||
{latest.length === 0 ? (
|
||||
<div className="missing-notice">No race control messages in the current live snapshot.</div>
|
||||
@@ -104,7 +102,7 @@ export function RaceControlFeed({ messages, driverInfo }: Props) {
|
||||
|
||||
return (
|
||||
<div className={`live-rc-row${flashClass}`} key={key}>
|
||||
<span className="rc-time" title="UTC">{message.Time || '--:--'}</span>
|
||||
<span className="rc-time">{message.Time || '--:--'}</span>
|
||||
{message.Lap > 0 && <span className="rc-lap">L{message.Lap}</span>}
|
||||
{message.Flag
|
||||
? <span className={`rc-flag ${rcFlagClass(message.Flag)}`}>{message.Flag}</span>
|
||||
|
||||
@@ -38,11 +38,9 @@ export function SessionBanner({ isLive, isArchive = false, snapshot, rows, conne
|
||||
<div className="live-banner-meta">
|
||||
{display.advanceCount && <span>{display.advanceCount} advance</span>}
|
||||
{atRiskLabel && <span>{atRiskLabel}</span>}
|
||||
{display.isRace && (
|
||||
<span data-testid="live-lap-counter">
|
||||
<span>
|
||||
L<strong>{snapshot.CurrentLap || '-'}</strong>/<strong>{snapshot.TotalLaps || '-'}</strong>
|
||||
</span>
|
||||
)}
|
||||
<span className={isLive ? 'live-state live-state-on' : 'live-state'}>{stateLabel}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useState, useMemo, Fragment } from 'react'
|
||||
import { useState, Fragment } from 'react'
|
||||
import { teamColor } from '../../utils'
|
||||
import { useAutoAnimate } from '@formkit/auto-animate/react'
|
||||
import type { LiveSessionMeta, LiveStintData } from '../../types'
|
||||
import type { LiveTimingRow } from '../../lib/live'
|
||||
import {
|
||||
bestLapGaps,
|
||||
driverCode,
|
||||
liveSessionDisplay,
|
||||
positionDelta,
|
||||
@@ -63,10 +62,6 @@ export function TimingTower({
|
||||
const isQuali = sessionDisplay.isQualifying || !isRace
|
||||
const columnCount = 7 + (isRace ? 3 : 0) + (isQuali ? 3 : 0)
|
||||
|
||||
// Practice/qualifying: derive a display-only gap to P1 from valid best laps
|
||||
// when the upstream feed omits GapToLeader. Empty for races (feed is truth).
|
||||
const practiceGaps = useMemo(() => bestLapGaps(isRace ? [] : rows), [isRace, rows])
|
||||
|
||||
return (
|
||||
<div className="scroll-x">
|
||||
<table className="data-table live-tower" style={{ minWidth: 760 }}>
|
||||
@@ -76,7 +71,7 @@ export function TimingTower({
|
||||
{isRace && <th>Δ</th>}
|
||||
<th>Driver</th>
|
||||
<th>Tyre</th>
|
||||
<th className={isRace ? undefined : 'hide-mobile'}>Last Lap</th>
|
||||
<th>Last Lap</th>
|
||||
<th
|
||||
className="interactive"
|
||||
onClick={() => setGapMode(g => g === 'interval' ? 'leader' : 'interval')}
|
||||
@@ -86,10 +81,10 @@ export function TimingTower({
|
||||
{gapMode === 'interval' && isRace ? 'Interval' : 'Gap to P1'}
|
||||
</th>
|
||||
{isRace && <th>Trend</th>}
|
||||
{isQuali && <th className="hide-mobile">S1</th>}
|
||||
{isQuali && <th className="hide-mobile">S2</th>}
|
||||
{isQuali && <th className="hide-mobile">S3</th>}
|
||||
<th className={isRace ? 'hide-mobile' : undefined}>Best</th>
|
||||
{isQuali && <th>S1</th>}
|
||||
{isQuali && <th>S2</th>}
|
||||
{isQuali && <th>S3</th>}
|
||||
<th className="hide-mobile">Best</th>
|
||||
{isRace && <th className="hide-mobile r">Laps</th>}
|
||||
<th className="r"></th>
|
||||
</tr>
|
||||
@@ -107,15 +102,7 @@ export function TimingTower({
|
||||
driver.Cutoff
|
||||
const showCutoffAfter = row.Position === sessionDisplay.cutoffPosition
|
||||
|
||||
let gapText: string
|
||||
if (isRace) {
|
||||
gapText = gapMode === 'interval' ? (driver.Interval || driver.GapToLeader) : driver.GapToLeader
|
||||
} else if (driver.GapToLeader) {
|
||||
gapText = driver.GapToLeader
|
||||
} else {
|
||||
const computed = practiceGaps[row.RacingNumber]
|
||||
gapText = computed ? (computed.isLeader ? '—' : computed.gap) : ''
|
||||
}
|
||||
const gapText = gapMode === 'interval' && isRace ? (driver.Interval || driver.GapToLeader) : driver.GapToLeader
|
||||
const intervalAnnotation =
|
||||
gapMode === 'interval' && isRace && row.Position > 1
|
||||
? intervalMeaning(parseIntervalSeconds(gapText))
|
||||
@@ -166,10 +153,7 @@ export function TimingTower({
|
||||
<td>
|
||||
<span className={`tyre-badge ${tyreClass(row.Tyre)}`}>{tyreLabel(row.Tyre)}</span>
|
||||
</td>
|
||||
<td className={[
|
||||
isRace ? '' : 'hide-mobile',
|
||||
driver.LastLapOB ? 'mono lap-ob' : driver.LastLapPB ? 'mono lap-pb' : 'mono',
|
||||
].filter(Boolean).join(' ')}>
|
||||
<td className={driver.LastLapOB ? 'mono lap-ob' : driver.LastLapPB ? 'mono lap-pb' : 'mono'}>
|
||||
{driver.LastLapTime || '-'}
|
||||
</td>
|
||||
<td className="mono">
|
||||
@@ -187,14 +171,11 @@ export function TimingTower({
|
||||
</td>
|
||||
)}
|
||||
|
||||
{isQuali && <td className="hide-mobile">{renderSector(0)}</td>}
|
||||
{isQuali && <td className="hide-mobile">{renderSector(1)}</td>}
|
||||
{isQuali && <td className="hide-mobile">{renderSector(2)}</td>}
|
||||
{isQuali && <td>{renderSector(0)}</td>}
|
||||
{isQuali && <td>{renderSector(1)}</td>}
|
||||
{isQuali && <td>{renderSector(2)}</td>}
|
||||
|
||||
<td className={[
|
||||
isRace ? 'hide-mobile' : '',
|
||||
driver.BestLapOB ? 'mono lap-ob' : 'mono',
|
||||
].filter(Boolean).join(' ')}>
|
||||
<td className={`hide-mobile ${driver.BestLapOB ? 'mono lap-ob' : 'mono'}`}>
|
||||
{driver.BestLapTime || '-'}
|
||||
</td>
|
||||
|
||||
@@ -227,16 +208,6 @@ export function TimingTower({
|
||||
<div className="mono">{driver.NumberOfLaps || 0}</div>
|
||||
</div>
|
||||
)}
|
||||
{!isRace && driver.Sectors?.some((sec) => sec?.Value) && (
|
||||
<div data-testid="expanded-sectors">
|
||||
<div className="mono" style={{ color: 'var(--text-3)', fontSize: '10px', marginBottom: '4px' }}>SECTORS</div>
|
||||
<div className="mono" style={{ display: 'flex', gap: '10px' }}>
|
||||
{renderSector(0)}
|
||||
{renderSector(1)}
|
||||
{renderSector(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{driver.SpeedTrap && (
|
||||
<div>
|
||||
<div className="mono" style={{ color: 'var(--text-3)', fontSize: '10px', marginBottom: '4px' }}>SPEED TRAP</div>
|
||||
|
||||
@@ -52,10 +52,7 @@ function StintSparkline({ seconds }: { seconds: number[] }) {
|
||||
}
|
||||
|
||||
export function TyreDegPanel({ rows, sessionType, pinned }: Props) {
|
||||
const isRace = isRaceSession(sessionType)
|
||||
// In practice/qualifying deg trends are secondary — collapse by default so
|
||||
// the Timing Tower stays above the fold. Races keep it open.
|
||||
const [collapsed, setCollapsed] = useState(!isRace)
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const [stints, setStints] = useState<StintHistoryMap>({})
|
||||
|
||||
// One lap-history update per received snapshot (rows is rebuilt per snapshot).
|
||||
@@ -64,6 +61,8 @@ export function TyreDegPanel({ rows, sessionType, pinned }: Props) {
|
||||
setStints((prev) => recordStintSamples(prev, rows.map(stintInputFromRow)))
|
||||
}, [rows])
|
||||
|
||||
const isRace = isRaceSession(sessionType)
|
||||
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
rows.filter(
|
||||
|
||||
@@ -268,63 +268,6 @@ export function driverCode(row: LiveTimingRow): string {
|
||||
return row.Info?.Tla || row.RacingNumber
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an F1 lap-time string ("1:45.944", "45.944") into total seconds.
|
||||
* Returns null for empty/invalid values so callers never invent a gap.
|
||||
*/
|
||||
export function parseLapTimeSeconds(value: string | null | undefined): number | null {
|
||||
if (!value) return null
|
||||
const match = value.trim().match(/^(?:(\d+):)?([0-5]?\d(?:\.\d+)?)$/)
|
||||
if (!match) return null
|
||||
const minutes = match[1] ? Number(match[1]) : 0
|
||||
const seconds = Number(match[2])
|
||||
if (!Number.isFinite(minutes) || !Number.isFinite(seconds)) return null
|
||||
return minutes * 60 + seconds
|
||||
}
|
||||
|
||||
export interface BestLapGap {
|
||||
isLeader: boolean
|
||||
gap: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Display-only gap-to-P1 for practice/qualifying, derived from each driver's
|
||||
* valid best lap. Only drivers with a parseable best lap get an entry, and the
|
||||
* fastest is flagged as the leader. Never fabricates a gap from a missing or
|
||||
* invalid lap — the upstream interval remains the source of truth for races.
|
||||
*/
|
||||
export function bestLapGaps(rows: ReadonlyArray<LiveTimingRow>): Record<string, BestLapGap> {
|
||||
let leaderNumber = ''
|
||||
let best = Infinity
|
||||
for (const row of rows) {
|
||||
const seconds = parseLapTimeSeconds(row.Driver.BestLapTime)
|
||||
if (seconds === null) continue
|
||||
if (seconds < best) {
|
||||
best = seconds
|
||||
leaderNumber = row.RacingNumber
|
||||
}
|
||||
}
|
||||
|
||||
const out: Record<string, BestLapGap> = {}
|
||||
if (!Number.isFinite(best)) return out
|
||||
for (const row of rows) {
|
||||
const seconds = parseLapTimeSeconds(row.Driver.BestLapTime)
|
||||
if (seconds === null) continue
|
||||
out[row.RacingNumber] =
|
||||
row.RacingNumber === leaderNumber
|
||||
? { isLeader: true, gap: '' }
|
||||
: { isLeader: false, gap: `+${(seconds - best).toFixed(3)}` }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** True when the live feed reports an in-progress session with timing data. */
|
||||
export function isLiveSessionActive(
|
||||
state: { is_live?: boolean; data?: unknown } | null | undefined,
|
||||
): boolean {
|
||||
return Boolean(state?.is_live && state.data)
|
||||
}
|
||||
|
||||
export function trackStatusLabel(status: string): string {
|
||||
return TRACK_STATUS_LABELS[status] || status || 'UNKNOWN'
|
||||
}
|
||||
|
||||
@@ -112,30 +112,6 @@ a { color: inherit; text-decoration: none; }
|
||||
.nav-links a:hover { color: var(--text); background: var(--surface-h); }
|
||||
.nav-links a.active { color: var(--text); background: var(--surface-2); }
|
||||
|
||||
/* Live nav gets a pulsing marker only while a session is on air. */
|
||||
.nav-live { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.nav-links a.nav-live-on { color: var(--text); font-weight: 600; }
|
||||
.nav-live-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--red);
|
||||
box-shadow: 0 0 0 0 rgba(225, 6, 0, 0.4);
|
||||
animation: pulse-live 1.6s infinite;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.nav-utility {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
|
||||
@@ -209,32 +209,6 @@ describe('TimingTower', () => {
|
||||
expect(screen.getByText('DRS range')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('derives a gap to P1 from best laps when the practice feed omits GapToLeader', () => {
|
||||
const practiceRows = [
|
||||
makeRow('1', 1, 'VER', { BestLapTime: '1:45.944', GapToLeader: '' }),
|
||||
makeRow('4', 2, 'NOR', { BestLapTime: '1:46.134', GapToLeader: '' }),
|
||||
makeRow('16', 3, 'LEC', { BestLapTime: '', GapToLeader: '' }),
|
||||
]
|
||||
render(
|
||||
<TimingTower
|
||||
rows={practiceRows}
|
||||
session={{
|
||||
MeetingName: 'Belgian Grand Prix',
|
||||
CircuitName: 'Spa',
|
||||
SessionType: 'Practice',
|
||||
SessionName: 'Practice 2',
|
||||
Path: '',
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
// Leader shows a clear leader marker, not a fabricated gap.
|
||||
expect(screen.getByText('VER').closest('tr')).toHaveTextContent('—')
|
||||
expect(screen.getByText('+0.190')).toBeInTheDocument()
|
||||
// A driver without a valid best lap gets no invented gap.
|
||||
const lecRow = screen.getByText('LEC').closest('tr')!
|
||||
expect(lecRow).not.toHaveTextContent('+')
|
||||
})
|
||||
|
||||
it('renders the SQ1 cutoff after P17 and marks rows below as at risk', () => {
|
||||
const sprintRows = Array.from({ length: 22 }, (_, index) =>
|
||||
makeRow(String(index + 1), index + 1, `D${index + 1}`),
|
||||
|
||||
@@ -153,29 +153,6 @@ describe('LiveTimingPage archive mode', () => {
|
||||
expect(screen.queryByRole('button', { name: /view last session/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the live session for a red-flag paused snapshot instead of the inactive empty state', async () => {
|
||||
renderPage({
|
||||
is_live: true,
|
||||
data: {
|
||||
...archivedSnapshot,
|
||||
SessionStatus: 'Inactive',
|
||||
TrackStatus: '2',
|
||||
Clock: '00:03:27',
|
||||
Session: {
|
||||
MeetingName: 'Belgian Grand Prix',
|
||||
CircuitName: 'Spa-Francorchamps',
|
||||
SessionType: 'Practice',
|
||||
SessionName: 'Practice 2',
|
||||
Path: '',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
expect(await screen.findByText('Timing Tower')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('live-empty')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('live-archive-strip')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('temporarily omits the track map while live GPS is unavailable', async () => {
|
||||
renderPage({
|
||||
is_live: true,
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { SessionBanner } from '../components/live/SessionBanner'
|
||||
import type { LiveStreamData } from '../types'
|
||||
|
||||
function makeSnapshot(sessionType: string, sessionName: string): LiveStreamData {
|
||||
return {
|
||||
Drivers: {},
|
||||
DriverInfo: {},
|
||||
Tyres: {},
|
||||
RCMessages: [],
|
||||
Weather: { AirTemp: 0, TrackTemp: 0, Humidity: 0, WindSpeed: 0, WindDir: 0, Rainfall: false },
|
||||
Session: {
|
||||
MeetingName: 'Belgian Grand Prix',
|
||||
CircuitName: 'Spa-Francorchamps',
|
||||
SessionType: sessionType,
|
||||
SessionName: sessionName,
|
||||
Path: '',
|
||||
},
|
||||
TeamRadio: [],
|
||||
TrackStatus: '1',
|
||||
CurrentLap: 0,
|
||||
TotalLaps: 0,
|
||||
Clock: '00:45:00',
|
||||
ClockRefTime: '',
|
||||
ClockExtrapolating: false,
|
||||
Stints: {},
|
||||
}
|
||||
}
|
||||
|
||||
describe('SessionBanner', () => {
|
||||
it('never renders a race lap counter for a practice session', () => {
|
||||
render(
|
||||
<SessionBanner
|
||||
isLive
|
||||
snapshot={makeSnapshot('Practice', 'Practice 2')}
|
||||
rows={[]}
|
||||
connection="connected"
|
||||
now={0}
|
||||
/>,
|
||||
)
|
||||
expect(screen.queryByTestId('live-lap-counter')).not.toBeInTheDocument()
|
||||
// Session identity and clock stay intact.
|
||||
expect(screen.getByText('Belgian Grand Prix')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('live-clock')).toHaveTextContent('00:45:00')
|
||||
})
|
||||
|
||||
it('shows the lap counter for a race session', () => {
|
||||
const snapshot = { ...makeSnapshot('Race', 'Race'), CurrentLap: 12, TotalLaps: 44 }
|
||||
render(
|
||||
<SessionBanner
|
||||
isLive
|
||||
snapshot={snapshot}
|
||||
rows={[]}
|
||||
connection="connected"
|
||||
now={0}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByTestId('live-lap-counter')).toHaveTextContent('L12/44')
|
||||
})
|
||||
})
|
||||
@@ -81,20 +81,14 @@ describe('TyreDegPanel', () => {
|
||||
expect(panel).toHaveTextContent('→ ~P2')
|
||||
})
|
||||
|
||||
it('collapses by default outside race sessions and hides the rejoin estimate when expanded', () => {
|
||||
it('hides the rejoin estimate outside race sessions and collapses on toggle', () => {
|
||||
render(<TyreDegPanel rows={snapshotRows(3, '1:30.000')} sessionType="Qualifying" pinned={[]} />)
|
||||
const panel = screen.getByTestId('tyredeg-panel')
|
||||
|
||||
// Practice/qualifying starts collapsed so the Timing Tower stays above the fold.
|
||||
expect(screen.queryAllByTestId('tyredeg-row')).toHaveLength(0)
|
||||
fireEvent.click(screen.getByRole('button', { name: /tyre deg/i }))
|
||||
expect(screen.getAllByTestId('tyredeg-row')).toHaveLength(2)
|
||||
expect(panel).not.toHaveTextContent('~P')
|
||||
})
|
||||
|
||||
it('starts expanded during a race', () => {
|
||||
render(<TyreDegPanel rows={snapshotRows(3, '1:30.000')} sessionType="Race" pinned={[]} />)
|
||||
expect(screen.getAllByTestId('tyredeg-row')).toHaveLength(2)
|
||||
fireEvent.click(screen.getByRole('button', { name: /tyre deg/i }))
|
||||
expect(screen.queryAllByTestId('tyredeg-row')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('limits rows to the top ten plus pinned drivers', () => {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
bestLapGaps,
|
||||
compoundClass,
|
||||
compoundLetter,
|
||||
extrapolateClock,
|
||||
isLiveSessionActive,
|
||||
latestRaceControl,
|
||||
liveSessionDisplay,
|
||||
loadPinnedDrivers,
|
||||
mergeVisibleSectors,
|
||||
parseLapTimeSeconds,
|
||||
positionDeltaClass,
|
||||
parseLiveStateEvent,
|
||||
rcFlagClass,
|
||||
@@ -282,43 +279,6 @@ describe('live qualifying display', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('practice/qualifying computed gaps', () => {
|
||||
it('parses lap-time strings into seconds and rejects invalid input', () => {
|
||||
expect(parseLapTimeSeconds('1:45.944')).toBeCloseTo(105.944, 3)
|
||||
expect(parseLapTimeSeconds('45.944')).toBeCloseTo(45.944, 3)
|
||||
expect(parseLapTimeSeconds('')).toBeNull()
|
||||
expect(parseLapTimeSeconds(undefined)).toBeNull()
|
||||
expect(parseLapTimeSeconds('-')).toBeNull()
|
||||
expect(parseLapTimeSeconds('nope')).toBeNull()
|
||||
})
|
||||
|
||||
it('derives a gap to P1 from valid best laps only, flagging the leader', () => {
|
||||
const gaps = bestLapGaps([
|
||||
timingRow('1', 1, { BestLapTime: '1:45.944' }),
|
||||
timingRow('4', 2, { BestLapTime: '1:46.134' }),
|
||||
timingRow('16', 3, { BestLapTime: '' }),
|
||||
])
|
||||
expect(gaps['1']).toEqual({ isLeader: true, gap: '' })
|
||||
expect(gaps['4']).toEqual({ isLeader: false, gap: '+0.190' })
|
||||
// No valid best lap → no fabricated gap.
|
||||
expect(gaps['16']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns no gaps when nobody has set a lap', () => {
|
||||
expect(bestLapGaps([timingRow('1', 1, { BestLapTime: '' })])).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('live session activity', () => {
|
||||
it('is active only when the feed reports a live session with data', () => {
|
||||
expect(isLiveSessionActive({ is_live: true, data: snapshot })).toBe(true)
|
||||
expect(isLiveSessionActive({ is_live: true, data: null })).toBe(false)
|
||||
expect(isLiveSessionActive({ is_live: false, data: snapshot })).toBe(false)
|
||||
expect(isLiveSessionActive(null)).toBe(false)
|
||||
expect(isLiveSessionActive(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('visible sector display', () => {
|
||||
it('holds S1 and S2 through temporary blanks while a flying lap is active', () => {
|
||||
const first = [timingRow('4', 1, {
|
||||
|
||||
@@ -307,28 +307,6 @@ func TestSessionStatusIsActive(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStatusIsTerminal(t *testing.T) {
|
||||
tests := []struct {
|
||||
status string
|
||||
want bool
|
||||
}{
|
||||
{"Finished", true},
|
||||
{"Finalised", true},
|
||||
{"Finalized", true},
|
||||
{"Ends", true},
|
||||
{"Aborted", true},
|
||||
{"Started", false},
|
||||
{"Resumed", false},
|
||||
{"Inactive", false},
|
||||
{"", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := live.SessionStatusIsTerminal(tt.status); got != tt.want {
|
||||
t.Errorf("SessionStatusIsTerminal(%q) = %v, want %v", tt.status, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessTopicRaceControlMessages(t *testing.T) {
|
||||
state := live.NewState()
|
||||
data := json.RawMessage(`{
|
||||
|
||||
@@ -186,19 +186,6 @@ func SessionStatusIsActive(status string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// SessionStatusIsTerminal reports whether a raw F1 live timing SessionStatus
|
||||
// value represents a session that has ended and will not resume. A temporarily
|
||||
// inactive session (e.g. a red-flag pause reported as "Inactive") is neither
|
||||
// active nor terminal.
|
||||
func SessionStatusIsTerminal(status string) bool {
|
||||
switch normalizeSessionStatus(status) {
|
||||
case "finished", "finalised", "finalized", "ends", "aborted":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeSessionStatus(status string) string {
|
||||
out := make([]rune, 0, len(status))
|
||||
for _, r := range status {
|
||||
|
||||
435
internal/query/context.go
Normal file
435
internal/query/context.go
Normal file
@@ -0,0 +1,435 @@
|
||||
package query
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/box-box/internal/models"
|
||||
"github.com/AmanTahiliani/box-box/internal/store"
|
||||
)
|
||||
|
||||
// TemporalState describes where the fan is in the current season/weekend.
|
||||
type TemporalState string
|
||||
|
||||
const (
|
||||
TemporalNoSeason TemporalState = "no_season"
|
||||
TemporalBetweenWeekends TemporalState = "between_weekends"
|
||||
TemporalPreSession TemporalState = "pre_session"
|
||||
TemporalSessionLive TemporalState = "session_live"
|
||||
TemporalSessionSettling TemporalState = "session_settling"
|
||||
TemporalBetweenSessions TemporalState = "between_sessions"
|
||||
TemporalPostWeekend TemporalState = "post_weekend"
|
||||
TemporalSeasonComplete TemporalState = "season_complete"
|
||||
|
||||
preSessionWindow = 48 * time.Hour
|
||||
postWeekendWindow = 48 * time.Hour
|
||||
)
|
||||
|
||||
// LiveEvidence is the small, transport-independent subset of FIA state needed
|
||||
// by the context resolver. Active identity is authoritative over the schedule.
|
||||
type LiveEvidence struct {
|
||||
Active bool
|
||||
Final bool
|
||||
MeetingName string
|
||||
CircuitName string
|
||||
SessionName string
|
||||
SessionType string
|
||||
ObservedAt time.Time
|
||||
}
|
||||
|
||||
// ContextAvailability is structured source state for a referenced session.
|
||||
type ContextAvailability struct {
|
||||
Schedule string `json:"schedule"`
|
||||
LiveTransport string `json:"live_transport"`
|
||||
LiveSession string `json:"live_session"`
|
||||
Archive string `json:"archive"`
|
||||
LocalAnalysis string `json:"local_analysis"`
|
||||
Freshness string `json:"freshness"`
|
||||
ObservedAt string `json:"observed_at,omitempty"`
|
||||
Limitations []string `json:"limitations"`
|
||||
}
|
||||
|
||||
// ContextSession couples a session identity with its availability contract.
|
||||
type ContextSession struct {
|
||||
Session models.Session `json:"session"`
|
||||
Meeting *models.Meeting `json:"meeting,omitempty"`
|
||||
Availability ContextAvailability `json:"availability"`
|
||||
}
|
||||
|
||||
// WeekendContext is the canonical local-first previous/current/next model.
|
||||
type WeekendContext struct {
|
||||
Season int `json:"season,omitempty"`
|
||||
TemporalState TemporalState `json:"temporal_state"`
|
||||
PreviousMeeting *models.Meeting `json:"previous_meeting,omitempty"`
|
||||
FocusMeeting *models.Meeting `json:"focus_meeting,omitempty"`
|
||||
NextMeeting *models.Meeting `json:"next_meeting,omitempty"`
|
||||
PreviousCompletedSession *ContextSession `json:"previous_completed_session,omitempty"`
|
||||
ActiveSession *ContextSession `json:"active_session,omitempty"`
|
||||
NextSession *ContextSession `json:"next_session,omitempty"`
|
||||
DefaultAnalysisSession *ContextSession `json:"default_analysis_session,omitempty"`
|
||||
ChampionshipRound int `json:"championship_round"`
|
||||
TotalChampionshipRounds int `json:"total_championship_rounds"`
|
||||
}
|
||||
|
||||
type contextCandidate struct {
|
||||
meeting store.Meeting
|
||||
session store.Session
|
||||
start time.Time
|
||||
end time.Time
|
||||
counts store.SessionDatasetCounts
|
||||
complete bool
|
||||
archived bool
|
||||
}
|
||||
|
||||
// ResolveWeekendContext computes the canonical context using only the domain
|
||||
// store, the service clock, and optional in-memory FIA evidence.
|
||||
func (s *Service) ResolveWeekendContext(evidence LiveEvidence) (WeekendContext, error) {
|
||||
now := s.now().UTC()
|
||||
out := WeekendContext{TemporalState: TemporalNoSeason}
|
||||
years, err := s.store.ListYears()
|
||||
if err != nil || len(years) == 0 {
|
||||
return out, err
|
||||
}
|
||||
out.Season = currentLocalSeason(years, now.Year())
|
||||
meetings, err := s.store.ListMeetingsByYear(out.Season)
|
||||
if err != nil {
|
||||
return WeekendContext{}, err
|
||||
}
|
||||
if len(meetings) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
byMeeting := make(map[int][]store.Session, len(meetings))
|
||||
var candidates []contextCandidate
|
||||
for i := range meetings {
|
||||
m := meetings[i]
|
||||
sessions, listErr := s.store.ListSessionsByMeeting(m.MeetingKey)
|
||||
if listErr != nil {
|
||||
return WeekendContext{}, listErr
|
||||
}
|
||||
byMeeting[m.MeetingKey] = sessions
|
||||
applySessionDisplayRange(&meetings[i], sessions)
|
||||
m = meetings[i]
|
||||
for _, sess := range sessions {
|
||||
if m.IsCancelled || sess.IsCancelled {
|
||||
continue
|
||||
}
|
||||
start, _ := parseContextTime(sess.DateStart)
|
||||
end, _ := parseContextTime(sess.DateEnd)
|
||||
if end.IsZero() && !start.IsZero() {
|
||||
end = start.Add(3 * time.Hour)
|
||||
}
|
||||
counts, countErr := s.store.CountSessionDatasets(sess.SessionKey)
|
||||
if countErr != nil {
|
||||
return WeekendContext{}, countErr
|
||||
}
|
||||
archived := evidence.Final && liveMatches(evidence, m, sess)
|
||||
candidates = append(candidates, contextCandidate{
|
||||
meeting: m, session: sess, start: start, end: end, counts: counts,
|
||||
complete: hasMeaningfulAnalysis(counts) || archived, archived: archived,
|
||||
})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].start.Before(candidates[j].start) })
|
||||
|
||||
champMeetings := championshipMeetings(meetings, byMeeting)
|
||||
out.TotalChampionshipRounds = len(champMeetings)
|
||||
|
||||
var active *contextCandidate
|
||||
if evidence.Active {
|
||||
for i := range candidates {
|
||||
if liveMatches(evidence, candidates[i].meeting, candidates[i].session) {
|
||||
active = &candidates[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if active == nil {
|
||||
active = syntheticLiveCandidate(evidence, now)
|
||||
}
|
||||
}
|
||||
|
||||
var previous, next, defaultAnalysis *contextCandidate
|
||||
for i := range candidates {
|
||||
c := &candidates[i]
|
||||
isActive := active != nil && active.session.SessionKey != 0 && c.session.SessionKey == active.session.SessionKey
|
||||
completionEligible := c.start.IsZero() || !c.start.After(now) || c.archived
|
||||
if !isActive && c.complete && completionEligible && (previous == nil || candidateTime(*c).After(candidateTime(*previous))) {
|
||||
previous = c
|
||||
}
|
||||
if !isActive && c.complete && hasMeaningfulAnalysis(c.counts) && (c.start.IsZero() || !c.start.After(now)) && (defaultAnalysis == nil || candidateTime(*c).After(candidateTime(*defaultAnalysis))) {
|
||||
defaultAnalysis = c
|
||||
}
|
||||
if !isActive && !c.start.IsZero() && !c.start.Before(now) && (next == nil || c.start.Before(next.start)) {
|
||||
next = c
|
||||
}
|
||||
}
|
||||
|
||||
if previous != nil {
|
||||
out.PreviousCompletedSession = sessionRef(*previous, evidence, now)
|
||||
out.PreviousMeeting = meetingModelByKey(meetings, previous.meeting.MeetingKey)
|
||||
}
|
||||
if defaultAnalysis != nil {
|
||||
out.DefaultAnalysisSession = sessionRef(*defaultAnalysis, evidence, now)
|
||||
}
|
||||
if next != nil {
|
||||
out.NextSession = sessionRef(*next, evidence, now)
|
||||
out.NextMeeting = meetingModelByKey(meetings, next.meeting.MeetingKey)
|
||||
}
|
||||
if active != nil {
|
||||
out.ActiveSession = sessionRef(*active, evidence, now)
|
||||
out.FocusMeeting = out.ActiveSession.Meeting
|
||||
out.TemporalState = TemporalSessionLive
|
||||
} else {
|
||||
out.FocusMeeting = chooseFocusMeeting(meetings, previous, next)
|
||||
out.TemporalState = classifyTemporalState(now, previous, next, candidates, champMeetings, championshipScheduleUnknown(champMeetings, byMeeting))
|
||||
}
|
||||
if out.FocusMeeting != nil {
|
||||
out.ChampionshipRound = championshipRound(champMeetings, int(out.FocusMeeting.MeetingKey))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func currentLocalSeason(years []int, current int) int {
|
||||
for _, year := range years {
|
||||
if year == current {
|
||||
return year
|
||||
}
|
||||
}
|
||||
for _, year := range years {
|
||||
if year < current {
|
||||
return year
|
||||
}
|
||||
}
|
||||
return years[len(years)-1]
|
||||
}
|
||||
|
||||
func parseContextTime(value string) (time.Time, bool) {
|
||||
if value == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
for _, layout := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05"} {
|
||||
if parsed, err := time.Parse(layout, value); err == nil {
|
||||
return parsed.UTC(), true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
func hasMeaningfulAnalysis(c store.SessionDatasetCounts) bool {
|
||||
return c.Results > 0 || c.Laps > 0 || c.Stints > 0 || c.Positions > 0 || c.RaceControl > 0
|
||||
}
|
||||
|
||||
func candidateTime(c contextCandidate) time.Time {
|
||||
if !c.end.IsZero() {
|
||||
return c.end
|
||||
}
|
||||
return c.start
|
||||
}
|
||||
|
||||
func liveMatches(e LiveEvidence, m store.Meeting, s store.Session) bool {
|
||||
meetingMatch := normalizedContains(e.MeetingName, m.MeetingName) || normalizedContains(e.CircuitName, m.CircuitShortName)
|
||||
sessionMatch := normalizedEqual(e.SessionName, s.SessionName)
|
||||
if normalizeIdentity(e.SessionName) == "" {
|
||||
sessionMatch = normalizedEqual(e.SessionType, s.SessionType)
|
||||
}
|
||||
return meetingMatch && sessionMatch
|
||||
}
|
||||
|
||||
func normalizedEqual(a, b string) bool {
|
||||
return normalizeIdentity(a) != "" && normalizeIdentity(a) == normalizeIdentity(b)
|
||||
}
|
||||
func normalizedContains(a, b string) bool {
|
||||
a, b = normalizeIdentity(a), normalizeIdentity(b)
|
||||
return a != "" && b != "" && (strings.Contains(a, b) || strings.Contains(b, a))
|
||||
}
|
||||
func normalizeIdentity(v string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if r >= 'A' && r <= 'Z' {
|
||||
return r + ('a' - 'A')
|
||||
}
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
|
||||
return r
|
||||
}
|
||||
return -1
|
||||
}, v)
|
||||
}
|
||||
|
||||
func syntheticLiveCandidate(e LiveEvidence, now time.Time) *contextCandidate {
|
||||
return &contextCandidate{meeting: store.Meeting{MeetingName: e.MeetingName, CircuitShortName: e.CircuitName}, session: store.Session{SessionName: e.SessionName, SessionType: e.SessionType, DateStart: now.Format(time.RFC3339)}, start: now}
|
||||
}
|
||||
|
||||
func applySessionDisplayRange(m *store.Meeting, sessions []store.Session) {
|
||||
var first, last time.Time
|
||||
for _, sess := range sessions {
|
||||
if sess.IsCancelled {
|
||||
continue
|
||||
}
|
||||
start, ok := parseContextTime(sess.DateStart)
|
||||
if ok && (first.IsZero() || start.Before(first)) {
|
||||
first = start
|
||||
}
|
||||
end, ok := parseContextTime(sess.DateEnd)
|
||||
if !ok {
|
||||
end = start
|
||||
}
|
||||
if !end.IsZero() && (last.IsZero() || end.After(last)) {
|
||||
last = end
|
||||
}
|
||||
}
|
||||
if !first.IsZero() {
|
||||
m.DateStart = first.Format(time.RFC3339)
|
||||
}
|
||||
if !last.IsZero() {
|
||||
m.DateEnd = last.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
|
||||
func meetingModelByKey(meetings []store.Meeting, key int) *models.Meeting {
|
||||
for _, meeting := range meetings {
|
||||
if meeting.MeetingKey == key {
|
||||
model := meetingToModel(meeting)
|
||||
return &model
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sessionRef(c contextCandidate, evidence LiveEvidence, now time.Time) *ContextSession {
|
||||
session := sessionToModel(c.session)
|
||||
meeting := meetingToModel(c.meeting)
|
||||
availability := ContextAvailability{Schedule: "available", LiveSession: "inactive", Archive: "unavailable", Freshness: "fresh", Limitations: []string{}}
|
||||
availability.LiveTransport = "unknown"
|
||||
if c.session.SessionKey == 0 {
|
||||
availability.Schedule = "unavailable"
|
||||
availability.Limitations = append(availability.Limitations, "schedule_identity_unmatched")
|
||||
}
|
||||
if evidence.Active && liveMatches(evidence, c.meeting, c.session) {
|
||||
availability.LiveTransport = "connected"
|
||||
availability.LiveSession = "active"
|
||||
if !evidence.ObservedAt.IsZero() {
|
||||
availability.ObservedAt = evidence.ObservedAt.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
if c.archived {
|
||||
availability.Archive = "available"
|
||||
if !evidence.ObservedAt.IsZero() {
|
||||
availability.ObservedAt = evidence.ObservedAt.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
if c.counts.Results > 0 && (c.counts.Laps+c.counts.Stints+c.counts.Positions+c.counts.RaceControl > 0) {
|
||||
availability.LocalAnalysis = "complete"
|
||||
} else if hasMeaningfulAnalysis(c.counts) || c.counts.Drivers+c.counts.StartingGrid+c.counts.Weather > 0 {
|
||||
availability.LocalAnalysis = "partial"
|
||||
} else if !c.start.IsZero() && c.start.After(now) {
|
||||
availability.LocalAnalysis = "not_applicable"
|
||||
} else {
|
||||
availability.LocalAnalysis = "pending"
|
||||
}
|
||||
return &ContextSession{Session: session, Meeting: &meeting, Availability: availability}
|
||||
}
|
||||
|
||||
func chooseFocusMeeting(meetings []store.Meeting, previous, next *contextCandidate) *models.Meeting {
|
||||
if next != nil {
|
||||
return meetingModelByKey(meetings, next.meeting.MeetingKey)
|
||||
}
|
||||
if previous != nil {
|
||||
return meetingModelByKey(meetings, previous.meeting.MeetingKey)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func classifyTemporalState(now time.Time, previous, next *contextCandidate, candidates []contextCandidate, championship []store.Meeting, scheduleUnknown bool) TemporalState {
|
||||
var latestStarted *contextCandidate
|
||||
for i := range candidates {
|
||||
if !candidates[i].start.IsZero() && !candidates[i].start.After(now) && (latestStarted == nil || candidates[i].start.After(latestStarted.start)) {
|
||||
latestStarted = &candidates[i]
|
||||
}
|
||||
}
|
||||
// Once a new meeting enters its preparation window, an ingest gap from an
|
||||
// older meeting must not keep the product stuck in settling.
|
||||
if next != nil && next.start.Sub(now) <= preSessionWindow && (latestStarted == nil || latestStarted.meeting.MeetingKey != next.meeting.MeetingKey) {
|
||||
return TemporalPreSession
|
||||
}
|
||||
if latestStarted != nil && !latestStarted.complete && !latestStarted.end.IsZero() {
|
||||
if now.Before(latestStarted.end) {
|
||||
return TemporalPreSession
|
||||
}
|
||||
return TemporalSessionSettling
|
||||
}
|
||||
if previous != nil && next != nil && previous.meeting.MeetingKey == next.meeting.MeetingKey {
|
||||
return TemporalBetweenSessions
|
||||
}
|
||||
if previous != nil && meetingFinalSession(*previous, candidates) && !candidateTime(*previous).After(now) && now.Sub(candidateTime(*previous)) <= postWeekendWindow {
|
||||
return TemporalPostWeekend
|
||||
}
|
||||
if next != nil && next.start.Sub(now) <= preSessionWindow {
|
||||
return TemporalPreSession
|
||||
}
|
||||
if next == nil && len(championship) > 0 && !scheduleUnknown {
|
||||
return TemporalSeasonComplete
|
||||
}
|
||||
return TemporalBetweenWeekends
|
||||
}
|
||||
|
||||
func championshipScheduleUnknown(meetings []store.Meeting, sessions map[int][]store.Session) bool {
|
||||
for _, meeting := range meetings {
|
||||
for _, session := range sessions[meeting.MeetingKey] {
|
||||
if !session.IsCancelled && isChampionshipRace(session) {
|
||||
if _, ok := parseContextTime(session.DateStart); !ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func meetingFinalSession(previous contextCandidate, candidates []contextCandidate) bool {
|
||||
latest := previous.start
|
||||
for _, c := range candidates {
|
||||
if c.meeting.MeetingKey == previous.meeting.MeetingKey && c.start.After(latest) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func championshipMeetings(meetings []store.Meeting, sessions map[int][]store.Session) []store.Meeting {
|
||||
var out []store.Meeting
|
||||
for _, m := range meetings {
|
||||
if m.IsCancelled || isTestMeeting(m) {
|
||||
continue
|
||||
}
|
||||
for _, sess := range sessions[m.MeetingKey] {
|
||||
if !sess.IsCancelled && isChampionshipRace(sess) {
|
||||
out = append(out, m)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
a, _ := parseContextTime(out[i].DateStart)
|
||||
b, _ := parseContextTime(out[j].DateStart)
|
||||
return a.Before(b)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func isTestMeeting(m store.Meeting) bool {
|
||||
n := strings.ToLower(m.MeetingName + " " + m.MeetingOfficialName)
|
||||
return strings.Contains(n, "test")
|
||||
}
|
||||
func isChampionshipRace(s store.Session) bool {
|
||||
n := strings.ToLower(s.SessionName)
|
||||
t := strings.ToLower(s.SessionType)
|
||||
return (n == "race" || t == "race") && !strings.Contains(n, "sprint") && !strings.Contains(t, "sprint")
|
||||
}
|
||||
func championshipRound(meetings []store.Meeting, key int) int {
|
||||
for i, m := range meetings {
|
||||
if m.MeetingKey == key {
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
321
internal/query/context_test.go
Normal file
321
internal/query/context_test.go
Normal file
@@ -0,0 +1,321 @@
|
||||
package query
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/box-box/internal/store"
|
||||
)
|
||||
|
||||
func contextService(t *testing.T, now time.Time) *Service {
|
||||
t.Helper()
|
||||
base := openTestService(t)
|
||||
return NewServiceWithClock(base.store, func() time.Time { return now })
|
||||
}
|
||||
|
||||
func addContextMeeting(t *testing.T, svc *Service, key int, name, start, end string, cancelled bool) {
|
||||
t.Helper()
|
||||
if err := svc.store.UpsertMeeting(store.Meeting{MeetingKey: key, MeetingName: name, MeetingOfficialName: name, CircuitShortName: name, Year: 2026, DateStart: start, DateEnd: end, IsCancelled: cancelled}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func addContextSession(t *testing.T, svc *Service, key, meeting int, name, start, end string, cancelled bool) {
|
||||
t.Helper()
|
||||
if err := svc.store.UpsertSession(store.Session{SessionKey: key, MeetingKey: meeting, SessionName: name, SessionType: name, DateStart: start, DateEnd: end, IsCancelled: cancelled}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func completeContextSession(t *testing.T, svc *Service, key, meeting int) {
|
||||
t.Helper()
|
||||
if err := svc.store.UpsertSessionResult(store.SessionResult{SessionKey: key, MeetingKey: meeting, DriverNumber: 1, Position: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextTemporalStates(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
now string
|
||||
seed func(*testing.T, *Service)
|
||||
evidence LiveEvidence
|
||||
want TemporalState
|
||||
}{
|
||||
{name: "no season", now: "2026-06-01T12:00:00Z", want: TemporalNoSeason},
|
||||
{name: "between weekends", now: "2026-06-10T12:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 1, "Monaco Grand Prix", "2026-06-01T09:00:00Z", "2026-06-02T16:00:00Z", false)
|
||||
addContextSession(t, s, 11, 1, "Race", "2026-06-02T14:00:00Z", "2026-06-02T16:00:00Z", false)
|
||||
completeContextSession(t, s, 11, 1)
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 21, 2, "Practice 1", "2026-06-20T09:00:00Z", "2026-06-20T10:00:00Z", false)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
}, want: TemporalBetweenWeekends},
|
||||
{name: "pre session", now: "2026-06-19T12:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 21, 2, "Practice 1", "2026-06-20T09:00:00Z", "2026-06-20T10:00:00Z", false)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
}, want: TemporalPreSession},
|
||||
{name: "session live overrides schedule", now: "2026-06-20T12:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 21, 2, "Practice 1", "2026-06-20T09:00:00Z", "2026-06-20T10:00:00Z", false)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
}, evidence: LiveEvidence{Active: true, MeetingName: "Canadian Grand Prix", CircuitName: "Canada Grand Prix", SessionName: "Practice 1", SessionType: "Practice 1"}, want: TemporalSessionLive},
|
||||
{name: "session settling", now: "2026-06-20T11:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 21, 2, "Practice 1", "2026-06-20T09:00:00Z", "2026-06-20T10:00:00Z", false)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
}, want: TemporalSessionSettling},
|
||||
{name: "between sessions", now: "2026-06-20T11:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 21, 2, "Practice 1", "2026-06-20T09:00:00Z", "2026-06-20T10:00:00Z", false)
|
||||
completeContextSession(t, s, 21, 2)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
}, want: TemporalBetweenSessions},
|
||||
{name: "post weekend", now: "2026-06-22T18:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
completeContextSession(t, s, 22, 2)
|
||||
}, want: TemporalPostWeekend},
|
||||
{name: "season complete", now: "2026-06-30T12:00:00Z", seed: func(t *testing.T, s *Service) {
|
||||
addContextMeeting(t, s, 2, "Canada Grand Prix", "2026-06-20T09:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
addContextSession(t, s, 22, 2, "Race", "2026-06-22T14:00:00Z", "2026-06-22T16:00:00Z", false)
|
||||
completeContextSession(t, s, 22, 2)
|
||||
}, want: TemporalSeasonComplete},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, tt.now)
|
||||
svc := contextService(t, now)
|
||||
if tt.seed != nil {
|
||||
tt.seed(t, svc)
|
||||
}
|
||||
got, err := svc.ResolveWeekendContext(tt.evidence)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != tt.want {
|
||||
t.Fatalf("state = %s, want %s; context=%+v", got.TemporalState, tt.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextTruthRules(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-10T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "Pre-Season Testing", "2026-02-01T00:00:00Z", "2026-02-03T00:00:00Z", false)
|
||||
addContextSession(t, svc, 10, 1, "Race", "2026-02-03T10:00:00Z", "2026-02-03T12:00:00Z", false)
|
||||
addContextMeeting(t, svc, 2, "Cancelled Grand Prix", "2026-03-01T00:00:00Z", "2026-03-03T00:00:00Z", true)
|
||||
addContextSession(t, svc, 20, 2, "Race", "2026-03-03T10:00:00Z", "2026-03-03T12:00:00Z", false)
|
||||
addContextMeeting(t, svc, 3, "British Grand Prix", "2026-07-01T00:00:00Z", "2026-07-05T00:00:00Z", false)
|
||||
addContextSession(t, svc, 30, 3, "Practice 1", "2026-07-03T09:00:00Z", "2026-07-03T10:00:00Z", false)
|
||||
addContextSession(t, svc, 31, 3, "Sprint", "2026-07-04T10:00:00Z", "2026-07-04T11:00:00Z", false)
|
||||
addContextSession(t, svc, 32, 3, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
completeContextSession(t, svc, 32, 3)
|
||||
addContextMeeting(t, svc, 4, "Belgian Grand Prix", "2026-07-16T00:00:00Z", "2026-07-18T00:00:00Z", false)
|
||||
addContextSession(t, svc, 40, 4, "Practice 1", "2026-07-17T09:00:00Z", "2026-07-17T10:00:00Z", false)
|
||||
addContextSession(t, svc, 41, 4, "Cancelled Practice", "2026-07-18T09:00:00Z", "2026-07-18T10:00:00Z", true)
|
||||
addContextSession(t, svc, 42, 4, "Race", "2026-07-19T14:00:00Z", "2026-07-19T16:00:00Z", false)
|
||||
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TotalChampionshipRounds != 2 || got.ChampionshipRound != 2 {
|
||||
t.Fatalf("rounds = %d/%d, want 2/2", got.ChampionshipRound, got.TotalChampionshipRounds)
|
||||
}
|
||||
if got.DefaultAnalysisSession == nil || got.DefaultAnalysisSession.Session.SessionKey != 32 {
|
||||
t.Fatalf("default analysis = %+v, want completed race 32", got.DefaultAnalysisSession)
|
||||
}
|
||||
if got.NextSession == nil || got.NextSession.Session.SessionKey != 40 {
|
||||
t.Fatalf("next = %+v, want 40", got.NextSession)
|
||||
}
|
||||
if got.NextMeeting.DateStart != "2026-07-17T09:00:00Z" || got.NextMeeting.DateEnd != "2026-07-19T16:00:00Z" {
|
||||
t.Fatalf("display range = %s..%s", got.NextMeeting.DateStart, got.NextMeeting.DateEnd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextPassedTimeDoesNotCompleteSession(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-05T18:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T00:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.PreviousCompletedSession != nil || got.DefaultAnalysisSession != nil {
|
||||
t.Fatalf("passed schedule was treated complete: %+v", got)
|
||||
}
|
||||
archive, err := svc.ResolveWeekendContext(LiveEvidence{Final: true, MeetingName: "British Grand Prix", CircuitName: "British Grand Prix", SessionName: "Race", SessionType: "Race", ObservedAt: now})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if archive.PreviousCompletedSession == nil || archive.PreviousCompletedSession.Availability.Archive != "available" {
|
||||
t.Fatalf("final archive not used: %+v", archive)
|
||||
}
|
||||
if archive.DefaultAnalysisSession != nil {
|
||||
t.Fatal("archive without local analysis must not become default analysis")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextNeverUsesFutureAnalysis(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-01T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T00:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
completeContextSession(t, svc, 11, 1) // bad/preloaded data must not make a future session canonical
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.PreviousCompletedSession != nil || got.DefaultAnalysisSession != nil {
|
||||
t.Fatalf("future analysis selected: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextSprintWeekendHandoff(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-04T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Sprint", "2026-07-04T10:00:00Z", "2026-07-04T11:00:00Z", false)
|
||||
addContextSession(t, svc, 12, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
completeContextSession(t, svc, 11, 1)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != TemporalBetweenSessions || got.PreviousCompletedSession.Session.SessionKey != 11 || got.NextSession.Session.SessionKey != 12 {
|
||||
t.Fatalf("sprint handoff = %+v", got)
|
||||
}
|
||||
if got.TotalChampionshipRounds != 1 {
|
||||
t.Fatalf("sprint created extra championship round: %d", got.TotalChampionshipRounds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextBoundaryTimestamps(t *testing.T) {
|
||||
t.Run("pre-session window is inclusive", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-01T09:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Practice 1", "2026-07-03T09:00:00Z", "2026-07-03T10:00:00Z", false)
|
||||
addContextSession(t, svc, 12, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != TemporalPreSession {
|
||||
t.Fatalf("state = %s", got.TemporalState)
|
||||
}
|
||||
})
|
||||
t.Run("scheduled end enters settling", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-03T10:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Practice 1", "2026-07-03T09:00:00Z", "2026-07-03T10:00:00Z", false)
|
||||
addContextSession(t, svc, 12, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != TemporalSessionSettling {
|
||||
t.Fatalf("state = %s", got.TemporalState)
|
||||
}
|
||||
})
|
||||
t.Run("post-weekend window is inclusive", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-07T16:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 12, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
completeContextSession(t, svc, 12, 1)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != TemporalPostWeekend {
|
||||
t.Fatalf("state = %s", got.TemporalState)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextPartialFutureSchedule(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-01T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "", false)
|
||||
addContextSession(t, svc, 11, 1, "Practice 1", "", "", false)
|
||||
addContextSession(t, svc, 12, 1, "Race", "2026-07-05T14:00:00Z", "", false)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.NextSession == nil || got.NextSession.Session.SessionKey != 12 {
|
||||
t.Fatalf("partial schedule next = %+v", got.NextSession)
|
||||
}
|
||||
if got.FocusMeeting == nil || got.FocusMeeting.DateStart != "2026-07-05T14:00:00Z" || got.FocusMeeting.DateEnd != "2026-07-05T14:00:00Z" {
|
||||
t.Fatalf("partial display range = %+v", got.FocusMeeting)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextActiveSessionIsNotCompletedOrDefault(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-05T15:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 10, 1, "Qualifying", "2026-07-04T14:00:00Z", "2026-07-04T15:00:00Z", false)
|
||||
completeContextSession(t, svc, 10, 1)
|
||||
addContextSession(t, svc, 11, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
completeContextSession(t, svc, 11, 1)
|
||||
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{Active: true, MeetingName: "British Grand Prix", CircuitName: "British Grand Prix", SessionName: "Race", SessionType: "Race", ObservedAt: now})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveSession == nil || got.ActiveSession.Session.SessionKey != 11 {
|
||||
t.Fatalf("active = %+v", got.ActiveSession)
|
||||
}
|
||||
if got.PreviousCompletedSession == nil || got.PreviousCompletedSession.Session.SessionKey != 10 {
|
||||
t.Fatalf("previous = %+v, want earlier completed session", got.PreviousCompletedSession)
|
||||
}
|
||||
if got.DefaultAnalysisSession == nil || got.DefaultAnalysisSession.Session.SessionKey != 10 {
|
||||
t.Fatalf("default = %+v, want earlier completed session", got.DefaultAnalysisSession)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextOldIncompleteSessionDoesNotSuppressNextWeekend(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-16T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextMeeting(t, svc, 2, "Belgian Grand Prix", "2026-07-17T09:00:00Z", "2026-07-19T16:00:00Z", false)
|
||||
addContextSession(t, svc, 21, 2, "Practice 1", "2026-07-17T09:00:00Z", "2026-07-17T10:00:00Z", false)
|
||||
addContextSession(t, svc, 22, 2, "Race", "2026-07-19T14:00:00Z", "2026-07-19T16:00:00Z", false)
|
||||
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != TemporalPreSession {
|
||||
t.Fatalf("state = %s, want %s; context=%+v", got.TemporalState, TemporalPreSession, got)
|
||||
}
|
||||
if got.FocusMeeting == nil || got.FocusMeeting.MeetingKey != 2 {
|
||||
t.Fatalf("focus = %+v, want Belgian weekend", got.FocusMeeting)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextMissingScheduleDoesNotClaimSeasonComplete(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-01T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "", "", false)
|
||||
addContextSession(t, svc, 11, 1, "Race", "", "", false)
|
||||
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != TemporalBetweenWeekends {
|
||||
t.Fatalf("state = %s, want limited %s context", got.TemporalState, TemporalBetweenWeekends)
|
||||
}
|
||||
if got.TotalChampionshipRounds != 1 {
|
||||
t.Fatalf("total rounds = %d, want scheduled round retained", got.TotalChampionshipRounds)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package query
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/box-box/internal/chapters"
|
||||
"github.com/AmanTahiliani/box-box/internal/models"
|
||||
@@ -12,11 +13,20 @@ import (
|
||||
// Service assembles store-backed read models.
|
||||
type Service struct {
|
||||
store *store.Store
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewService creates a query service over a domain store.
|
||||
func NewService(st *store.Store) *Service {
|
||||
return &Service{store: st}
|
||||
return NewServiceWithClock(st, time.Now)
|
||||
}
|
||||
|
||||
// NewServiceWithClock creates a query service with an injected clock.
|
||||
func NewServiceWithClock(st *store.Store, now func() time.Time) *Service {
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
return &Service{store: st, now: now}
|
||||
}
|
||||
|
||||
// EnrichedResult is a session result with driver identity fields.
|
||||
|
||||
52
internal/web/context.go
Normal file
52
internal/web/context.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/AmanTahiliani/box-box/internal/live"
|
||||
"github.com/AmanTahiliani/box-box/internal/query"
|
||||
)
|
||||
|
||||
func (s *Server) handleWeekendContext(w http.ResponseWriter, _ *http.Request) {
|
||||
if !s.hasLocalQuery() {
|
||||
writeJSON(w, query.WeekendContext{TemporalState: query.TemporalNoSeason})
|
||||
return
|
||||
}
|
||||
|
||||
state := s.hub.State()
|
||||
evidence := query.LiveEvidence{}
|
||||
if state.IsLive && state.Data != nil {
|
||||
evidence = liveEvidence(state.Data, true, false)
|
||||
} else if state.LastSnapshot != nil && terminalSessionStatus(state.LastSnapshot.SessionStatus) {
|
||||
evidence = liveEvidence(state.LastSnapshot, false, true)
|
||||
if state.LastSnapshotAt != nil {
|
||||
evidence.ObservedAt = *state.LastSnapshotAt
|
||||
}
|
||||
}
|
||||
context, err := s.query.ResolveWeekendContext(evidence)
|
||||
if err != nil {
|
||||
writeError(w, err, http.StatusInternalServerError, false)
|
||||
return
|
||||
}
|
||||
writeJSON(w, context)
|
||||
}
|
||||
|
||||
func liveEvidence(data *live.LiveStreamData, active, final bool) query.LiveEvidence {
|
||||
return query.LiveEvidence{Active: active, Final: final, MeetingName: data.Session.MeetingName, CircuitName: data.Session.CircuitName, SessionName: data.Session.SessionName, SessionType: data.Session.SessionType}
|
||||
}
|
||||
|
||||
func terminalSessionStatus(status string) bool {
|
||||
normalized := strings.ToLower(strings.Map(func(r rune) rune {
|
||||
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
|
||||
return r
|
||||
}
|
||||
return -1
|
||||
}, status))
|
||||
switch normalized {
|
||||
case "finished", "finalised", "finalized", "ended", "aborted":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
113
internal/web/context_test.go
Normal file
113
internal/web/context_test.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/box-box/internal/live"
|
||||
"github.com/AmanTahiliani/box-box/internal/query"
|
||||
"github.com/AmanTahiliani/box-box/internal/store"
|
||||
)
|
||||
|
||||
func openContextStore(t *testing.T) *store.Store {
|
||||
t.Helper()
|
||||
st, err := store.Open(filepath.Join(t.TempDir(), "context.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
return st
|
||||
}
|
||||
|
||||
func seedContextHandler(t *testing.T, st *store.Store) {
|
||||
t.Helper()
|
||||
if err := st.UpsertMeeting(store.Meeting{MeetingKey: 1, MeetingName: "British Grand Prix", CircuitShortName: "Silverstone", Year: 2026, DateStart: "2026-07-03T09:00:00Z", DateEnd: "2026-07-05T16:00:00Z"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.UpsertSession(store.Session{SessionKey: 11, MeetingKey: 1, SessionName: "Race", SessionType: "Race", DateStart: "2026-07-05T14:00:00Z", DateEnd: "2026-07-05T16:00:00Z"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeekendContextHandlerWithoutStoreReturnsNoSeason(t *testing.T) {
|
||||
s := NewServer(nil, 0, nil)
|
||||
rr := httptest.NewRecorder()
|
||||
s.handleWeekendContext(rr, httptest.NewRequest(http.MethodGet, "/api/v1/weekend-context", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rr.Code)
|
||||
}
|
||||
var got query.WeekendContext
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != query.TemporalNoSeason {
|
||||
t.Fatalf("state = %s", got.TemporalState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeekendContextHandlerUsesLiveHubIdentityWithoutOpenF1(t *testing.T) {
|
||||
st := openContextStore(t)
|
||||
seedContextHandler(t, st)
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-05T13:55:00Z")
|
||||
s := NewServer(nil, 0, st) // a nil OpenF1 client makes any REST dependency panic
|
||||
s.query = query.NewServiceWithClock(st, func() time.Time { return now })
|
||||
s.hub.applySnapshot(live.LiveStreamData{SessionStatus: "Started", Session: live.LiveSessionMeta{MeetingName: "British Grand Prix", CircuitName: "Silverstone", SessionName: "Race", SessionType: "Race"}}, now)
|
||||
|
||||
handler, err := s.routes()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/v1/weekend-context", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", rr.Code, rr.Body.String())
|
||||
}
|
||||
var got query.WeekendContext
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TemporalState != query.TemporalSessionLive || got.ActiveSession == nil || got.ActiveSession.Session.SessionKey != 11 {
|
||||
t.Fatalf("live context = %+v", got)
|
||||
}
|
||||
if got.ActiveSession.Availability.LiveTransport != "connected" || got.ActiveSession.Availability.LiveSession != "active" {
|
||||
t.Fatalf("availability = %+v", got.ActiveSession.Availability)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeekendContextHandlerUsesTerminalArchiveAsCompletionEvidence(t *testing.T) {
|
||||
st := openContextStore(t)
|
||||
seedContextHandler(t, st)
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-05T16:05:00Z")
|
||||
s := NewServer(nil, 0, st)
|
||||
s.query = query.NewServiceWithClock(st, func() time.Time { return now })
|
||||
s.hub.applySnapshot(live.LiveStreamData{SessionStatus: "Finished", Session: live.LiveSessionMeta{MeetingName: "British Grand Prix", CircuitName: "Silverstone", SessionName: "Race", SessionType: "Race"}}, now)
|
||||
rr := httptest.NewRecorder()
|
||||
s.handleWeekendContext(rr, httptest.NewRequest(http.MethodGet, "/api/v1/weekend-context", nil))
|
||||
var got query.WeekendContext
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.PreviousCompletedSession == nil || got.PreviousCompletedSession.Availability.Archive != "available" {
|
||||
t.Fatalf("archive context = %+v", got)
|
||||
}
|
||||
if got.DefaultAnalysisSession != nil {
|
||||
t.Fatal("archive-only session must not become local default analysis")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalSessionStatus(t *testing.T) {
|
||||
for _, status := range []string{"Finished", "Finalised", "ENDED", "Aborted"} {
|
||||
if !terminalSessionStatus(status) {
|
||||
t.Errorf("%q should be terminal", status)
|
||||
}
|
||||
}
|
||||
for _, status := range []string{"Started", "Resumed", "Inactive", ""} {
|
||||
if terminalSessionStatus(status) {
|
||||
t.Errorf("%q should not be terminal", status)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,7 +134,7 @@ func (h *SSEHub) applySnapshot(data live.LiveStreamData, now time.Time) liveStat
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
if snapshotIsLive(data) {
|
||||
if live.SessionStatusIsActive(data.SessionStatus) {
|
||||
h.isLive = true
|
||||
h.activeSnapshot = &data
|
||||
if data.PositionUpdated && len(data.Positions) > 0 {
|
||||
@@ -208,40 +208,6 @@ func (h *SSEHub) stateLocked() liveStatePayload {
|
||||
return payload
|
||||
}
|
||||
|
||||
// snapshotIsLive reports whether the current live-timing snapshot represents an
|
||||
// ongoing session that should be surfaced as live.
|
||||
//
|
||||
// An actively running session (Started/Resumed) is always live. A non-terminal
|
||||
// but temporarily inactive session — e.g. a red-flag pause where SessionStatus
|
||||
// drops to "Inactive" while the session is still in progress — is also live when
|
||||
// the snapshot itself carries live evidence: a session clock with time remaining
|
||||
// plus session metadata. This keeps the paused track state visible instead of
|
||||
// collapsing to the inactive empty state.
|
||||
//
|
||||
// Terminal sessions (Finished/Finalised/Ends/Aborted) are never live. A generic
|
||||
// inactive/no-session stale snapshot is not live either: the predicate keys off
|
||||
// the current snapshot's clock and session, so old metadata alone is not enough.
|
||||
func snapshotIsLive(data live.LiveStreamData) bool {
|
||||
if live.SessionStatusIsActive(data.SessionStatus) {
|
||||
return true
|
||||
}
|
||||
if live.SessionStatusIsTerminal(data.SessionStatus) {
|
||||
return false
|
||||
}
|
||||
return clockHasTimeRemaining(data.Clock) && data.Session.SessionName != ""
|
||||
}
|
||||
|
||||
// clockHasTimeRemaining reports whether an "HH:MM:SS" session clock has any time
|
||||
// left. Empty or all-zero clocks (a spent or absent session) return false.
|
||||
func clockHasTimeRemaining(clock string) bool {
|
||||
for _, r := range clock {
|
||||
if r >= '1' && r <= '9' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hasLiveSnapshotData(data live.LiveStreamData) bool {
|
||||
return len(data.Drivers) > 0 ||
|
||||
len(data.DriverInfo) > 0 ||
|
||||
|
||||
@@ -51,101 +51,6 @@ func TestSSEHubArchivesTerminalSessionSnapshot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotIsLive(t *testing.T) {
|
||||
redFlag := live.LiveStreamData{
|
||||
SessionStatus: "Inactive",
|
||||
TrackStatus: "2",
|
||||
Clock: "00:03:27",
|
||||
Session: live.LiveSessionMeta{MeetingName: "Belgian Grand Prix", SessionName: "Practice 2", SessionType: "Practice"},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
data live.LiveStreamData
|
||||
want bool
|
||||
}{
|
||||
{"started", live.LiveStreamData{SessionStatus: "Started"}, true},
|
||||
{"resumed", live.LiveStreamData{SessionStatus: "Resumed"}, true},
|
||||
{"red flag inactive with clock and session", redFlag, true},
|
||||
{"terminal finished with clock", func() live.LiveStreamData {
|
||||
d := redFlag
|
||||
d.SessionStatus = "Finished"
|
||||
return d
|
||||
}(), false},
|
||||
{"inactive spent clock", func() live.LiveStreamData {
|
||||
d := redFlag
|
||||
d.Clock = "00:00:00"
|
||||
return d
|
||||
}(), false},
|
||||
{"inactive no clock", func() live.LiveStreamData {
|
||||
d := redFlag
|
||||
d.Clock = ""
|
||||
return d
|
||||
}(), false},
|
||||
{"inactive no session metadata", func() live.LiveStreamData {
|
||||
d := redFlag
|
||||
d.Session = live.LiveSessionMeta{}
|
||||
return d
|
||||
}(), false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := snapshotIsLive(tt.data); got != tt.want {
|
||||
t.Errorf("%s: snapshotIsLive = %v, want %v", tt.name, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEHubKeepsRedFlagSessionLive(t *testing.T) {
|
||||
hub := newSSEHub()
|
||||
now := time.Date(2026, 7, 26, 14, 0, 0, 0, time.UTC)
|
||||
|
||||
redFlag := live.LiveStreamData{
|
||||
SessionStatus: "Inactive",
|
||||
TrackStatus: "2",
|
||||
Clock: "00:03:27",
|
||||
Session: live.LiveSessionMeta{MeetingName: "Belgian Grand Prix", SessionName: "Practice 2", SessionType: "Practice"},
|
||||
SnapshotUpdated: true,
|
||||
}
|
||||
state := hub.applySnapshot(redFlag, now)
|
||||
|
||||
if !state.IsLive {
|
||||
t.Fatal("red-flag paused session should report is_live=true")
|
||||
}
|
||||
if state.Data == nil {
|
||||
t.Fatal("red-flag paused session must still send the active snapshot")
|
||||
}
|
||||
if state.Data.TrackStatus != "2" {
|
||||
t.Fatalf("track status = %q, want the paused state \"2\"", state.Data.TrackStatus)
|
||||
}
|
||||
if state.LastSnapshot != nil {
|
||||
t.Fatalf("red-flag session should not be archived: %+v", state.LastSnapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEHubStaleInactiveSnapshotNotLive(t *testing.T) {
|
||||
hub := newSSEHub()
|
||||
now := time.Date(2026, 7, 26, 14, 0, 0, 0, time.UTC)
|
||||
|
||||
// Inactive snapshot with session metadata but no remaining clock: this is a
|
||||
// stale/no-live-evidence snapshot and must not be surfaced as live.
|
||||
stale := live.LiveStreamData{
|
||||
SessionStatus: "Inactive",
|
||||
Clock: "00:00:00",
|
||||
Session: live.LiveSessionMeta{MeetingName: "Belgian Grand Prix", SessionName: "Practice 2"},
|
||||
SnapshotUpdated: true,
|
||||
}
|
||||
state := hub.applySnapshot(stale, now)
|
||||
|
||||
if state.IsLive {
|
||||
t.Fatal("stale inactive snapshot should report is_live=false")
|
||||
}
|
||||
if state.Data != nil {
|
||||
t.Fatalf("stale inactive snapshot leaked into active data: %+v", state.Data)
|
||||
}
|
||||
if state.LastSnapshot == nil {
|
||||
t.Fatal("stale inactive snapshot with metadata should be archived")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleLiveStateKeepsArchiveOutOfActiveData(t *testing.T) {
|
||||
hub := newSSEHub()
|
||||
now := time.Date(2026, 7, 4, 14, 0, 0, 0, time.UTC)
|
||||
|
||||
@@ -62,6 +62,7 @@ func (s *Server) routes() (http.Handler, error) {
|
||||
|
||||
// REST API — /api/v1/laps/comparison must be registered before /api/v1/laps
|
||||
// because Go's ServeMux uses longest-prefix matching.
|
||||
mux.HandleFunc("/api/v1/weekend-context", s.handleWeekendContext)
|
||||
mux.HandleFunc("/api/v1/race-hub", s.handleRaceHub)
|
||||
mux.HandleFunc("/api/v1/seasons", s.handleSeasons)
|
||||
mux.HandleFunc("/api/v1/weekend", s.handleWeekend)
|
||||
|
||||
@@ -147,58 +147,6 @@ const sprintQualifyingSnapshot = {
|
||||
},
|
||||
}
|
||||
|
||||
// Practice: the feed sets best laps but no GapToLeader/Interval, and there is
|
||||
// no race lap-total concept. Exercises computed gaps, the non-race banner, the
|
||||
// collapsed-by-default tyre panel, and the 390px core-field layout.
|
||||
const practiceSnapshot = {
|
||||
is_live: true,
|
||||
data: {
|
||||
...raceSnapshot.data,
|
||||
Drivers: Object.fromEntries(
|
||||
Array.from({ length: 10 }, (_, index) => {
|
||||
const num = String(index + 1)
|
||||
return [
|
||||
num,
|
||||
driver(num, index + 1, '', '', {
|
||||
// Distinct, increasing best laps; P1 fastest, +0.200s per position.
|
||||
BestLapTime: `1:${(45.9 + index * 0.2).toFixed(3).padStart(6, '0')}`,
|
||||
LastLapTime: '1:46.500',
|
||||
NumberOfLaps: 12,
|
||||
Sectors: index === 0
|
||||
? [
|
||||
{ Value: '28.500', PersonalFastest: true, OverallFastest: false },
|
||||
{ Value: '52.100', PersonalFastest: false, OverallFastest: false },
|
||||
{ Value: '25.344', PersonalFastest: false, OverallFastest: false },
|
||||
]
|
||||
: [],
|
||||
}),
|
||||
]
|
||||
}),
|
||||
),
|
||||
DriverInfo: Object.fromEntries(
|
||||
Array.from({ length: 10 }, (_, index) => {
|
||||
const num = String(index + 1)
|
||||
return [num, info(num, `D${index + 1}`, 'Driver', String(index + 1), 'Test Team', index % 2 ? 'FF8000' : '27F4D2')]
|
||||
}),
|
||||
),
|
||||
Tyres: Object.fromEntries(
|
||||
Array.from({ length: 10 }, (_, index) => [String(index + 1), { Compound: 'SOFT', New: false, Age: index % 4 }]),
|
||||
),
|
||||
Session: {
|
||||
MeetingName: 'Belgian Grand Prix',
|
||||
CircuitName: 'Spa-Francorchamps',
|
||||
SessionType: 'Practice',
|
||||
SessionName: 'Practice 2',
|
||||
},
|
||||
TrackStatus: '1',
|
||||
CurrentLap: 0,
|
||||
TotalLaps: 0,
|
||||
Clock: '00:45:00',
|
||||
ClockRefTime: '2026-07-17T13:00:00Z',
|
||||
ClockExtrapolating: false,
|
||||
},
|
||||
}
|
||||
|
||||
test.describe('Live Timing (mocked snapshot)', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/v1/live/state', (route) =>
|
||||
@@ -285,94 +233,6 @@ test.describe('Live Timing (mocked Sprint Qualifying)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test.describe('Live Timing (mocked Practice)', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/v1/live/state', (route) =>
|
||||
route.fulfill({ contentType: 'application/json', body: JSON.stringify(practiceSnapshot) }),
|
||||
)
|
||||
await page.route('**/api/v1/live/stream', (route) =>
|
||||
route.fulfill({ contentType: 'text/event-stream', body: 'event: heartbeat\ndata: {}\n\n' }),
|
||||
)
|
||||
await page.goto('/live')
|
||||
})
|
||||
|
||||
test('derives a gap to P1 from best laps and marks the leader', async ({ page }) => {
|
||||
const tower = page.locator('.live-tower')
|
||||
await expect(tower).toBeVisible()
|
||||
// P1 shows a leader marker, not a fabricated gap.
|
||||
await expect(tower.locator('tbody tr').first()).toContainText('—')
|
||||
// P2 shows the computed +0.200 delta.
|
||||
await expect(tower).toContainText('+0.200')
|
||||
})
|
||||
|
||||
test('omits the race lap counter and keeps the session clock for practice', async ({ page }) => {
|
||||
await expect(page.getByTestId('live-lap-counter')).toHaveCount(0)
|
||||
await expect(page.getByTestId('live-clock')).toContainText('00:45:00')
|
||||
await expect(page.locator('.live-banner')).not.toContainText('L-/-')
|
||||
})
|
||||
|
||||
test('collapses the tyre panel by default so the tower is above the fold', async ({ page }) => {
|
||||
await expect(page.getByTestId('tyredeg-panel')).toBeVisible()
|
||||
await expect(page.getByTestId('tyredeg-row')).toHaveCount(0)
|
||||
await expect(page.locator('.live-tower')).toBeVisible()
|
||||
})
|
||||
|
||||
test('labels Race Control times as UTC', async ({ page }) => {
|
||||
await expect(page.getByTestId('rc-timezone')).toContainText('UTC')
|
||||
})
|
||||
|
||||
test('marks Live as active in the primary navigation', async ({ page }) => {
|
||||
await expect(page.getByTestId('nav-live')).toHaveAttribute('data-live-active', 'true')
|
||||
await expect(page.getByTestId('nav-live').locator('.nav-live-dot')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
test.describe('Live Timing (390px practice viewport)', () => {
|
||||
test.use({ viewport: { width: 390, height: 844 } })
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/v1/live/state', (route) =>
|
||||
route.fulfill({ contentType: 'application/json', body: JSON.stringify(practiceSnapshot) }),
|
||||
)
|
||||
await page.route('**/api/v1/live/stream', (route) =>
|
||||
route.fulfill({ contentType: 'text/event-stream', body: 'event: heartbeat\ndata: {}\n\n' }),
|
||||
)
|
||||
await page.goto('/live')
|
||||
})
|
||||
|
||||
test('shows the five core fields with no horizontal overflow', async ({ page }) => {
|
||||
const tower = page.locator('.live-tower')
|
||||
await expect(tower).toBeVisible()
|
||||
|
||||
// Core comparison fields are present in the header.
|
||||
await expect(tower.locator('thead')).toContainText('Pos')
|
||||
await expect(tower.locator('thead')).toContainText('Driver')
|
||||
await expect(tower.locator('thead')).toContainText('Tyre')
|
||||
await expect(tower.locator('thead')).toContainText('Best')
|
||||
await expect(tower.locator('thead')).toContainText('Gap to P1')
|
||||
|
||||
// Sectors are hidden from the initial mobile tower (reachable via expand).
|
||||
const firstSector = tower.locator('thead th', { hasText: 'S1' })
|
||||
await expect(firstSector).toBeHidden()
|
||||
|
||||
// The document must not scroll horizontally.
|
||||
const overflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
)
|
||||
expect(overflow).toBeLessThanOrEqual(0)
|
||||
})
|
||||
|
||||
test('exposes sectors through the row detail interaction', async ({ page }) => {
|
||||
// Sector columns are not in the initial mobile tower...
|
||||
await expect(page.locator('.live-tower thead th', { hasText: 'S1' })).toBeHidden()
|
||||
// ...but the P1 row's sectors are reachable by expanding the row.
|
||||
await page.locator('.live-tower tbody tr', { hasText: 'D1' }).first().click()
|
||||
const sectors = page.getByTestId('expanded-sectors')
|
||||
await expect(sectors).toBeVisible()
|
||||
await expect(sectors).toContainText('28.500')
|
||||
})
|
||||
})
|
||||
|
||||
test.describe('Live Timing (no session)', () => {
|
||||
test('shows the empty state when the feed has no snapshot', async ({ page }) => {
|
||||
await page.goto('/live')
|
||||
|
||||
Reference in New Issue
Block a user