feat(training): base training stats on practice, keep race laps separate

Training stats count Open/Free practice by default; laps from
qualifying, heats and finals are kept and shown under Based on: Races
or All, marked with race, session and series. Races are listed per race
session and never split into stints. Same picker in the mobile profile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
larssandandClaude Opus 5.5 committed 2026-10-10 20:08:17 +02:00
1 parent 9a9379aa83
commit af79b610db
15 files changed
+377 -42

No files matched your search

+78 -12
View File
@@ -83,6 +83,8 @@ export function normalizeTrainingState(training, { uid }) {
lapMs: Math.max(0, Math.round(Number(entry?.lapMs || 0) || 0)),
recordedAt: String(entry?.recordedAt || (timestamp ? new Date(timestamp).toISOString() : new Date().toISOString())),
trackLayoutId: String(entry?.trackLayoutId || "").trim(),
sessionType: String(entry?.sessionType || "").trim(),
eventId: String(entry?.eventId || "").trim(),
};
})
.filter((entry) => {
@@ -248,6 +250,7 @@ export function syncTrainingLedger(training, state, { uid }) {
// can run one Open Practice all season and switch layout mid-session, and laps on
// either side of the switch must land on their own layout.
trackLayoutId: timestamp ? getTrackLayoutIdAt(state?.trackLayouts, timestamp) : String(session?.trackLayoutId || "").trim(),
sessionType: String(session?.type || ""),
});
});
});
@@ -255,18 +258,74 @@ export function syncTrainingLedger(training, state, { uid }) {
// Spread the rest of `normalized` rather than listing each field by name: an evenLaps
// config once went missing here because this rebuild listed fields individually and
// silently dropped a newly-added one. Only `ledger` actually needs to change.
// Laps saved before the session type was recorded get it from their session, if it still
// exists (otherwise they stay "" and count as practice - nothing disappears).
retained.forEach((entry) => {
if (!entry.sessionType && sessions.has(entry.sessionId)) entry.sessionType = String(sessions.get(entry.sessionId).type || "");
});
return normalizeTrainingState({
...normalized,
ledger: [...retained, ...current],
}, { uid });
}
export function getDriverTrainingLaps(state, driverId, classId = "") {
// Training stats are about practice: laps from qualifying, heats, finals and team races are
// kept (a driver may want to compare race pace) but only counted when "race" or "all" is
// chosen. Laps whose session type is unknown count as practice.
const RACE_SESSION_TYPES = new Set(["qualification", "heat", "final", "team_race"]);
export const TRAINING_LAP_SOURCES = Object.freeze(["practice", "race", "all"]);
export function getTrainingLapSource(sessionType) {
return RACE_SESSION_TYPES.has(String(sessionType || "")) ? "race" : "practice";
}
export function normalizeTrainingLapSource(value) {
return TRAINING_LAP_SOURCES.includes(String(value)) ? String(value) : "practice";
}
const practiceLapsOnly = (laps) => laps.filter((lap) => lap.source !== "race");
// One row per race session (a qualifying heat, a final ...) the driver took part in: laps,
// best, average and spread - the race counterpart of the practice stint table.
export function buildTrainingRaceSessions(state, driverId, classId = "", { layout = "all" } = {}) {
const bySession = new Map();
getDriverTrainingLapsForLayout(state, driverId, classId, layout, "race").forEach((lap) => {
if (!bySession.has(lap.sessionId)) bySession.set(lap.sessionId, { sessionId: lap.sessionId, sessionType: lap.sessionType, sessionName: lap.sessionName, eventId: lap.eventId, eventName: lap.eventName, laps: [] });
bySession.get(lap.sessionId).laps.push(lap);
});
return [...bySession.values()].map((session) => {
const values = session.laps.filter((lap) => !lap.excludedFromPace).map((lap) => lap.lapMs);
return {
sessionId: session.sessionId,
sessionType: session.sessionType,
sessionName: session.sessionName,
eventId: session.eventId,
eventName: session.eventName,
startedAt: Math.min(...session.laps.map((lap) => lap.timestamp - lap.lapMs)),
lapCount: session.laps.length,
bestLapMs: values.length ? Math.min(...values) : 0,
averageLapMs: values.length ? Math.round(values.reduce((sum, value) => sum + value, 0) / values.length) : 0,
consistencyPct: values.length >= 3 ? consistencySpread(values) : null,
};
}).sort((a, b) => b.startedAt - a.startedAt);
}
export function getDriverTrainingLaps(state, driverId, classId = "", { source = "practice" } = {}) {
const ledger = Array.isArray(state?.training?.ledger) ? state.training.ledger : [];
const profileReferences = getTrainingDriverIds(state, driverId, classId);
const sessionTypes = new Map((Array.isArray(state?.sessions) ? state.sessions : []).map((session) => [String(session.id), String(session.type || "")]));
const wanted = normalizeTrainingLapSource(source);
return ledger
.filter((entry) => profileReferences.has(String(entry?.driverId || "")) && Number(entry?.lapMs || 0) > 500)
.map((entry) => ({
.map((entry) => {
const sessionType = String(entry.sessionType || sessionTypes.get(String(entry.sessionId || "")) || "");
return { entry, sessionType, source: getTrainingLapSource(sessionType) };
})
.filter(({ source: lapSource }) => wanted === "all" || lapSource === wanted)
.map(({ entry, sessionType, source: lapSource }) => ({
sessionType,
source: lapSource,
eventId: String(entry.eventId || ""),
sessionId: String(entry.sessionId || ""),
sessionName: String(entry.sessionName || ""),
eventName: String(entry.eventName || ""),
@@ -292,8 +351,8 @@ export function getDriverTrainingLaps(state, driverId, classId = "") {
// `layout` picks which laps count: "current" (default, the active layout), "all" (every
// layout blended - the overall view), "none" (laps driven before any layout existed), or
// a specific layout id.
export function getDriverTrainingLapsForLayout(state, driverId, classId = "", layout = "current") {
const laps = getDriverTrainingLaps(state, driverId, classId);
export function getDriverTrainingLapsForLayout(state, driverId, classId = "", layout = "current", source = "practice") {
const laps = getDriverTrainingLaps(state, driverId, classId, { source });
if (layout === "all") return laps;
const layoutId = layout === "current" || !layout ? getTrackLayoutIdAt(state?.trackLayouts) : layout === "none" ? "" : String(layout);
return laps.filter((lap) => lap.trackLayoutId === layoutId);
@@ -453,10 +512,12 @@ function getTrainingStintMetrics(stint) {
};
}
export function buildTrainingStintAnalysis(state, driverId, classId = "", { layout = "current" } = {}) {
export function buildTrainingStintAnalysis(state, driverId, classId = "", { layout = "current", source = "practice" } = {}) {
// Scoped to one track layout (the active one unless another is chosen), same as
// buildDriverTrainingStats - a "best stint" spanning two tracks would not be comparable.
const stints = splitTrainingStints(getDriverTrainingLapsForLayout(state, driverId, classId, layout));
// Stints are a practice idea (breaks split a run into stints). A race is one fixed-time run,
// so race laps never form stints - see buildTrainingRaceSessions for those.
const stints = splitTrainingStints(practiceLapsOnly(getDriverTrainingLapsForLayout(state, driverId, classId, layout, source)));
const rows = stints.map((stint, index) => {
const { laps, values, outlierLaps, startPaceMs, endPaceMs, endChangeMs, strongFinish } = getTrainingStintMetrics(stint);
return {
@@ -531,8 +592,13 @@ function buildDailySummaries(laps) {
const byDay = new Map();
laps.forEach((lap) => {
const key = getLocalDayKey(lap.timestamp);
const current = byDay.get(key) || { dateKey: key, laps: 0, totalMs: 0, bestLapMs: 0, latestTimestamp: 0 };
const current = byDay.get(key) || { dateKey: key, laps: 0, totalMs: 0, bestLapMs: 0, latestTimestamp: 0, raceLaps: 0, raceSessions: [] };
current.laps += 1;
if (lap.source === "race") {
current.raceLaps += 1;
const label = [lap.eventName, lap.sessionName].filter(Boolean).join(" · ");
if (label && !current.raceSessions.includes(label)) current.raceSessions.push(label);
}
current.totalMs += lap.lapMs;
current.bestLapMs = current.bestLapMs ? Math.min(current.bestLapMs, lap.lapMs) : lap.lapMs;
current.latestTimestamp = Math.max(current.latestTimestamp, lap.timestamp);
@@ -675,15 +741,15 @@ export function getBestTrainingDurationResult(stints, targetMs = 5 * 60 * 1000)
return best;
}
export function buildDriverTrainingStats(state, driverId, classId = "", { layout = "current" } = {}) {
export function buildDriverTrainingStats(state, driverId, classId = "", { layout = "current", source = "practice" } = {}) {
// Lifetime commitment stats (how much a driver has trained, ever) read the full lap
// history - a track rebuild doesn't erase past practice. Every pace/record/consistency
// stat below instead reads layoutLaps, scoped to whichever track layout is active right
// now, so a lap from a track that no longer exists can't be reported as today's "record"
// or blend into today's consistency numbers. The `layout` option picks another layout,
// or "all" for the overall view - see getDriverTrainingLapsForLayout.
const laps = getDriverTrainingLaps(state, driverId, classId);
const layoutLaps = getDriverTrainingLapsForLayout(state, driverId, classId, layout);
const laps = getDriverTrainingLaps(state, driverId, classId, { source });
const layoutLaps = getDriverTrainingLapsForLayout(state, driverId, classId, layout, source);
const historyPaceLaps = laps.filter((lap) => !lap.excludedFromPace);
const paceLaps = layoutLaps.filter((lap) => !lap.excludedFromPace);
const lapTimes = paceLaps.map((lap) => lap.lapMs);
@@ -704,7 +770,7 @@ export function buildDriverTrainingStats(state, driverId, classId = "", { layout
const controlZoneMinMs = bestLapMs;
const controlTargetMs = bestLapMs ? Math.round(bestLapMs * 1.08) : 0;
const dailySummaries = buildDailySummaries(historyPaceLaps);
const stints = splitTrainingStints(layoutLaps);
const stints = splitTrainingStints(practiceLapsOnly(layoutLaps));
const stintMetrics = stints.map((stint) => ({ stint, ...getTrainingStintMetrics(stint) }));
const controlledLapStreak = getLongestControlledLapStreak(stints, controlTargetMs);
const completedFiveMinuteStints = stints.filter((stint) => getBestTrainingDurationResult([stint], 5 * 60 * 1000)).length;
@@ -715,7 +781,7 @@ export function buildDriverTrainingStats(state, driverId, classId = "", { layout
const bestFiveMinuteResult = getBestTrainingDurationResult(stints, 5 * 60 * 1000);
const todayKey = getLocalDayKey(Date.now());
const todayLaps = layoutLaps.filter((lap) => getLocalDayKey(lap.timestamp) === todayKey);
const todayStints = splitTrainingStints(todayLaps);
const todayStints = splitTrainingStints(practiceLapsOnly(todayLaps));
const todayStintMetrics = todayStints.map((stint) => ({ stint, ...getTrainingStintMetrics(stint) }));
const todayLapTimes = todayLaps.filter((lap) => !lap.excludedFromPace).map((lap) => lap.lapMs);