import { getDriverProfile, getDriverProfileReferences } from "./driver_profile_logic.js"; import { getTrackLayoutIdAt } from "./track_layouts_logic.js"; const PUBLIC_TRAINING_SECTIONS = ["progress", "achievements", "performance", "goals", "history"]; function normalizePublicTrainingVisibility(value) { const source = value && typeof value === "object" ? value : {}; return Object.fromEntries(PUBLIC_TRAINING_SECTIONS.map((key) => [key, source[key] !== false])); } function getTrainingDriverIds(state, driverId, classId = "") { const profile = getDriverProfile(state, driverId); if (!profile) return getDriverProfileReferences(state, driverId); const normalizedClassId = String(classId || ""); return new Set(profile.drivers .filter((driver) => !normalizedClassId || String(driver.classId || "") === normalizedClassId) .map((driver) => String(driver.id || "")) .filter(Boolean)); } export function normalizeTrainingState(training, { uid }) { const source = training && typeof training === "object" ? training : {}; const clubGoalSource = source.clubGoal && typeof source.clubGoal === "object" ? source.clubGoal : null; const clubGoalMetric = String(clubGoalSource?.metric || "") === "sessions" ? "sessions" : "laps"; const clubGoalExerciseKind = ["timer", "evenLaps", "stepTraining"].includes(String(clubGoalSource?.exerciseKind || "")) ? String(clubGoalSource.exerciseKind) : ""; const clubGoalHasTarget = clubGoalSource && (clubGoalMetric === "sessions" ? Number(clubGoalSource.targetSessions || 0) > 0 && clubGoalExerciseKind : Number(clubGoalSource.targetLaps || 0) > 0); const clubGoal = clubGoalHasTarget ? { id: String(clubGoalSource.id || uid("club_goal")), title: String(clubGoalSource.title || "").trim(), reward: String(clubGoalSource.reward || "").trim(), targetLaps: Math.max(1, Math.round(Number(clubGoalSource.targetLaps || 0) || 0)), baselineLaps: Math.max(0, Math.round(Number(clubGoalSource.baselineLaps || 0) || 0)), metric: clubGoalMetric, exerciseKind: clubGoalMetric === "sessions" ? clubGoalExerciseKind : "", targetSessions: Math.max(1, Math.round(Number(clubGoalSource.targetSessions || 0) || 0)), baselineSessions: Math.max(0, Math.round(Number(clubGoalSource.baselineSessions || 0) || 0)), createdAt: String(clubGoalSource.createdAt || new Date().toISOString()), celebratedAt: clubGoalSource.celebratedAt ? String(clubGoalSource.celebratedAt) : "", } : null; const goals = Array.isArray(source.goals) ? source.goals .map((goal) => { const metric = String(goal?.metric || "") === "sessions" ? "sessions" : "laps"; const exerciseKind = ["timer", "evenLaps", "stepTraining"].includes(String(goal?.exerciseKind || "")) ? String(goal.exerciseKind) : ""; return { id: String(goal?.id || uid("goal")), driverId: String(goal?.driverId || ""), classId: String(goal?.classId || ""), title: String(goal?.title || "").trim(), reward: String(goal?.reward || "").trim(), targetLaps: Math.max(1, Math.round(Number(goal?.targetLaps || 0) || 0)), metric, exerciseKind: metric === "sessions" ? exerciseKind : "", targetSessions: Math.max(1, Math.round(Number(goal?.targetSessions || 0) || 0)), createdAt: String(goal?.createdAt || new Date().toISOString()), claimedAt: goal?.claimedAt ? String(goal.claimedAt) : "", }; }) .filter((goal) => goal.driverId && (goal.metric === "sessions" ? goal.exerciseKind && goal.targetSessions > 0 : goal.targetLaps > 0)) : []; const seenLedgerKeys = new Set(); const ledger = Array.isArray(source.ledger) ? source.ledger .map((entry) => { const timestamp = Math.max(0, Number(entry?.timestamp || 0) || 0); return { id: String(entry?.id || uid("training_lap")), sourceKey: String(entry?.sourceKey || ""), sessionId: String(entry?.sessionId || ""), sessionName: String(entry?.sessionName || "").trim(), eventId: String(entry?.eventId || ""), eventName: String(entry?.eventName || "").trim(), driverId: String(entry?.driverId || ""), sourceId: String(entry?.sourceId || entry?.driverId || ""), excludedFromPace: Boolean(entry?.excludedFromPace), stintBoundary: Boolean(entry?.stintBoundary), timestamp, 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(), }; }) .filter((entry) => { const key = entry.sourceKey || entry.id; if (!entry.driverId || entry.lapMs <= 500 || seenLedgerKeys.has(key)) return false; seenLedgerKeys.add(key); return true; }) .sort((left, right) => left.timestamp - right.timestamp) : []; const seenShareDrivers = new Set(); const shares = Array.isArray(source.shares) ? source.shares .map((share) => ({ driverId: String(share?.driverId || ""), token: String(share?.token || "").trim(), enabled: share?.enabled !== false, createdAt: String(share?.createdAt || new Date().toISOString()), visibility: normalizePublicTrainingVisibility(share?.visibility), })) .filter((share) => { if (!share.driverId || share.token.length < 24 || seenShareDrivers.has(share.driverId)) return false; seenShareDrivers.add(share.driverId); return true; }) : []; const markers = Array.isArray(source.markers) ? source.markers .map((marker) => ({ id: String(marker?.id || uid("training_marker")), driverId: String(marker?.driverId || ""), classId: String(marker?.classId || ""), sessionId: String(marker?.sessionId || ""), timestamp: Math.max(0, Number(marker?.timestamp || 0) || 0), type: ["setup", "tires", "suspension", "car", "note"].includes(String(marker?.type || "").toLowerCase()) ? String(marker.type).toLowerCase() : "setup", note: String(marker?.note || "").trim(), createdAt: String(marker?.createdAt || new Date().toISOString()), })) .filter((marker) => marker.driverId && marker.classId && marker.timestamp > 0) .sort((left, right) => left.timestamp - right.timestamp) : []; const seenEvenLapsConfigs = new Set(); const evenLaps = Array.isArray(source.evenLaps) ? source.evenLaps .map((entry) => ({ id: String(entry?.id || uid("even_laps")), driverId: String(entry?.driverId || ""), classId: String(entry?.classId || ""), targetMs: Math.max(0, Math.round(Number(entry?.targetMs || 0) || 0)), toleranceMs: Math.max(0, Math.round(Number(entry?.toleranceMs || 0) || 0)), lapCount: Math.max(1, Math.round(Number(entry?.lapCount || 0) || 5)), updatedAt: String(entry?.updatedAt || new Date().toISOString()), })) .filter((entry) => { const key = `${entry.driverId}:${entry.classId}`; if (!entry.driverId || !entry.classId || entry.targetMs <= 0 || seenEvenLapsConfigs.has(key)) return false; seenEvenLapsConfigs.add(key); return true; }) : []; const seenStepTrainingConfigs = new Set(); const stepTraining = Array.isArray(source.stepTraining) ? source.stepTraining .map((entry) => ({ id: String(entry?.id || uid("step_training")), driverId: String(entry?.driverId || ""), classId: String(entry?.classId || ""), steps: Array.isArray(entry?.steps) ? entry.steps .map((step) => ({ effort: ["calm", "controlled", "fast"].includes(String(step?.effort || "")) ? String(step.effort) : "calm", lapCount: Math.max(0, Math.round(Number(step?.lapCount || 0) || 0)), })) .filter((step) => step.lapCount > 0) : [], updatedAt: String(entry?.updatedAt || new Date().toISOString()), })) .filter((entry) => { const key = `${entry.driverId}:${entry.classId}`; if (!entry.driverId || !entry.classId || !entry.steps.length || seenStepTrainingConfigs.has(key)) return false; seenStepTrainingConfigs.add(key); return true; }) : []; const seenExerciseSessions = new Set(); const exerciseSessions = Array.isArray(source.exerciseSessions) ? source.exerciseSessions .map((entry) => ({ id: String(entry?.id || uid("exercise_session")), driverId: String(entry?.driverId || ""), classId: String(entry?.classId || ""), kind: ["timer", "evenLaps", "stepTraining"].includes(String(entry?.kind || "")) ? String(entry.kind) : "", startedAt: Math.max(0, Number(entry?.startedAt || 0) || 0), completedAt: String(entry?.completedAt || new Date().toISOString()), summary: entry?.summary && typeof entry.summary === "object" ? entry.summary : {}, })) .filter((entry) => { if (!entry.driverId || !entry.classId || !entry.kind || !entry.startedAt) return false; const key = `${entry.driverId}:${entry.classId}:${entry.kind}:${entry.startedAt}`; if (seenExerciseSessions.has(key)) return false; seenExerciseSessions.add(key); return true; }) .sort((left, right) => right.startedAt - left.startedAt) : []; return { goals, ledger, shares, markers, clubGoal, evenLaps, stepTraining, exerciseSessions }; } function getPassingSourceKey(sessionId, passing, index) { const competitor = String(passing?.competitorKey || passing?.driverId || passing?.transponder || "unknown"); return `${sessionId}:${Number(passing?.timestamp || 0) || 0}:${competitor}:${index}`; } export function syncTrainingLedger(training, state, { uid }) { const normalized = normalizeTrainingState(training, { uid }); const results = state?.resultsBySession && typeof state.resultsBySession === "object" ? state.resultsBySession : {}; const currentSessionIds = new Set(Object.keys(results)); const sessions = new Map((Array.isArray(state?.sessions) ? state.sessions : []).map((session) => [String(session.id), session])); // A session's laps are rebuilt from its results - except laps from before a "Reset data" // (session.resultsResetAt): they're gone from the results but stay training history, so an // Open Practice can be cleared for a new day without losing anyone's stats. const retained = normalized.ledger.filter((entry) => { if (!currentSessionIds.has(entry.sessionId)) return true; const resetAt = Number(sessions.get(entry.sessionId)?.resultsResetAt || 0); return resetAt > 0 && entry.timestamp < resetAt; }); const events = new Map((Array.isArray(state?.events) ? state.events : []).map((event) => [String(event.id), event])); const current = []; Object.entries(results).forEach(([sessionId, result]) => { const session = sessions.get(String(sessionId)); const event = session ? events.get(String(session.eventId || "")) : null; (Array.isArray(result?.passings) ? result.passings : []).forEach((passing, index) => { const driverId = String(passing?.driverId || ""); const lapMs = Math.round(Number(passing?.lapMs || 0) || 0); // A suspect practice lap (a likely shortcut) joins the stats only once it is approved. if (!driverId || passing?.validLap === false || passing?.suspect || lapMs <= 500) return; const timestamp = Math.max(0, Number(passing?.timestamp || 0) || 0); const sourceKey = getPassingSourceKey(sessionId, passing, index); current.push({ id: `training_${sourceKey}`, sourceKey, sessionId: String(sessionId), sessionName: String(session?.name || "").trim(), eventId: String(session?.eventId || ""), eventName: String(event?.name || "").trim(), driverId, sourceId: String(passing?.competitorKey || passing?.carId || passing?.transponder || driverId), excludedFromPace: Boolean(passing?.excludedFromPace || passing?.validationWarning === "above_max_stint"), stintBoundary: Boolean(passing?.stintBoundary || passing?.validationWarning === "above_max_stint"), timestamp, lapMs, recordedAt: timestamp ? new Date(timestamp).toISOString() : new Date().toISOString(), // The layout active when this lap was driven, not when the session started: a club // 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(), }); }); }); // 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. return normalizeTrainingState({ ...normalized, ledger: [...retained, ...current], }, { uid }); } export function getDriverTrainingLaps(state, driverId, classId = "") { const ledger = Array.isArray(state?.training?.ledger) ? state.training.ledger : []; const profileReferences = getTrainingDriverIds(state, driverId, classId); return ledger .filter((entry) => profileReferences.has(String(entry?.driverId || "")) && Number(entry?.lapMs || 0) > 500) .map((entry) => ({ sessionId: String(entry.sessionId || ""), sessionName: String(entry.sessionName || ""), eventName: String(entry.eventName || ""), driverId: String(entry.driverId || ""), sourceId: String(entry.sourceId || entry.driverId || ""), excludedFromPace: Boolean(entry.excludedFromPace), stintBoundary: Boolean(entry.stintBoundary), timestamp: Number(entry.timestamp || 0) || 0, lapMs: Number(entry.lapMs || 0), trackLayoutId: String(entry.trackLayoutId || ""), })) .sort((left, right) => left.timestamp - right.timestamp); } // Every lifetime/commitment stat (total laps ever driven, training days, achievement // badges) intentionally keeps reading the full history via getDriverTrainingLaps above - // a track rebuild doesn't erase how much a driver has practiced. Only pace-comparison // stats (personal best, consistency, the "stable pace" cue's target) should stop blending // laps from a track that no longer exists into today's numbers, so those read this // layout-scoped subset instead. With no track layouts configured, every lap's // trackLayoutId is "" and getTrackLayoutIdAt() also returns "" - so this returns exactly // the same laps as getDriverTrainingLaps, and the feature stays fully inert until used. // `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); if (layout === "all") return laps; const layoutId = layout === "current" || !layout ? getTrackLayoutIdAt(state?.trackLayouts) : layout === "none" ? "" : String(layout); return laps.filter((lap) => lap.trackLayoutId === layoutId); } export function getDriverTrainingLapsForCurrentLayout(state, driverId, classId = "") { return getDriverTrainingLapsForLayout(state, driverId, classId, "current"); } function percentile(values, ratio) { if (!values.length) return 0; const sorted = [...values].sort((left, right) => left - right); const index = Math.min(sorted.length - 1, Math.max(0, Math.round((sorted.length - 1) * ratio))); return sorted[index]; } function average(values) { return values.length ? Math.round(values.reduce((sum, value) => sum + value, 0) / values.length) : 0; } function consistencySpread(values) { const mean = average(values); return mean ? ((percentile(values, 0.9) - percentile(values, 0.1)) / mean) * 100 : 0; } function trimmedAverage(values, trimRatio = 0.1) { if (!values.length) return 0; const sorted = [...values].sort((left, right) => left - right); const trimCount = sorted.length >= 5 ? Math.max(1, Math.floor(sorted.length * trimRatio)) : 0; const kept = trimCount ? sorted.slice(trimCount, sorted.length - trimCount) : sorted; return average(kept); } export function getDriverTrainingMarkers(state, driverId, classId = "") { const profileReferences = getTrainingDriverIds(state, driverId, classId); const normalizedClassId = String(classId || ""); return (Array.isArray(state?.training?.markers) ? state.training.markers : []) .filter((marker) => ( profileReferences.has(String(marker?.driverId || "")) && (!normalizedClassId || String(marker?.classId || "") === normalizedClassId) )) .map((marker) => ({ ...marker })) .sort((left, right) => Number(left.timestamp || 0) - Number(right.timestamp || 0)); } export function buildTrainingPaceBuckets(state, driverId, classId = "", bucketMinutes = 30) { const laps = getDriverTrainingLaps(state, driverId, classId).filter((lap) => !lap.excludedFromPace); const bucketMs = Math.max(5, Number(bucketMinutes || 30)) * 60 * 1000; const buckets = new Map(); laps.forEach((lap) => { const date = new Date(lap.timestamp); const bucketMinutesValue = bucketMs / 60000; const startTs = new Date( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), Math.floor(date.getMinutes() / bucketMinutesValue) * bucketMinutesValue, 0, 0 ).getTime(); const key = String(startTs); const bucket = buckets.get(key) || { startTs, endTs: startTs + bucketMs, laps: [], sessionIds: new Set() }; bucket.laps.push(lap); if (lap.sessionId) bucket.sessionIds.add(lap.sessionId); buckets.set(key, bucket); }); const markers = getDriverTrainingMarkers(state, driverId, classId); return [...buckets.values()] .sort((left, right) => left.startTs - right.startTs) .map((bucket) => { const values = bucket.laps.map((lap) => lap.lapMs); return { startTs: bucket.startTs, endTs: bucket.endTs, lapCount: values.length, paceMs: trimmedAverage(values), medianMs: percentile(values, 0.5), bestLapMs: values.length ? Math.min(...values) : 0, sessionIds: [...bucket.sessionIds], markers: markers.filter((marker) => marker.timestamp >= bucket.startTs && marker.timestamp < bucket.endTs), }; }); } export function buildTrainingWeekdayStats(state, driverId, classId = "") { const groups = Array.from({ length: 7 }, (_, weekday) => ({ weekday, laps: [] })); getDriverTrainingLaps(state, driverId, classId) .filter((lap) => !lap.excludedFromPace) .forEach((lap) => groups[new Date(lap.timestamp).getDay()].laps.push(lap.lapMs)); return groups.map((group) => ({ weekday: group.weekday, lapCount: group.laps.length, paceMs: trimmedAverage(group.laps), bestLapMs: group.laps.length ? Math.min(...group.laps) : 0, })); } export function buildTrainingMarkerComparisons(state, driverId, classId = "", windowMinutes = 30) { const laps = getDriverTrainingLaps(state, driverId, classId).filter((lap) => !lap.excludedFromPace); const windowMs = Math.max(5, Number(windowMinutes || 30)) * 60 * 1000; return getDriverTrainingMarkers(state, driverId, classId).map((marker) => { const comparableLaps = marker.sessionId ? laps.filter((lap) => lap.sessionId === marker.sessionId) : laps; const before = comparableLaps.filter((lap) => lap.timestamp < marker.timestamp && lap.timestamp >= marker.timestamp - windowMs); const after = comparableLaps.filter((lap) => lap.timestamp >= marker.timestamp && lap.timestamp < marker.timestamp + windowMs); const beforePaceMs = before.length >= 3 ? trimmedAverage(before.map((lap) => lap.lapMs)) : 0; const afterPaceMs = after.length >= 3 ? trimmedAverage(after.map((lap) => lap.lapMs)) : 0; return { ...marker, beforeLapCount: before.length, afterLapCount: after.length, beforePaceMs, afterPaceMs, improvementMs: beforePaceMs && afterPaceMs ? beforePaceMs - afterPaceMs : null, }; }); } function getBestConsecutiveAverage(laps, count) { let best = 0; for (let index = 0; index <= laps.length - count; index += 1) { const candidate = average(laps.slice(index, index + count).map((lap) => lap.lapMs)); if (!best || candidate < best) best = candidate; } return best; } function getLongestControlledLapStreak(stints, controlTargetMs) { let longest = 0; (Array.isArray(stints) ? stints : []).forEach((stint) => { let current = 0; (Array.isArray(stint?.laps) ? stint.laps : []).forEach((lap) => { if (lap.excludedFromPace || !controlTargetMs || Number(lap.lapMs || 0) > controlTargetMs) { current = 0; return; } current += 1; longest = Math.max(longest, current); }); }); return longest; } function getTrainingStintMetrics(stint) { const laps = (Array.isArray(stint?.laps) ? stint.laps : []).filter((lap) => !lap.excludedFromPace); const values = laps.map((lap) => Number(lap.lapMs || 0)).filter((lapMs) => lapMs > 500); const medianMs = percentile(values, 0.5); const outlierThresholdMs = medianMs ? medianMs * 1.15 : 0; const outlierLaps = values.filter((lapMs) => outlierThresholdMs && lapMs > outlierThresholdMs).length; const comparisonSize = values.length >= 6 ? Math.max(3, Math.floor(values.length / 3)) : 0; const startPaceMs = comparisonSize ? trimmedAverage(values.slice(0, comparisonSize)) : 0; const endPaceMs = comparisonSize ? trimmedAverage(values.slice(-comparisonSize)) : 0; return { laps, values, outlierLaps, comparisonSize, startPaceMs, endPaceMs, endChangeMs: startPaceMs && endPaceMs ? startPaceMs - endPaceMs : null, strongFinish: Boolean(comparisonSize && endPaceMs <= startPaceMs * 1.01), }; } export function buildTrainingStintAnalysis(state, driverId, classId = "", { layout = "current" } = {}) { // 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)); const rows = stints.map((stint, index) => { const { laps, values, outlierLaps, startPaceMs, endPaceMs, endChangeMs, strongFinish } = getTrainingStintMetrics(stint); return { id: `${stint.sessionId}:${stint.startedAt}:${index}`, number: index + 1, sessionId: stint.sessionId, startedAt: stint.startedAt, endedAt: stint.endedAt, durationMs: stint.durationMs, lapCount: values.length, bestLapMs: values.length ? Math.min(...values) : 0, paceMs: trimmedAverage(values), racePace10Ms: values.length >= 10 ? getBestConsecutiveAverage(laps, 10) : 0, fiveMinuteResult: getBestTrainingDurationResult([stint], 5 * 60 * 1000), mistakes: outlierLaps, mistakePct: values.length ? (outlierLaps / values.length) * 100 : 0, consistencyPct: values.length >= 3 ? consistencySpread(values) : null, startPaceMs, endPaceMs, endChangeMs, strongFinish, insufficient: values.length < 3, }; }); const visibleRows = rows.filter((row) => row.lapCount > 0); visibleRows.forEach((row, index) => { row.number = index + 1; }); const eligible = visibleRows.filter((row) => !row.insufficient); const best = eligible.reduce((current, row) => (!current || row.paceMs < current.paceMs ? row : current), null); return { rows: visibleRows.sort((left, right) => right.startedAt - left.startedAt), best }; } export function buildTrainingAchievements(stats) { const source = stats && typeof stats === "object" ? stats : {}; const definitions = [ ["first_session", Number(source.totalSessions || 0), 1], ["laps_100", Number(source.totalLaps || 0), 100], ["laps_250", Number(source.totalLaps || 0), 250], ["laps_500", Number(source.totalLaps || 0), 500], ["laps_1000", Number(source.totalLaps || 0), 1000], ["laps_1500", Number(source.totalLaps || 0), 1500], ["sessions_5", Number(source.totalSessions || 0), 5], ["days_3", Number(source.trainingDays || 0), 3], ["days_10", Number(source.trainingDays || 0), 10], ["controlled_5", Number(source.controlledLapStreak || 0), 5], ["controlled_10", Number(source.controlledLapStreak || 0), 10], ["five_minute", source.bestFiveMinuteResult ? 1 : 0, 1], ["five_minutes_3", Number(source.completedFiveMinuteStints || 0), 3], ["consistency_5", source.recentLapCount >= 30 && source.consistencySpreadPct <= 5 ? 1 : 0, 1], ["strong_finish", Number(source.strongFinishStints || 0), 1], ["clean_five_minute", Number(source.cleanFiveMinuteStints || 0), 1], ["pace_gain", source.trendSampleReady && source.averageTrendMs > 0 ? 1 : 0, 1], ]; return definitions.map(([id, current, target]) => ({ id, current: Math.max(0, current), target, percent: Math.min(100, Math.max(0, (current / target) * 100)), unlocked: current >= target, })); } function getLocalDayKey(timestamp) { const date = new Date(Number(timestamp || 0)); if (Number.isNaN(date.getTime())) return "unknown"; const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, "0"); const day = String(date.getDate()).padStart(2, "0"); return `${year}-${month}-${day}`; } 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 }; current.laps += 1; current.totalMs += lap.lapMs; current.bestLapMs = current.bestLapMs ? Math.min(current.bestLapMs, lap.lapMs) : lap.lapMs; current.latestTimestamp = Math.max(current.latestTimestamp, lap.timestamp); byDay.set(key, current); }); return [...byDay.values()] .map((day) => ({ ...day, averageLapMs: day.laps ? Math.round(day.totalMs / day.laps) : 0 })) .sort((left, right) => right.latestTimestamp - left.latestTimestamp); } export function getControlledLapStreak(lapTimes, controlTargetMs) { let streak = 0; for (let index = lapTimes.length - 1; index >= 0; index -= 1) { if (!controlTargetMs || lapTimes[index] > controlTargetMs) break; streak += 1; } return streak; } export function splitTrainingStints(laps, breakThresholdMs = 2 * 60 * 1000) { const normalized = (Array.isArray(laps) ? laps : []) .filter((lap) => Number(lap?.lapMs || 0) > 500 && Number(lap?.timestamp || 0) > 0) .map((lap) => ({ ...lap, sessionId: String(lap.sessionId || ""), sourceId: String(lap.sourceId || lap.driverId || lap.competitorKey || lap.transponder || "default"), timestamp: Number(lap.timestamp), lapMs: Number(lap.lapMs), })); const streams = new Map(); normalized.forEach((lap) => { const streamKey = `${lap.sessionId}:${lap.sourceId}`; if (!streams.has(streamKey)) streams.set(streamKey, []); streams.get(streamKey).push(lap); }); const stints = []; streams.forEach((streamLaps) => { const sorted = streamLaps.sort((left, right) => left.timestamp - right.timestamp); let currentStint = null; sorted.forEach((lap) => { const previousLap = currentStint?.laps.at(-1); const lapStartedAt = Math.max(0, lap.timestamp - lap.lapMs); const breakMs = previousLap ? Math.max(0, lap.timestamp - previousLap.timestamp) : 0; const detectedBreak = Boolean(previousLap && breakMs > breakThresholdMs); const explicitBoundary = Boolean(lap.stintBoundary); const startsNewStint = !currentStint || detectedBreak || explicitBoundary; const normalizedLap = { ...lap, excludedFromPace: Boolean(lap.excludedFromPace || explicitBoundary || (detectedBreak && lap.lapMs > breakThresholdMs)), stintBoundary: Boolean(explicitBoundary || detectedBreak), }; if (startsNewStint) { const boundaryLap = Boolean(normalizedLap.excludedFromPace && (explicitBoundary || detectedBreak)); currentStint = { sessionId: lap.sessionId, sourceId: lap.sourceId, startedAt: boundaryLap ? lap.timestamp : lapStartedAt, endedAt: lap.timestamp, durationMs: boundaryLap ? 0 : lap.lapMs, laps: [normalizedLap], }; stints.push(currentStint); return; } currentStint.laps.push(normalizedLap); currentStint.endedAt = lap.timestamp; currentStint.durationMs = Math.max(0, currentStint.endedAt - currentStint.startedAt); }); }); return stints.sort((left, right) => left.startedAt - right.startedAt); } export function getBestConsecutiveTrainingLaps(stints, lapCount = 3) { const count = Math.max(1, Math.round(Number(lapCount || 1) || 1)); let best = null; (Array.isArray(stints) ? stints : []).forEach((stint) => { const paceLaps = stint.laps.filter((lap) => !lap.excludedFromPace); for (let index = 0; index <= paceLaps.length - count; index += 1) { const laps = paceLaps.slice(index, index + count); const totalMs = laps.reduce((sum, lap) => sum + lap.lapMs, 0); const candidate = { lapCount: count, totalMs, averageLapMs: Math.round(totalMs / count), startedAt: Math.max(0, laps[0].timestamp - laps[0].lapMs), endedAt: laps.at(-1).timestamp, sessionId: String(stint.sessionId || ""), }; if (!best || candidate.totalMs < best.totalMs) best = candidate; } }); return best; } export function getBestTrainingDurationResult(stints, targetMs = 5 * 60 * 1000) { const target = Math.max(1, Math.round(Number(targetMs || 0) || 0)); let best = null; (Array.isArray(stints) ? stints : []).forEach((stint) => { const paceLaps = stint.laps.filter((lap) => !lap.excludedFromPace); for (let startIndex = 0; startIndex < paceLaps.length; startIndex += 1) { const firstLap = paceLaps[startIndex]; const startedAt = Math.max(0, firstLap.timestamp - firstLap.lapMs); const cutoffAt = startedAt + target; const counted = []; for (let index = startIndex; index < paceLaps.length; index += 1) { const lap = paceLaps[index]; const lapStartedAt = Math.max(0, lap.timestamp - lap.lapMs); if (lapStartedAt >= cutoffAt) break; counted.push(lap); } const lastLap = counted.at(-1); if (!lastLap || lastLap.timestamp < cutoffAt) continue; const totalMs = Math.max(0, lastLap.timestamp - startedAt); if (totalMs > target + lastLap.lapMs) continue; const lapCount = counted.length; const candidate = { targetMs: target, lapCount, totalMs, averageLapMs: lapCount ? Math.round(counted.reduce((sum, lap) => sum + lap.lapMs, 0) / lapCount) : 0, startedAt, endedAt: lastLap.timestamp, sessionId: String(stint.sessionId || ""), }; if (!best || candidate.lapCount > best.lapCount || (candidate.lapCount === best.lapCount && candidate.totalMs < best.totalMs)) { best = candidate; } } }); return best; } export function buildDriverTrainingStats(state, driverId, classId = "", { layout = "current" } = {}) { // 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 historyPaceLaps = laps.filter((lap) => !lap.excludedFromPace); const paceLaps = layoutLaps.filter((lap) => !lap.excludedFromPace); const lapTimes = paceLaps.map((lap) => lap.lapMs); const recentLapTimes = lapTimes.slice(-30); const previousWindowLapTimes = lapTimes.slice(Math.max(0, lapTimes.length - 60), Math.max(0, lapTimes.length - 30)); const earlierLapTimes = lapTimes.slice(0, Math.max(0, lapTimes.length - recentLapTimes.length)); const totalLaps = laps.length; const bestLapMs = lapTimes.length ? Math.min(...lapTimes) : 0; const averageLapMs = average(lapTimes); const recentAverageMs = average(recentLapTimes); const previousRecentAverageMs = average(previousWindowLapTimes); const consistencySpreadPct = consistencySpread(recentLapTimes); const previousConsistencySpreadPct = consistencySpread(previousWindowLapTimes); const trendSampleReady = recentLapTimes.length >= 10 && previousWindowLapTimes.length >= 10; const previousBestMs = earlierLapTimes.length ? Math.min(...earlierLapTimes) : 0; const recentBestMs = recentLapTimes.length ? Math.min(...recentLapTimes) : 0; const personalBestGainMs = previousBestMs && recentBestMs ? Math.max(0, previousBestMs - recentBestMs) : 0; const controlZoneMinMs = bestLapMs; const controlTargetMs = bestLapMs ? Math.round(bestLapMs * 1.08) : 0; const dailySummaries = buildDailySummaries(historyPaceLaps); const stints = splitTrainingStints(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; const cleanFiveMinuteStints = stintMetrics.filter(({ stint, outlierLaps }) => !outlierLaps && getBestTrainingDurationResult([stint], 5 * 60 * 1000)).length; const strongFinishStints = stintMetrics.filter((metrics) => metrics.strongFinish).length; const outlierLaps = stintMetrics.reduce((sum, metrics) => sum + metrics.outlierLaps, 0); const bestThreeConsecutive = getBestConsecutiveTrainingLaps(stints, 3); 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 todayStintMetrics = todayStints.map((stint) => ({ stint, ...getTrainingStintMetrics(stint) })); const todayLapTimes = todayLaps.filter((lap) => !lap.excludedFromPace).map((lap) => lap.lapMs); const stats = { totalLaps, totalSessions: new Set(laps.map((lap) => lap.sessionId)).size, trainingDays: dailySummaries.length, bestLapMs, averageLapMs, recentAverageMs, previousRecentAverageMs, averageTrendMs: trendSampleReady ? previousRecentAverageMs - recentAverageMs : 0, recentBestMs, previousBestMs, personalBestGainMs, controlZoneMinMs, controlZoneMaxMs: controlTargetMs, controlledLapStreak, outlierLaps, strongFinishStints, cleanFiveMinuteStints, todayLaps: todayLaps.length, todayBestLapMs: todayLapTimes.length ? Math.min(...todayLapTimes) : 0, todayAverageLapMs: average(todayLapTimes), todayControlledLapStreak: getLongestControlledLapStreak(todayStints, controlTargetMs), todayOutlierLaps: todayStintMetrics.reduce((sum, metrics) => sum + metrics.outlierLaps, 0), todayStrongFinishStints: todayStintMetrics.filter((metrics) => metrics.strongFinish).length, todayCompletedFiveMinuteStints: todayStints.filter((stint) => getBestTrainingDurationResult([stint], 5 * 60 * 1000)).length, todayCleanFiveMinuteStints: todayStintMetrics.filter(({ stint, outlierLaps: count }) => !count && getBestTrainingDurationResult([stint], 5 * 60 * 1000)).length, consistencySpreadPct, previousConsistencySpreadPct, consistencyTrendPct: trendSampleReady ? previousConsistencySpreadPct - consistencySpreadPct : 0, trendSampleReady, recentLapCount: recentLapTimes.length, lastLapAt: laps.at(-1)?.timestamp || 0, dailySummaries, stintCount: stints.length, completedFiveMinuteStints, bestThreeConsecutive, bestFiveMinuteResult, }; return { ...stats, achievements: buildTrainingAchievements(stats) }; } export function buildDriverTimingChannelStats(state, driverId, classId = "") { const profileReferences = getTrainingDriverIds(state, driverId, classId); const sessions = new Map((Array.isArray(state?.sessions) ? state.sessions : []).map((session) => [String(session.id || ""), session])); const events = new Map((Array.isArray(state?.events) ? state.events : []).map((event) => [String(event.id || ""), event])); const splits = []; const pitStops = []; Object.entries(state?.resultsBySession || {}).forEach(([sessionId, result]) => { const session = sessions.get(String(sessionId)); const event = session ? events.get(String(session.eventId || "")) : null; (Array.isArray(result?.splits) ? result.splits : []).forEach((split) => { if (!profileReferences.has(String(split?.driverId || "")) || Number(split?.splitMs || 0) <= 0) return; splits.push({ ...split, sessionId: String(sessionId), sessionName: String(session?.name || ""), eventName: String(event?.name || ""), splitMs: Math.round(Number(split.splitMs)), }); }); (Array.isArray(result?.pitStops) ? result.pitStops : []).forEach((stop) => { if (!profileReferences.has(String(stop?.driverId || "")) || Number(stop?.pitStopMs || 0) <= 0) return; pitStops.push({ ...stop, sessionId: String(sessionId), sessionName: String(session?.name || ""), eventName: String(event?.name || ""), pitStopMs: Math.round(Number(stop.pitStopMs)), }); }); }); splits.sort((left, right) => Number(left.timestamp || 0) - Number(right.timestamp || 0)); pitStops.sort((left, right) => Number(left.enteredAt || 0) - Number(right.enteredAt || 0)); const splitTimes = splits.map((split) => split.splitMs); const pitTimes = pitStops.map((stop) => stop.pitStopMs); let runningBestSplitMs = 0; let latestSplitGainMs = 0; let latestSplitGainAt = 0; splits.forEach((split) => { if (runningBestSplitMs && split.splitMs < runningBestSplitMs) { latestSplitGainMs = runningBestSplitMs - split.splitMs; latestSplitGainAt = Number(split.timestamp || 0); } if (!runningBestSplitMs || split.splitMs < runningBestSplitMs) runningBestSplitMs = split.splitMs; }); return { splitCount: splits.length, splitSessions: new Set(splits.map((split) => split.sessionId)).size, bestSplitMs: splitTimes.length ? Math.min(...splitTimes) : 0, averageSplitMs: splitTimes.length ? Math.round(splitTimes.reduce((sum, value) => sum + value, 0) / splitTimes.length) : 0, lastSplitMs: splitTimes.at(-1) || 0, latestSplitGainMs, latestSplitGainAt, pitStopCount: pitStops.length, pitSessions: new Set(pitStops.map((stop) => stop.sessionId)).size, totalPitMs: pitTimes.reduce((sum, value) => sum + value, 0), averagePitStopMs: pitTimes.length ? Math.round(pitTimes.reduce((sum, value) => sum + value, 0) / pitTimes.length) : 0, bestPitStopMs: pitTimes.length ? Math.min(...pitTimes) : 0, longestPitStopMs: pitTimes.length ? Math.max(...pitTimes) : 0, recentPitStops: pitStops.slice(-10).reverse(), }; } function getActivePracticeLaps(state, driverId, classId) { const session = (Array.isArray(state?.sessions) ? state.sessions : []) .find((item) => String(item?.id || "") === String(state?.activeSessionId || "")); const practiceTypes = new Set(["open_practice", "free_practice", "practice"]); if (!session || session.status !== "running" || !practiceTypes.has(String(session.type || "").toLowerCase())) return null; const result = state?.resultsBySession?.[session.id]; const startedAt = Math.max(0, Number(session.startedAt || 0) || 0); const profileReferences = getTrainingDriverIds(state, driverId, classId); const laps = (Array.isArray(result?.passings) ? result.passings : []) .filter((passing) => ( profileReferences.has(String(passing?.driverId || "")) && passing?.validLap !== false && Number(passing?.lapMs || 0) > 500 && (!startedAt || Number(passing?.timestamp || 0) >= startedAt) )) .map((passing) => ({ sessionId: String(session.id || ""), sourceId: String(passing.competitorKey || passing.carId || passing.transponder || passing.driverId || "default"), timestamp: Math.max(0, Number(passing.timestamp || 0) || 0), lapMs: Math.round(Number(passing.lapMs || 0) || 0), excludedFromPace: Boolean(passing.excludedFromPace || passing.validationWarning === "above_max_stint"), stintBoundary: Boolean(passing.stintBoundary || passing.validationWarning === "above_max_stint"), })) .sort((left, right) => left.timestamp - right.timestamp); return { session, startedAt, laps }; } export function buildDriverActivePracticeStats(state, driverId, nowTs = Date.now(), classId = "") { const active = getActivePracticeLaps(state, driverId, classId); if (!active) return null; const { session, startedAt, laps } = active; const paceLapTimes = laps.filter((lap) => !lap.excludedFromPace).map((lap) => lap.lapMs); const bestLapMs = paceLapTimes.length ? Math.min(...paceLapTimes) : 0; const controlZoneMaxMs = bestLapMs ? Math.round(bestLapMs * 1.08) : 0; const activeStints = splitTrainingStints(laps); return { sessionId: String(session.id || ""), sessionName: String(session.name || "").trim(), startedAt, elapsedMs: startedAt ? Math.max(0, Number(nowTs || 0) - startedAt) : 0, laps: laps.length, bestLapMs, averageLapMs: average(paceLapTimes), lastLapMs: laps.at(-1)?.lapMs || 0, controlZoneMinMs: bestLapMs, controlZoneMaxMs, controlledLapStreak: getLongestControlledLapStreak(activeStints, controlZoneMaxMs), }; } // "Jämna varv" (even laps): a driver-configured target lap time and tolerance, run live // inside an already-active Open Practice session. Tolerance is +/- around the target lap // time (not the spread between the streak's fastest and slowest lap) - decided because // it's simpler to understand and to show live, and matches how a beginner already thinks // about "hit the target". A lap outside tolerance, or one excluded from pace (pit/reset), // ends the current streak but never erases the best streak already reached today. export function buildEvenLapsProgress(state, driverId, classId, config, nowTs = Date.now()) { const targetMs = Math.round(Number(config?.targetMs || 0)); const toleranceMs = Math.round(Number(config?.toleranceMs || 0)); const lapCount = Math.max(1, Math.round(Number(config?.lapCount || 0) || 0)); if (!(targetMs > 0) || !(toleranceMs >= 0)) return null; const withinTolerance = (lapMs) => Math.abs(lapMs - targetMs) <= toleranceMs; const longestStreak = (lapTimes) => { let longest = 0; let current = 0; for (const lap of lapTimes) { if (!lap.excludedFromPace && withinTolerance(lap.lapMs)) { current += 1; longest = Math.max(longest, current); } else { current = 0; } } return longest; }; const active = getActivePracticeLaps(state, driverId, classId); const liveLaps = active?.laps || []; let currentStreak = 0; for (let index = liveLaps.length - 1; index >= 0; index -= 1) { if (!liveLaps[index].excludedFromPace && withinTolerance(liveLaps[index].lapMs)) currentStreak += 1; else break; } const dayStart = new Date(nowTs); dayStart.setHours(0, 0, 0, 0); const profileReferences = getTrainingDriverIds(state, driverId, classId); const ledgerToday = (Array.isArray(state?.training?.ledger) ? state.training.ledger : []) .filter((entry) => profileReferences.has(String(entry?.driverId || "")) && Number(entry?.timestamp || 0) >= dayStart.getTime()) .map((entry) => ({ timestamp: Number(entry.timestamp || 0), lapMs: Number(entry.lapMs || 0), excludedFromPace: Boolean(entry.excludedFromPace) })); const seen = new Set(); const todayLaps = [...ledgerToday, ...liveLaps] .sort((left, right) => left.timestamp - right.timestamp) .filter((lap) => { const key = `${lap.timestamp}:${lap.lapMs}`; if (seen.has(key)) return false; seen.add(key); return true; }); const bestStreakToday = Math.max(longestStreak(todayLaps), currentStreak); const lastLap = liveLaps.at(-1) || null; return { active: Boolean(active), targetMs, toleranceMs, lapCount, currentStreak, bestStreakToday, lastLapMs: lastLap?.lapMs ?? null, lastLapWithinTolerance: lastLap ? !lastLap.excludedFromPace && withinTolerance(lastLap.lapMs) : null, }; } const STEP_TRAINING_EFFORTS = ["calm", "controlled", "fast"]; // "Stegträning" (step training): a driver-configured sequence of steps (lap count plus a // perceived-effort instruction - calm/controlled/fast), run live inside an already-active // Open Practice session. Effort is guidance shown to the driver, never an enforced lap-time // target: there is no reliable way to measure how hard a driver is actually pushing. When // the config repeats "controlled" (the classic calm/controlled/fast/controlled/calm shape), // the first and last controlled steps are compared afterward as a neutral pace difference, // never automatically labeled as fatigue. export function buildStepTrainingProgress(state, driverId, classId, config, nowTs = Date.now()) { const steps = Array.isArray(config?.steps) ? config.steps .map((step) => ({ effort: STEP_TRAINING_EFFORTS.includes(String(step?.effort || "")) ? String(step.effort) : "calm", lapCount: Math.max(0, Math.round(Number(step?.lapCount || 0) || 0)), })) .filter((step) => step.lapCount > 0) : []; if (!steps.length) return null; const active = getActivePracticeLaps(state, driverId, classId); const liveLaps = active?.laps || []; const totalLaps = steps.reduce((sum, step) => sum + step.lapCount, 0); let cursor = 0; const stepStates = steps.map((step, index) => { const stepLaps = liveLaps.slice(cursor, cursor + step.lapCount); cursor += step.lapCount; const paceValues = stepLaps.filter((lap) => !lap.excludedFromPace).map((lap) => lap.lapMs); return { index, effort: step.effort, lapCount: step.lapCount, lapsCompleted: stepLaps.length, done: stepLaps.length >= step.lapCount, averageLapMs: paceValues.length ? Math.round(paceValues.reduce((sum, value) => sum + value, 0) / paceValues.length) : null, }; }); const complete = liveLaps.length >= totalLaps; const currentStepIndex = complete ? steps.length - 1 : stepStates.findIndex((step) => !step.done); const currentStepState = stepStates[currentStepIndex] || null; const controlledSteps = stepStates.filter((step) => step.effort === "controlled" && step.averageLapMs != null); const controlledComparison = controlledSteps.length >= 2 ? { firstAvgMs: controlledSteps[0].averageLapMs, lastAvgMs: controlledSteps.at(-1).averageLapMs, diffMs: controlledSteps.at(-1).averageLapMs - controlledSteps[0].averageLapMs, } : null; return { active: Boolean(active), totalSteps: steps.length, totalLaps, completedLaps: Math.min(liveLaps.length, totalLaps), complete, currentStepIndex, currentStep: currentStepState && { index: currentStepState.index, effort: currentStepState.effort, lapCount: currentStepState.lapCount, lapsCompleted: currentStepState.lapsCompleted, lapsRemaining: Math.max(0, currentStepState.lapCount - currentStepState.lapsCompleted), }, steps: stepStates, controlledComparison, }; } export function buildTrainingRecommendation(stats) { if (!stats || stats.totalLaps < 10) { return { level: "baseline", titleKey: "training.plan_baseline_title", bodyKey: "training.plan_baseline_body", targetLapMs: 0, }; } if (stats.recentLapCount >= 10 && stats.consistencySpreadPct > 8) { return { level: "consistency", titleKey: "training.plan_consistency_title", bodyKey: "training.plan_consistency_body", targetLapMs: Math.round(stats.bestLapMs * 1.08), }; } return { level: "progression", titleKey: "training.plan_progression_title", bodyKey: "training.plan_progression_body", targetLapMs: Math.round(stats.bestLapMs * 1.05), }; } // Goals and the club goal share this same {currentLaps, targetLaps, ...} shape whether they // track laps or completed guided-exercise sessions, so every existing progress-bar/reward // renderer keeps working unchanged - callers branch on goal.metric only to pick the right // label ("laps" vs "sessions"), never to reshape this result. export function countExerciseSessions(exerciseSessions, { driverId = "", classId = "", kind = "" } = {}) { return (Array.isArray(exerciseSessions) ? exerciseSessions : []).filter((entry) => (!driverId || entry.driverId === driverId) && (!classId || entry.classId === classId) && (!kind || entry.kind === kind) ).length; } // Admin goals store driverId as the *profile* id (see the "training-goal-form" submit handler // in training_views.js), the same value buildDriverTrainingStats resolves through // getTrainingDriverIds - but exerciseSessions store the specific per-class driver row id // (whichever the mobile link's completion request resolved to), the same as ledger entries do. // This bridges the two the same way buildDriverTrainingStats already does for laps. export function countDriverExerciseSessions(state, driverId, classId, kind) { const driverIds = getTrainingDriverIds(state, driverId, classId); return (Array.isArray(state?.training?.exerciseSessions) ? state.training.exerciseSessions : []) .filter((entry) => driverIds.has(String(entry?.driverId || "")) && String(entry?.classId || "") === String(classId || "") && entry?.kind === kind) .length; } export function getTrainingGoalProgress(goal, stats, exerciseSessionCount = 0) { if (goal?.metric === "sessions") { const targetSessions = Math.max(1, Number(goal?.targetSessions || 1)); const currentSessions = Math.max(0, Number(exerciseSessionCount || 0)); return { currentLaps: currentSessions, targetLaps: targetSessions, remainingLaps: Math.max(0, targetSessions - currentSessions), percent: Math.min(100, Math.max(0, (currentSessions / targetSessions) * 100)), reached: currentSessions >= targetSessions, }; } const targetLaps = Math.max(1, Number(goal?.targetLaps || 1)); const currentLaps = Math.max(0, Number(stats?.totalLaps || 0)); return { currentLaps, targetLaps, remainingLaps: Math.max(0, targetLaps - currentLaps), percent: Math.min(100, Math.max(0, (currentLaps / targetLaps) * 100)), reached: currentLaps >= targetLaps, }; } export function getNextTrainingMilestone(stats) { const currentLaps = Math.max(0, Number(stats?.totalLaps || 0)); const presets = [100, 250, 500, 1000, 1500, 2500, 5000]; const targetLaps = presets.find((target) => target > currentLaps) || (Math.floor(currentLaps / 1000) + 1) * 1000; return getTrainingGoalProgress({ targetLaps }, stats); } export function buildTrainingMissions(stats) { const source = stats && typeof stats === "object" ? stats : {}; const definitions = [ ["laps_today", Number(source.todayLaps || 0), 20], ["controlled_today", Number(source.todayControlledLapStreak || 0), 5], ["five_minute_today", Number(source.todayCompletedFiveMinuteStints || 0), 1], ]; return definitions.map(([id, current, target]) => ({ id, current: Math.max(0, current), target, percent: Math.min(100, Math.max(0, (current / target) * 100)), completed: current >= target, })); } export function buildTrainingHighlights(stats) { const source = stats && typeof stats === "object" ? stats : {}; const highlights = []; if (source.todayLaps > 0) highlights.push({ id: "today_laps", value: Number(source.todayLaps) }); if (source.personalBestGainMs > 0) highlights.push({ id: "personal_best", value: Number(source.personalBestGainMs) }); if (source.latestSplitGainMs > 0) highlights.push({ id: "sector_gain", value: Number(source.latestSplitGainMs) }); if (source.todayStrongFinishStints > 0) highlights.push({ id: "strong_finish", value: Number(source.todayStrongFinishStints) }); if (source.todayCleanFiveMinuteStints > 0) highlights.push({ id: "clean_five_minute", value: Number(source.todayCleanFiveMinuteStints) }); if (source.trendSampleReady && source.averageTrendMs > 0) highlights.push({ id: "pace_gain", value: Number(source.averageTrendMs) }); if (source.trendSampleReady && source.consistencyTrendPct > 0.1) highlights.push({ id: "consistency_gain", value: Number(source.consistencyTrendPct) }); if (source.todayControlledLapStreak >= 5) highlights.push({ id: "controlled_streak", value: Number(source.todayControlledLapStreak) }); if (source.todayCompletedFiveMinuteStints > 0) highlights.push({ id: "five_minute", value: Number(source.todayCompletedFiveMinuteStints) }); if (!highlights.length && source.totalLaps > 0) highlights.push({ id: "keep_building", value: Number(source.totalLaps) }); if (!highlights.length) highlights.push({ id: "ready", value: 0 }); return highlights.slice(0, 3); } export function getClubTrainingGoalProgress(training) { const goal = training?.clubGoal && typeof training.clubGoal === "object" ? training.clubGoal : null; if (!goal) return null; if (goal.metric === "sessions") { if (!(Number(goal.targetSessions || 0) > 0) || !goal.exerciseKind) return null; const totalSessions = countExerciseSessions(training?.exerciseSessions, { kind: goal.exerciseKind }); const currentSessions = Math.max(0, totalSessions - Math.max(0, Number(goal.baselineSessions || 0))); const targetSessions = Math.max(1, Number(goal.targetSessions || 1)); return { currentLaps: currentSessions, targetLaps: targetSessions, remainingLaps: Math.max(0, targetSessions - currentSessions), percent: Math.min(100, Math.max(0, (currentSessions / targetSessions) * 100)), reached: currentSessions >= targetSessions, }; } if (!(Number(goal.targetLaps || 0) > 0)) return null; const totalLaps = Array.isArray(training?.ledger) ? training.ledger.length : 0; const currentLaps = Math.max(0, totalLaps - Math.max(0, Number(goal.baselineLaps || 0))); const targetLaps = Math.max(1, Number(goal.targetLaps || 1)); return { currentLaps, targetLaps, remainingLaps: Math.max(0, targetLaps - currentLaps), percent: Math.min(100, Math.max(0, (currentLaps / targetLaps) * 100)), reached: currentLaps >= targetLaps, }; }