// The race day as one schedule: every race session of every class on one date, in one running // order with planned times, plus what the autopilot should do next. Pure logic - the panel is // in day_schedule_view.js and the runner in app.js. import { applyManualOrder, orderSessionsForRunning, parseQualifyingHeatName } from "./event_race_logic.js"; export const DEFAULT_DAY_GAP_MIN = 3; export const DEFAULT_CALL_MIN = 10; // One plan per date: { date, startAt, gapMin, roundGapMin, finalsGapMin, breaks, callMin, // sessionOrder, autopilot, pausedAt }. // gapMin = break between heats of one round; roundGapMin = between rounds (practice -> qualifying, // round 1 -> round 2, final leg 1 -> leg 2); finalsGapMin = before the finals (lunch). Empty // round / finals gaps fall back to the one before. breaks = { sessionId: minutes } of extra // break before that heat. breakFrom / breakTo = a break at fixed clock times ("12:00"-"13:00", // lunch): no heat starts or runs inside it. callMin = how long before its start a heat is called. const clockTime = (value) => { const match = String(value || "").trim().match(/^(\d{1,2}):(\d{2})$/); return match && Number(match[1]) < 24 && Number(match[2]) < 60 ? `${match[1].padStart(2, "0")}:${match[2]}` : null; }; // The fixed-time break of a day as timestamps, or null. export function fixedBreakWindow(day) { const plan = normalizeRaceDay(day || {}); if (!plan.breakFrom || !/^\d{4}-\d{2}-\d{2}$/.test(plan.date)) return null; const start = new Date(`${plan.date}T${plan.breakFrom}:00`).getTime(); const end = new Date(`${plan.date}T${plan.breakTo}:00`).getTime(); return Number.isFinite(start) && Number.isFinite(end) && end > start ? { start, end, from: plan.breakFrom, to: plan.breakTo, label: plan.breakLabel } : null; } const optionalMin = (value) => (value === null || value === undefined || value === "" || !Number.isFinite(Number(value)) ? null : Math.max(0, Number(value))); export function normalizeRaceDay(day = {}) { const breaks = Object.fromEntries(Object.entries(day.breaks && typeof day.breaks === "object" ? day.breaks : {}) .map(([id, min]) => [String(id), Math.max(0, Math.min(600, Number(min) || 0))]).filter(([id, min]) => id && min > 0)); return { date: String(day.date || ""), startAt: Number(day.startAt) > 0 ? Number(day.startAt) : null, gapMin: Number.isFinite(Number(day.gapMin)) && day.gapMin !== null && day.gapMin !== "" ? Math.max(0, Number(day.gapMin)) : DEFAULT_DAY_GAP_MIN, roundGapMin: optionalMin(day.roundGapMin), finalsGapMin: optionalMin(day.finalsGapMin), breaks, ...(() => { const from = clockTime(day.breakFrom); const to = clockTime(day.breakTo); return from && to && to > from ? { breakFrom: from, breakTo: to, breakLabel: String(day.breakLabel || "").trim().slice(0, 40) } : { breakFrom: null, breakTo: null, breakLabel: "" }; })(), callMin: Number(day.callMin) > 0 ? Math.min(60, Number(day.callMin)) : DEFAULT_CALL_MIN, sessionOrder: [...new Set((Array.isArray(day.sessionOrder) ? day.sessionOrder : []).map(String).filter(Boolean))], autopilot: day.autopilot === true, pausedAt: Number(day.pausedAt) > 0 ? Number(day.pausedAt) : null, }; } export function normalizeRaceDays(list) { const byDate = new Map(); (Array.isArray(list) ? list : []).map(normalizeRaceDay).filter((day) => /^\d{4}-\d{2}-\d{2}$/.test(day.date)).forEach((day) => byDate.set(day.date, day)); return [...byDate.values()]; } export function getRaceDay(raceDays, date) { return (raceDays || []).find((day) => day.date === date) || normalizeRaceDay({ date }); } // Race Day's first start is the only start time. A race that got one in Race setup before the // two were joined lends it to its day while the day has none of its own. const localDate = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; }; export function withRaceSetupStart(day, events = []) { if (!day || Number(day.startAt) > 0) return day; const legacy = (events || []) .filter((event) => event.date === day.date) .map((event) => Number(event.raceConfig?.scheduleStartAt || 0)) .filter((ms) => ms > 0 && localDate(ms) === day.date) .sort((a, b) => a - b)[0]; return legacy ? { ...day, startAt: legacy } : day; } // One race's part of the day schedule, in the shape Race setup and the printed start lists use. export function eventScheduleFromDayRows(rows, eventId) { return (rows || []).filter((row) => row.session.eventId === eventId).map((row) => ({ sessionId: row.session.id, plannedStart: row.start, plannedEnd: row.end, actualStart: Number(row.session.startedAt || 0) || null, actualEnd: row.state === "done" ? Number(row.session.endedAt || 0) || null : null, delayed: row.delayed, })); } // Stores a changed plan for its date; returns the new list. export function upsertRaceDay(raceDays, day) { const next = normalizeRaceDay(day); return [...(raceDays || []).filter((item) => item.date !== next.date), next]; } const sessionDurationMs = (session) => Math.max(1, Number(session.durationMin || 0)) * 60000 + Math.max(0, Number(session.followUpSec || 0)) * 1000; const isDone = (session) => ["finished", "stopped"].includes(session.status); const isLive = (session) => ["running", "paused"].includes(session.status); // Where a session sits in the day: practice, then qualifying round by round, then finals leg // by leg (lowest final first). Classes take turns within each step. function dayStepKey(session) { if (["practice", "free_practice", "open_practice"].includes(session.type)) return [0, 0, 0]; if (session.type === "final") { const match = String(session.name || "").match(/^([A-Z])\b.*?(\d+)\s*$/); return match ? [2, Number(match[2]), -match[1].charCodeAt(0)] : [2, 0, 0]; } return [1, parseQualifyingHeatName(session.name)?.round || 0, 0]; } // The break before `session` when `previous` ran just before it (minutes). export function breakBeforeMin(previous, session, day) { const plan = normalizeRaceDay(day || {}); const extra = plan.breaks[session?.id] || 0; if (!previous) return extra; const [prevType, prevRound] = dayStepKey(previous); const [type, round] = dayStepKey(session); const roundGap = plan.roundGapMin ?? plan.gapMin; const gap = type === 2 && prevType !== 2 ? plan.finalsGapMin ?? roundGap : type !== prevType || round !== prevRound ? roundGap : plan.gapMin; return gap + extra; } const compareKeys = (a, b) => a.reduce((diff, value, i) => diff || value - b[i], 0); // The race events of a date (one per class) and their race sessions, in the day's running order. export function orderDaySessions({ events = [], sessions = [], date, manualOrder = [] }) { const dayEvents = events.filter((event) => (event.mode === "race" || Boolean(event.sponsor)) && event.date === date) .sort((a, b) => String(a.name || "").localeCompare(String(b.name || ""), undefined, { numeric: true })); const items = dayEvents.flatMap((event, eventIndex) => { const own = orderSessionsForRunning(sessions.filter((session) => session.eventId === event.id && session.mode === "race"), event.sessionOrder); // A step never goes back within a class, so a class's own ▲▼ order is kept. let step = [0, 0, 0]; return own.map((session, position) => { const key = dayStepKey(session); if (compareKeys(key, step) > 0) step = key; return { session, event, key: [...step, eventIndex, position] }; }); }); const auto = items.sort((a, b) => compareKeys(a.key, b.key)).map((item) => item.session); return applyManualOrder(auto, manualOrder); } export function moveInDayOrder(ordered, sessionId, step) { const ids = ordered.map((session) => session.id); const index = ids.indexOf(sessionId); const other = index + step; if (index < 0 || other < 0 || other >= ids.length) return ids; [ids[index], ids[other]] = [ids[other], ids[index]]; return ids; } // Planned time for each session. A session that started or finished re-anchors everything // after it; one that should have started but hasn't is expected now, so a paused day or a // late heat pushes the rest of the day on its own. Without a start time the day runs from // its first real start, else from now. export function buildDaySchedule(ordered, day, now = Date.now()) { const firstStart = ordered.map((session) => Number(session.startedAt || 0)).filter(Boolean).sort((a, b) => a - b)[0]; const dayStartAt = Number(day?.startAt || 0) || 0; let cursor = dayStartAt || firstStart || now; let upcomingIndex = 0; let previous = null; const fixed = fixedBreakWindow(day); const overlapsFixed = (start, durationMs) => Boolean(fixed && start < fixed.end && start + durationMs > fixed.start); return ordered.map((session) => { const durationMs = sessionDurationMs(session); const actualStart = Number(session.startedAt || 0) || null; const actualEnd = isDone(session) ? Number(session.endedAt || 0) || null : null; // The first heat starts at the day's start time; an extra break before it still counts. const breakMin = breakBeforeMin(previous, session, day); let planned = cursor + breakMin * 60000; let afterFixedBreak = false; previous = session; let state = "upcoming"; let start = planned; let end; if (isDone(session)) { state = "done"; start = actualStart || planned; end = actualEnd || start + durationMs; } else if (isLive(session) && actualStart) { state = "live"; start = actualStart; const pausedMs = Number(session.totalPausedMs || 0) + (session.status === "paused" && session.pausedAt ? Math.max(0, now - Number(session.pausedAt)) : 0); end = Math.max(now, actualStart + durationMs + pausedMs); } else { // A heat that would start or run into the fixed break (lunch) waits until it is over. if (overlapsFixed(planned, durationMs)) { planned = fixed.end; afterFixedBreak = true; } // Not before the day's first start, nor before now. start = Math.max(planned, now, dayStartAt); if (overlapsFixed(start, durationMs)) { start = fixed.end; afterFixedBreak = true; } end = start + durationMs; } // A heat already run that comes after one still waiting (classes take turns, so a done // heat of one class can follow a pending one of another) must not pull the cursor back // to its real, earlier end - every heat after it would then get the same time ("now"). cursor = upcomingIndex > 0 || state === "upcoming" ? Math.max(cursor, end) : end; return { session, breakMin, afterFixedBreak, state, plannedStart: planned, start, end, upcomingIndex: state === "upcoming" ? upcomingIndex++ : null, delayed: Boolean((actualStart || (state === "upcoming" ? start : 0)) > planned + 60000), }; }); } // What the autopilot does now: { type: "start", row, launchAt } or { type: "wait", reason, row?, launchAt? }. // prologueMs(session) = how long before the planned start its count-down begins. // finalsPending = the classes whose qualifying is done but whose finals are not created yet: // the autopilot never creates finals (qualifying may need corrections first), it waits for them. export function getAutopilotAction(rows, { day, now = Date.now(), busy = false, prologueMs = () => 0, finalsPending = [] }) { if (day?.pausedAt) return { type: "wait", reason: "paused" }; if (busy || rows.some((row) => row.state === "live")) return { type: "wait", reason: "running" }; const row = rows.find((item) => item.state === "upcoming"); if (!row) return finalsPending.length ? { type: "wait", reason: "finals", classes: finalsPending } : { type: "wait", reason: "done" }; const launchAt = row.start - Math.max(0, Number(prologueMs(row.session) || 0)); return now >= launchAt ? { type: "start", row, launchAt } : { type: "wait", reason: "until", row, launchAt }; } // The date the drivers' board shows: today if anything is raced today, else the next date with // a session still to run, else today. export function pickBoardDate({ events = [], sessions = [], today }) { const raceDates = new Set(events.filter((event) => (event.mode === "race" || Boolean(event.sponsor)) && event.date).map((event) => event.date)); if (raceDates.has(today)) return today; const pending = events .filter((event) => (event.mode === "race" || Boolean(event.sponsor)) && event.date >= today && sessions.some((session) => session.eventId === event.id && !isDone(session))) .map((event) => event.date) .sort(); return pending[0] || today; } // The next heat to call: the first one not yet called that starts within callMin. A heat the // race controller put off ("Later") is skipped until snoozedUntil(sessionId) has passed. export function getDueCall(rows, { day, now = Date.now(), snoozedUntil = () => 0 }) { if (day?.pausedAt) return null; const callMs = Math.max(1, Number(day?.callMin || DEFAULT_CALL_MIN)) * 60000; return rows.find((row) => row.state === "upcoming" && !row.session.calledAt && row.start - now <= callMs && Number(snoozedUntil(row.session.id) || 0) <= now) || null; }