diff --git a/CHANGELOG.md b/CHANGELOG.md index d341493..f7e5fc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.89.46 - 2026-11-16 + +- Races: practice is now split into heats of at most Cars per heat, like qualifying ("practice 1 H1", "practice 1 H2" ...). Practice standings join all the heats, so seeding qualifying from practice works as before. A driver added later joins the smallest practice heat of every round. +- Manage → Format: changing Cars per heat or the number of qualifying rounds now rebuilds the practice and qualifying heats that have not run yet (e.g. 10 per heat → 5 gives twice as many heats, 5 rounds → 3 removes two). Heats that have run are never touched; the format still saves and a message says why. + ## 1.89.45 - 2026-11-16 - Dashboard: Schedule drift only counts today's timed heats. Open Practice and free practice no longer count, so an open practice left running, or last weekend's race, no longer shows as hours behind schedule. diff --git a/README.md b/README.md index 374af20..f63f9fc 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,8 @@ After creation the race is managed in four tabs (Race Setup → Manage): - presets: short technical track, club race, ÖRC Winter, endurance, and whole race days in federation style - **EFRA 1/10 Off-road**, **EFRA 1/10 Touring / On-road**, **EFRA/SBF 1/8 Nitro** (bump-up, long final), **IFMAR worlds**, **ROAR** (timed qualifying, bump-up, single A main), **Quick club day**, **Rookie / Junior** and **Points race without finals** - or your own saved club presets. A federation preset also sets the practice rounds (with seeding on the best 3 laps in a row), and its description is shown under the choice. The values follow the handbooks in spirit; rules change between editions, so everything stays editable; - **Race actions** at the bottom of the tab: - create qualifying from practice (or the entry list); heats are split as evenly as possible, e.g. 9 drivers with max 8 per heat gives 5 + 4; + - practice is split into heats the same way; + - changing cars per heat or the number of qualifying rounds under Format rebuilds the practice and qualifying heats that have not run yet; - reseed upcoming heats; locked manual grids are respected; - create A/B/C finals and apply bump-ups; - export the race as a package. diff --git a/README.sv.md b/README.sv.md index 1fac163..8ffa4be 100644 --- a/README.sv.md +++ b/README.sv.md @@ -188,6 +188,8 @@ Efter det hanteras racet i fyra flikar (Race Setup → Hantera): - förval: kort teknisk bana, klubbrace, ÖRC Winter, endurance, och hela racedagar i förbundsstil – **EFRA 1/10 Off-road**, **EFRA 1/10 Touring / On-road**, **EFRA/SBF 1/8 Nitro** (bump-up, lång final), **IFMAR VM**, **ROAR** (tidskval, bump-up, en A-final), **Klubbdag snabb**, **Rookie / Junior** och **Poängrace utan finaler** – eller egna sparade klubbförval. Ett förbundsförval sätter även antal träningar (med seeding på bästa 3 varv i följd), och beskrivningen visas under valet. Värdena följer handböckerna i stil; reglerna ändras mellan årgångar, så allt går att justera; - **Race actions** längst ner i fliken: - skapa kval från träningen (eller deltagarlistan); heaten delas så jämnt som möjligt, till exempel 9 förare och max 8 per heat → 5 + 4; + - träningen (practice) delas i heat på samma sätt; + - ändrar du bilar per heat eller antal kvalomgångar under Format byggs de practice- och kvalheat som inte har körts om; - omseeda kommande heat; låsta manuella grid respekteras; - skapa A/B/C-finaler och bump-up; - exportera racet som ett paket. diff --git a/package-lock.json b/package-lock.json index 20aa544..b211c82 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.89.45", + "version": "1.89.46", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.89.45", + "version": "1.89.46", "hasInstallScript": true, "license": "AGPL-3.0-or-later", "dependencies": { diff --git a/package.json b/package.json index 0b5eb08..546221f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.89.45", + "version": "1.89.46", "private": true, "license": "AGPL-3.0-or-later", "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", diff --git a/src/app.js b/src/app.js index f72ca7b..1c4c373 100644 --- a/src/app.js +++ b/src/app.js @@ -33,7 +33,7 @@ import { RACE_AUDIO_EVENT_DEFINITIONS, createRaceAudioEngine, normalizeRaceAudio import { renderRaceFormatField, renderRaceFormatContextCard, getRaceSummaryItems, getRaceSummaryWarnings, renderManageStatusBadge, renderRaceWizardSteps, renderRaceWizardContent, renderRaceStandingsTable } from "./race_setup_ui.js"; -import { normalizeRaceTeam as normalizeRaceTeamLogic, normalizeStoredRacePreset as normalizeStoredRacePresetLogic, getRaceFormatPresets as getRaceFormatPresetsLogic, applyRaceFormatPreset as applyRaceFormatPresetLogic, buildRaceFormatConfigFromForm as buildRaceFormatConfigFromFormLogic, normalizeEvent as normalizeEventLogic, normalizeBrandingConfig as normalizeBrandingConfigLogic, resolveEventBranding as resolveEventBrandingLogic, getRaceManageStatuses as getRaceManageStatusesLogic, buildDefaultRaceWizardDraft as buildDefaultRaceWizardDraftLogic, getRaceWizardPreset as getRaceWizardPresetLogic, applyRaceWizardPresetDefaults as applyRaceWizardPresetDefaultsLogic, ensureRaceParticipantsConfigured as ensureRaceParticipantsConfiguredLogic, buildRaceSession as buildRaceSessionLogic, buildOpenPracticeBundle as buildOpenPracticeBundleLogic, buildTrackSession as buildTrackSessionLogic, createSponsorRounds as createSponsorRoundsLogic, buildRaceSessionsFromWizard as buildRaceSessionsFromWizardLogic, getRaceWizardSessionPlan as getRaceWizardSessionPlanLogic, getEventDrivers as getEventDriversLogic, getEventTeams as getEventTeamsLogic, getTeamDriverPool as getTeamDriverPoolLogic, reassignTeamMembers as reassignTeamMembersLogic, findEventTeamForPassing as findEventTeamForPassingLogic, generateQualifyingForRace as generateQualifyingForRaceLogic, reseedUpcomingQualifying as reseedUpcomingQualifyingLogic, moveDriversIntoQualifyingHeat as moveDriversIntoQualifyingHeatLogic, parseQualifyingHeatName as parseQualifyingHeatNameLogic, generateFinalsForRace as generateFinalsForRaceLogic, getRunGeneratedSessions, applyBumpsForRace as applyBumpsForRaceLogic, orderSessionsForRunning, buildEventSchedule as buildEventScheduleLogic, normalizeHeatOrder, planSeedingGroups } from "./event_race_logic.js"; +import { normalizeRaceTeam as normalizeRaceTeamLogic, normalizeStoredRacePreset as normalizeStoredRacePresetLogic, getRaceFormatPresets as getRaceFormatPresetsLogic, applyRaceFormatPreset as applyRaceFormatPresetLogic, buildRaceFormatConfigFromForm as buildRaceFormatConfigFromFormLogic, normalizeEvent as normalizeEventLogic, normalizeBrandingConfig as normalizeBrandingConfigLogic, resolveEventBranding as resolveEventBrandingLogic, getRaceManageStatuses as getRaceManageStatusesLogic, buildDefaultRaceWizardDraft as buildDefaultRaceWizardDraftLogic, getRaceWizardPreset as getRaceWizardPresetLogic, applyRaceWizardPresetDefaults as applyRaceWizardPresetDefaultsLogic, ensureRaceParticipantsConfigured as ensureRaceParticipantsConfiguredLogic, buildRaceSession as buildRaceSessionLogic, buildOpenPracticeBundle as buildOpenPracticeBundleLogic, buildTrackSession as buildTrackSessionLogic, createSponsorRounds as createSponsorRoundsLogic, buildRaceSessionsFromWizard as buildRaceSessionsFromWizardLogic, getRaceWizardSessionPlan as getRaceWizardSessionPlanLogic, getEventDrivers as getEventDriversLogic, getEventTeams as getEventTeamsLogic, getTeamDriverPool as getTeamDriverPoolLogic, reassignTeamMembers as reassignTeamMembersLogic, findEventTeamForPassing as findEventTeamForPassingLogic, generateQualifyingForRace as generateQualifyingForRaceLogic, rebuildPracticeHeats as rebuildPracticeHeatsLogic, reseedUpcomingQualifying as reseedUpcomingQualifyingLogic, moveDriversIntoQualifyingHeat as moveDriversIntoQualifyingHeatLogic, parseQualifyingHeatName as parseQualifyingHeatNameLogic, generateFinalsForRace as generateFinalsForRaceLogic, getRunGeneratedSessions, applyBumpsForRace as applyBumpsForRaceLogic, orderSessionsForRunning, buildEventSchedule as buildEventScheduleLogic, normalizeHeatOrder, planSeedingGroups } from "./event_race_logic.js"; import { getFinishWait as getFinishWaitLogic, getSessionTypeLabel as getSessionTypeLabelLogic, getStatusLabel as getStatusLabelLogic, isUntimedSession as isUntimedSessionLogic, getActiveSession as getActiveSessionLogic, getLiveSession as getLiveSessionLogic, getSessionTargetMs as getSessionTargetMsLogic, getSessionLapWindow as getSessionLapWindowLogic, isCountedPassing as isCountedPassingLogic, getVisiblePassings as getVisiblePassingsLogic, getPassingValidationLabel as getPassingValidationLabelLogic, getSessionTiming as getSessionTimingLogic, ensureSessionResult as ensureSessionResultLogic, buildLeaderboard as buildLeaderboardLogic, formatLapDelta as formatLapDeltaLogic, formatLeaderboardGap as formatLeaderboardGapLogic, getCompetitorElapsedMs as getCompetitorElapsedMsLogic, getCompetitorPassings as getCompetitorPassingsLogic, getCompetitorSeedMetric as getCompetitorSeedMetricLogic, getSessionEntrants as getSessionEntrantsLogic, buildPracticeStandings as buildPracticeStandingsLogic, getQualifyingPointsValue as getQualifyingPointsValueLogic, isHighPointsTable as isHighPointsTableLogic, compareNumberSet as compareNumberSetLogic, buildQualifyingTieBreakNote as buildQualifyingTieBreakNoteLogic, hasQualifyingPrimaryTie as hasQualifyingPrimaryTieLogic, buildQualifyingStandings as buildQualifyingStandingsLogic, formatTeamActiveMemberLabel as formatTeamActiveMemberLabelLogic, buildTeamRaceStandings as buildTeamRaceStandingsLogic, buildSessionChannelStats as buildSessionChannelStatsLogic, buildTeamStintLog as buildTeamStintLogLogic, getSessionGridEntries as getSessionGridEntriesLogic, getSessionGridOrder as getSessionGridOrderLogic, ensureSessionDriverOrder as ensureSessionDriverOrderLogic, buildFinalStandings as buildFinalStandingsLogic, getTrackRecordMs as getTrackRecordMsLogic } from "./timing_logic.js"; import { normalizeTrackLayouts, getTrackLayoutIdAt, getTrackLayoutLabel, nextTrackLayoutLabel, findRaceSessionBlockingLayoutChange, isPracticeSessionType, isTrackLayoutInUse } from "./track_layouts_logic.js"; @@ -111,6 +111,7 @@ const reassignTeamMembers = (teams, options) => reassignTeamMembersLogic(teams, const moveDriversIntoQualifyingHeat = (targetSessionId, driverIds) => moveDriversIntoQualifyingHeatLogic(state.sessions, targetSessionId, driverIds); const parseQualifyingHeatName = (name) => parseQualifyingHeatNameLogic(name); const findEventTeamForPassing = (event, driverId, carId) => findEventTeamForPassingLogic(event, driverId, carId, { getEventTeams }); +const rebuildPracticeHeats = (event) => rebuildPracticeHeatsLogic(event, { state, t, buildRaceSession }); const generateQualifyingForRace = (event) => generateQualifyingForRaceLogic(event, { buildPracticeStandings, getEventDrivers, state, normalizeStartMode, normalizeSession, uid, chunkArray, clearGeneratedQualifying }); const reseedUpcomingQualifying = (event) => reseedUpcomingQualifyingLogic(event, { buildQualifyingStandings, buildPracticeStandings, getEventDrivers, getSessionsForEvent, chunkArray }); // Names of the generated heats of a race that already ran ("" = none): then they can't be made again. @@ -2535,7 +2536,7 @@ const TRANSLATIONS = { "guide.race_wizard_1": "1. Börja i Race Setup och använd wizarden när du skapar ett nytt race, i stället för att bygga allt direkt i Hantera.", "guide.race_wizard_2": "2. Steg 1 sätter namn, datum, klass och preset. Det finns hela tävlingsdagar som preset (EFRA off-road, touring, 1/8 nitro, ROAR, snabb klubbdag, Rookie/Junior, poängrace utan finaler) - beskrivningen visas under valet. Presetet fyller rimliga standardvärden innan du finjusterar något.", "guide.race_wizard_3": "3. Steg 2 väljer exakt vilka förare som ska vara med. Listan är grupperad per klass med Alla/Ingen per klass, sök på namn eller transponder och Samma förare som... för att kopiera ett tidigare race. De blir race-specifika deltagare och filter för timing/seedning.", - "guide.race_wizard_4": "4. Steg 3 väljer vilka sessioner som ska skapas direkt: practice, kval och/eller team race beroende på preset.", + "guide.race_wizard_4": "4. Steg 3 väljer vilka sessioner som ska skapas direkt: practice, kval och/eller team race beroende på preset. Practice och kval delas i heat med högst Bilar per heat (12 förare och max 5 → 4 + 4 + 4). Ändrar du Bilar per heat eller antal kvalomgångar under Hantera → Format innan heaten har körts byggs de om av sig själva; heat som redan har körts rörs inte.", "guide.race_wizard_5": "5. Wizarden skapar de första sessionerna automatiskt, kvalet som heat (Q1 H1, Q1 H2 …). Finaler skapas senare från Race actions när kval eller practice är klara.", "guide.race_wizard_6": "6. Efter skapandet går du vidare till Hantera för raceformat, generering, grid, standings och utskrift.", "guide.race_wizard_7": "7. I Hantera -> Race actions kan du exportera eller importera ett enskilt racepaket om du vill flytta just det racet till en annan installation.", @@ -2648,6 +2649,8 @@ const TRANSLATIONS = { "events.qualifying_standings": "Kval-ranking", "events.final_standings": "Final-ranking", "events.generated_qualifying": "Kvalheat skapade från ranking.", + "events.format_practice_not_rebuilt": "Practice-heaten görs inte om eftersom practice redan har börjat köras – då skulle varv och resultat raderas.", + "events.format_heats_not_rebuilt": "Formatet är sparat, men kvalheaten görs inte om eftersom kvalet redan har börjat köras ({names}) – då skulle varv och resultat raderas. Vill ni ändå göra om dem: tryck först \"Rensa genererade kval\" och sedan \"Skapa kval från practice\".", "events.finals_generated": "Finaler skapade från ranking.", "events.finals_already_run": "Finalerna har redan börjat köras ({names}), så de görs inte om – då skulle varv och resultat raderas. Vill ni verkligen göra om dem: tryck först \"Rensa genererade finaler\".", "events.qualifying_already_run": "Kvalet har redan börjat köras ({names}), så det görs inte om – då skulle varv och resultat raderas. Vill ni verkligen göra om det: tryck först \"Rensa genererade kval\".", @@ -4960,7 +4963,7 @@ const TRANSLATIONS = { "guide.race_wizard_1": "1. Start in Race Setup and use the wizard when creating a new race instead of building everything directly in Manage.", "guide.race_wizard_2": "2. Step 1 sets name, date, class and preset. Whole race days come as presets (EFRA off-road, touring, 1/8 nitro, ROAR, quick club day, Rookie/Junior, points race without finals) - the description shows under the choice. The preset fills sensible defaults before you fine-tune anything.", "guide.race_wizard_3": "3. Step 2 selects exactly which drivers take part. The list is grouped by class with All/None per class, a search on name or transponder and Same drivers as... to copy an earlier race. They become the race-specific participant scope for timing and seeding.", - "guide.race_wizard_4": "4. Step 3 chooses which sessions should be created immediately: practice, qualifying and/or team race depending on the preset.", + "guide.race_wizard_4": "4. Step 3 chooses which sessions should be created immediately: practice, qualifying and/or team race depending on the preset. Practice and qualifying are split into heats of at most Cars per heat (12 drivers and max 5 → 4 + 4 + 4). If you change Cars per heat or the number of qualifying rounds under Manage → Format before the heats have run, they are built again by themselves; heats that have already run are left alone.", "guide.race_wizard_5": "5. The wizard creates the initial sessions automatically, qualifying as heats (Q1 H1, Q1 H2 …). Finals are generated later from Race Actions after qualifying or practice is complete.", "guide.race_wizard_6": "6. After creation, continue in Manage for race format, generation, grid, standings and print/export.", "guide.race_wizard_7": "7. In Manage -> Race Actions you can export or import a single race package when you want to move just that race to another installation.", @@ -5073,6 +5076,8 @@ const TRANSLATIONS = { "events.qualifying_standings": "Qualifying standings", "events.final_standings": "Final standings", "events.generated_qualifying": "Qualifying heats generated from standings.", + "events.format_practice_not_rebuilt": "The practice heats are not made again because practice has already started running - that would delete laps and results.", + "events.format_heats_not_rebuilt": "The format is saved, but the qualifying heats are not made again because qualifying has already started running ({names}) - that would delete laps and results. To redo them anyway, press \"Clear generated qualifying\" first and then \"Generate qualifying from practice\".", "events.finals_generated": "Finals generated from standings.", "events.finals_already_run": "The finals have already started running ({names}), so they are not made again - that would delete their laps and results. To really redo them, press \"Clear generated finals\" first.", "events.qualifying_already_run": "Qualifying has already started running ({names}), so it is not made again - that would delete its laps and results. To really redo it, press \"Clear generated qualifying\" first.", @@ -8308,6 +8313,7 @@ function renderEventManager(eventId) { applyRaceFormatPreset, normalizeStoredRacePreset, generateQualifyingForRace, + rebuildPracticeHeats, clearGeneratedQualifying, reseedUpcomingQualifying, generateFinalsForRace, diff --git a/src/event_manager_controller.js b/src/event_manager_controller.js index 3eab691..8c8465b 100644 --- a/src/event_manager_controller.js +++ b/src/event_manager_controller.js @@ -89,6 +89,7 @@ export function renderEventManagerView(context) { applyRaceFormatPreset, normalizeStoredRacePreset, generateQualifyingForRace, + rebuildPracticeHeats, clearGeneratedQualifying, reseedUpcomingQualifying, generateFinalsForRace, @@ -673,8 +674,26 @@ export function renderEventManagerView(context) { }, })); applyFormatToPendingSessions(state.sessions.filter((session) => session.eventId === event.id), before, config); + // Cars per heat or the number of rounds changed: build the qualifying heats again, as + // long as none of them has run (that would delete laps). updateEvent replaced the event, + // so the new config is read from state. + let notice = ""; + // Practice heats follow cars per heat too (the race's own practice only, never one that ran). + if (Number(before.carsPerHeat) !== Number(config.carsPerHeat)) { + const updated = state.events.find((item) => item.id === event.id); + if (updated && rebuildPracticeHeats(updated) < 0) notice = t("events.format_practice_not_rebuilt"); + } + const heatsChanged = ["carsPerHeat", "qualifyingRounds"].some((key) => Number(before[key]) !== Number(config[key])); + if (heatsChanged && getSessionsForEvent(event.id).some((s) => s.type === "qualification" && s.generated)) { + const run = runHeatNames("qualification"); + const updated = state.events.find((item) => item.id === event.id); + // A rebuild shows in the heat list at once; only a refusal needs saying. + if (run) notice = [notice, t("events.format_heats_not_rebuilt", { names: run })].filter(Boolean).join("\n"); + else if (updated) generateQualifyingForRace(updated); + } saveState(); refreshManager(); + if (notice) alert(notice); }); document.getElementById("scheduleForm")?.addEventListener("submit", (e) => { diff --git a/src/event_race_logic.js b/src/event_race_logic.js index c4988b0..ae9b16a 100644 --- a/src/event_race_logic.js +++ b/src/event_race_logic.js @@ -609,15 +609,8 @@ export function buildRaceSessionsFromWizard(event, draft, { t, buildRaceSession const created = []; const practiceCount = Math.max(0, Number(draft.practiceSessions || 0) || 0); if (draft.createPractice && practiceCount > 0) { - for (let index = 1; index <= practiceCount; index += 1) { - created.push( - buildRaceSession(event.id, `${t("session.practice")} ${index}`, "practice", event.raceConfig.qualDurationMin, { - driverIds, - startMode: "mass", - followUpSec: 0, - }) - ); - } + event.raceConfig.practiceRounds = practiceCount; + created.push(...buildPracticeHeats(event, practiceCount, { t, buildRaceSession })); } // Qualifying is not built here: the wizard sets raceConfig.qualifyingRounds and calls // generateQualifyingForRace, so the heats are split per "drivers per heat" and named @@ -636,6 +629,54 @@ export function buildRaceSessionsFromWizard(event, draft, { t, buildRaceSession +// Practice in the race: every round split into heats of at most "cars per heat", like the +// qualifying ("träning 1 H1", "träning 1 H2", ...; just "träning 1" when everyone fits in one). +// Entry order; practice standings join all the heats, so seeding from practice works as before. +export function buildPracticeHeats(event, rounds, { t, buildRaceSession }) { + const carsPerHeat = Math.max(2, Number(event.raceConfig?.carsPerHeat || 8) || 8); + const groups = splitIntoBalancedGroups(event.raceConfig?.driverIds || [], carsPerHeat); + if (!groups.length) groups.push([]); + const sessions = []; + for (let round = 1; round <= Math.max(1, Number(rounds) || 1); round += 1) { + groups.forEach((driverIds, index) => { + const name = `${t("session.practice")} ${round}${groups.length > 1 ? ` H${index + 1}` : ""}`; + const session = buildRaceSession(event.id, name, "practice", event.raceConfig?.qualDurationMin, { driverIds, startMode: "mass", followUpSec: 0 }); + session.generated = true; + sessions.push(session); + }); + } + return sessions; +} + +// "träning 2 H3" / "practice 2" -> { round: 2, heat: 3 | null }. Races made before practice heats +// have one "träning N" / "practice N" session per round and no generated flag. +export function parsePracticeHeatName(name) { + const match = String(name || "").match(/^(?:träning|practice)\s+(\d+)(?:\s+H(\d+))?$/i); + return match ? { round: Number(match[1]), heat: match[2] ? Number(match[2]) : null } : null; +} + +// Builds the race's practice heats again for the current cars per heat and participants. +// Returns the number of sessions made, 0 when the race has no practice of its own, and -1 when a +// practice heat has already run (its laps would be lost). +export function rebuildPracticeHeats(event, { state, t, buildRaceSession }) { + const ours = state.sessions.filter((session) => session.eventId === event.id && session.type === "practice" + && (session.generated || parsePracticeHeatName(session.name))); + if (!ours.length) return 0; + const hasRun = ours.some((session) => session.status !== "ready" || session.startedAt + || Object.keys(state.resultsBySession?.[session.id]?.competitors || {}).length); + if (hasRun) return -1; + const rounds = Number(event.raceConfig?.practiceRounds) || new Set(ours.map((session) => parsePracticeHeatName(session.name)?.round || session.id)).size; + const ids = new Set(ours.map((session) => session.id)); + state.sessions = state.sessions.filter((session) => !ids.has(session.id)); + ids.forEach((id) => { + if (state.resultsBySession) delete state.resultsBySession[id]; + if (state.activeSessionId === id) state.activeSessionId = null; + }); + const sessions = buildPracticeHeats(event, rounds, { t, buildRaceSession }); + state.sessions.push(...sessions); + return sessions.length; +} + export function getRaceWizardSessionPlan(draft, { t }) { const plan = []; if (draft.createPractice) { @@ -688,8 +729,16 @@ export function syncParticipantsToSessions(sessions, beforeIds = [], afterIds = if (Array.isArray(session.manualGridIds) && !session.manualGridIds.includes(id)) session.manualGridIds = [...session.manualGridIds, id]; }; const keep = new Set(beforeIds.filter((id) => !removed.has(id))); - pending.filter((session) => session.type === "practice" && [...keep].every((id) => (session.driverIds || []).includes(id))) + pending.filter((session) => session.type === "practice" && !parsePracticeHeatName(session.name)?.heat && [...keep].every((id) => (session.driverIds || []).includes(id))) .forEach((session) => added.forEach((id) => join(session, id))); + // Practice split into heats: a new driver joins the smallest heat of every round. + const practiceHeats = pending.map((session) => ({ session, parsed: session.type === "practice" ? parsePracticeHeatName(session.name) : null })).filter((item) => item.parsed?.heat); + added.forEach((id) => { + [...new Set(practiceHeats.map((item) => item.parsed.round))].forEach((round) => { + const inRound = practiceHeats.filter((item) => item.parsed.round === round).sort((a, b) => (a.session.driverIds || []).length - (b.session.driverIds || []).length || a.parsed.heat - b.parsed.heat); + if (inRound.length) join(inRound[0].session, id); + }); + }); const heats = pending.map((session) => ({ session, parsed: parseQualifyingHeatName(session.name) })).filter((item) => item.parsed); added.forEach((id) => { if (!heats.length) return; diff --git a/tests/browser_race_setup.js b/tests/browser_race_setup.js index 7a43602..e96cdb4 100644 --- a/tests/browser_race_setup.js +++ b/tests/browser_race_setup.js @@ -83,7 +83,8 @@ export async function runRaceSetupSmoke({ evaluate, navigate, fill, savedState, const club = await findEvent("Browser Club Race"); const clubSessions = (await savedState()).sessions.filter((session) => session.eventId === club.id); const quals = clubSessions.filter((session) => session.type === "qualification"); - assert.equal(clubSessions.filter((session) => session.type === "practice").length, 1, "one practice"); + const practices = clubSessions.filter((session) => session.type === "practice"); + assert.ok(practices.length >= 1 && practices.every((session) => session.driverIds.length <= club.raceConfig.carsPerHeat), `practice split by cars per heat: ${practices.map((session) => session.name + ":" + session.driverIds.length)}`); assert.ok(quals.length >= 2 && quals.every((session) => /^Q[12] H\d+$/.test(session.name) && session.generated), `qualifying heats per round: ${quals.map((session) => session.name)}`); assert.equal(club.raceConfig.qualifyingRounds, 2); console.log("PASS wizard builds qualifying as Q H heats"); @@ -97,6 +98,17 @@ export async function runRaceSetupSmoke({ evaluate, navigate, fill, savedState, await evaluate(`document.querySelector('.race-participant[value="${first}"]').click()`); await waitFor(async () => (await savedState()).sessions.some((session) => session.eventId === club.id && session.type === "qualification" && session.driverIds.includes(first)), "ticked again: back in a heat"); console.log("PASS race participants can be changed after creation and the heats follow"); + // Format: changing cars per heat / rounds rebuilds the qualifying heats that have not run. + const qualCount = async () => (await savedState()).sessions.filter((session) => session.eventId === club.id && session.type === "qualification").length; + const before = await qualCount(); + await fill("raceFormatForm", { qualifyingRounds: "3", carsPerHeat: "2" }); + await submit("raceFormatForm"); + await waitFor(async () => (await savedState()).sessions.some((session) => session.eventId === club.id && session.name === "Q3 H1"), "a third round after the format change"); + const heats = (await savedState()).sessions.filter((session) => session.eventId === club.id && session.type === "qualification"); + assert.ok(heats.length > before && heats.every((session) => session.driverIds.length <= 2), `heats rebuilt with max 2 cars: ${heats.map((session) => session.name + ":" + session.driverIds.length)}`); + const practiceHeats = (await savedState()).sessions.filter((session) => session.eventId === club.id && session.type === "practice"); + assert.ok(practiceHeats.every((session) => session.driverIds.length <= 2), `practice heats rebuilt with max 2 cars: ${practiceHeats.map((session) => session.name + ":" + session.driverIds.length)}`); + console.log("PASS format change rebuilds the practice and qualifying heats (cars per heat, rounds)"); } await navigate("race_setup", "raceWizardStepForm"); await editEvent(race, "race_setup", "raceWizardStepForm"); diff --git a/tests/practice_heats.test.js b/tests/practice_heats.test.js new file mode 100644 index 0000000..b3f4bd5 --- /dev/null +++ b/tests/practice_heats.test.js @@ -0,0 +1,46 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { buildPracticeHeats, rebuildPracticeHeats, parsePracticeHeatName, syncParticipantsToSessions } from "../src/event_race_logic.js"; + +let n = 0; +const t = (key) => ({ "session.practice": "träning" }[key] || key); +const buildRaceSession = (eventId, name, type, durationMin, overrides = {}) => ({ id: `s${++n}`, eventId, name, type, durationMin, status: "ready", startedAt: null, driverIds: overrides.driverIds || [] }); +const drivers = (count) => Array.from({ length: count }, (_, i) => `d${i + 1}`); +const event = (count, carsPerHeat, extra = {}) => ({ id: "e1", raceConfig: { driverIds: drivers(count), carsPerHeat, qualDurationMin: 5, ...extra } }); + +test("practice heats: each round is split into balanced heats of at most cars per heat", () => { + const sessions = buildPracticeHeats(event(12, 5), 2, { t, buildRaceSession }); + assert.deepEqual(sessions.map((s) => s.name), ["träning 1 H1", "träning 1 H2", "träning 1 H3", "träning 2 H1", "träning 2 H2", "träning 2 H3"]); + assert.deepEqual(sessions.slice(0, 3).map((s) => s.driverIds.length), [4, 4, 4]); + assert.ok(sessions.every((s) => s.generated && s.type === "practice")); +}); + +test("practice heats: everyone in one heat keeps the plain name", () => { + assert.deepEqual(buildPracticeHeats(event(6, 10), 1, { t, buildRaceSession }).map((s) => s.name), ["träning 1"]); +}); + +test("practice heats: rebuilt for a new heat size, also from an older race without heats", () => { + const ev = event(10, 5); + const state = { sessions: [ + { id: "old1", eventId: "e1", name: "träning 1", type: "practice", status: "ready", driverIds: drivers(10) }, + { id: "old2", eventId: "e1", name: "träning 2", type: "practice", status: "ready", driverIds: drivers(10) }, + { id: "q", eventId: "e1", name: "Q1 H1", type: "qualification", status: "ready", driverIds: [] }, + ], resultsBySession: {} }; + assert.equal(rebuildPracticeHeats(ev, { state, t, buildRaceSession }), 4); + assert.deepEqual(state.sessions.filter((s) => s.type === "practice").map((s) => `${s.name}:${s.driverIds.length}`), ["träning 1 H1:5", "träning 1 H2:5", "träning 2 H1:5", "träning 2 H2:5"]); + assert.ok(state.sessions.some((s) => s.id === "q"), "qualifying untouched"); +}); + +test("practice heats: never rebuilt once one has run", () => { + const state = { sessions: [{ id: "p", eventId: "e1", name: "träning 1", type: "practice", status: "finished", startedAt: 1, driverIds: [] }], resultsBySession: {} }; + assert.equal(rebuildPracticeHeats(event(10, 5), { state, t, buildRaceSession }), -1); + assert.equal(state.sessions[0].id, "p"); +}); + +test("practice heats: a new participant joins the smallest heat of every round", () => { + const sessions = buildPracticeHeats(event(9, 5), 2, { t, buildRaceSession }); + syncParticipantsToSessions(sessions, drivers(9), [...drivers(9), "new"]); + const withNew = sessions.filter((s) => s.driverIds.includes("new")).map((s) => s.name); + assert.deepEqual(withNew, ["träning 1 H2", "träning 2 H2"]); + assert.deepEqual(parsePracticeHeatName("practice 3 H2"), { round: 3, heat: 2 }); +}); diff --git a/tests/run.js b/tests/run.js index 3074cf2..e74364d 100644 --- a/tests/run.js +++ b/tests/run.js @@ -39,6 +39,7 @@ import "./race_timing_logic.test.js"; import "./track_layouts_logic.test.js"; import "./race_day_logic.test.js"; import "./schedule_drift.test.js"; +import "./practice_heats.test.js"; import "./race_day_export.test.js"; import "./backup_service.test.js"; import "./judging_logic.test.js";