From e7eaa0561eb5e35e1d48c38cdf6ae729b0a287ed Mon Sep 17 00:00:00 2001 From: larssand Date: Sat, 31 Oct 2026 22:52:18 +0100 Subject: [PATCH] feat(series): seeding practice in groups split on the series standings (1.45.0) --- CHANGELOG.md | 6 ++++ README.md | 2 +- README.sv.md | 2 +- package-lock.json | 4 +-- package.json | 2 +- src/app.js | 52 ++++++++++++++++++++++++++++++---- src/event_race_logic.js | 13 +++++++++ src/series_logic.js | 4 ++- src/series_view.js | 18 +++++++++--- tests/browser_series.js | 15 +++++++--- tests/series_next_step.test.js | 15 ++++++++-- 11 files changed, 112 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ef9881..4311b6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.45.0 - 2026-10-31 + +### Added + +- **Series: seeding practice in groups.** "Max drivers per seeding group" (step 3, default 6) and a Seed group column per round (0 = everyone together) split the seeding practice into even groups - 10 drivers with max 5 give 2 × 5, 50 with max 6 give 9 groups of 6 or 5. The groups follow the series standings in the class (drivers close in the standings share a group; the first round and drivers without points in entry order), and with "fastest heat last" the top group runs last. They are split from today's drivers when ▶ Seeding practice is pressed, and re-split until the first group has started. All groups make one ranking for the qualifying heats. + ## 1.44.1 - 2026-10-31 ### Changed diff --git a/README.md b/README.md index d2d7b1d..43e967f 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ Menu **Series / cup** runs a championship over any number of rounds, with freely - **Counted results:** best N (e.g. 9 of 12), or all run rounds except the X worst. A cancelled round then lowers the count automatically. 3. **Rounds:** paste the dates, and one race per date and class is created. The button says how many races were made. - **Format:** e.g. **ÖRC Winter** (3 × 5 min qualifying with own clock, the best 2 rounds compared, max 6 per heat and final, 3 finals of which 2 count). It fills in the number of qualifying rounds, finals and max cars per heat, which can be changed. - - **Seeding practice before qualifying** (default: on, 5 min, best 3 consecutive laps): every race starts with a practice, and the qualifying heats are split on it so drivers of equal pace run together. + - **Seeding practice before qualifying** (default: on, 5 min, best 3 consecutive laps): every race starts with a practice, and the qualifying heats are split on it so drivers of equal pace run together. **Max drivers per seeding group** (default 6, the Seed group column per round, 0 = all together) splits the practice into even groups on the series standings when you press ▶ Seeding practice, e.g. 10 drivers with max 5 → 2 groups of 5. - **Heat order:** fastest heat last (default) or first. Also set per race in Race Setup. Each round is then run from its row: diff --git a/README.sv.md b/README.sv.md index 7d51eab..a49e722 100644 --- a/README.sv.md +++ b/README.sv.md @@ -189,7 +189,7 @@ Menyn **Serier / cup** kör ett mästerskap över valfritt antal deltävlingar, - **Räknade resultat:** bästa N (t.ex. 9 av 12), eller alla körda utom X sämsta. Då minskar antalet automatiskt om en deltävling ställs in. 3. **Deltävlingar:** klistra in datumen, så skapas ett race per datum och klass. Knappen talar om hur många race som skapades. - **Format:** till exempel **ÖRC Winter** (3 × 5 min kval med egen klocka där bästa 2 rundorna jämförs, max 6 per heat och final, 3 finaler där 2 räknas). Formatet fyller i antal kvalomgångar, finaler och max bilar per heat, som går att ändra. - - **Seedningsträning före kval** (standard: på, 5 min, bästa 3 konsekutiva varv): varje race börjar med en träning, och kvalheaten delas efter den så att lika snabba kör tillsammans. + - **Seedningsträning före kval** (standard: på, 5 min, bästa 3 konsekutiva varv): varje race börjar med en träning, och kvalheaten delas efter den så att lika snabba kör tillsammans. **Max förare per seedningsgrupp** (standard 6, kolumnen Seedgrupp per deltävling, 0 = alla samtidigt) delar träningen i jämna grupper efter serieställningen när du trycker ▶ Seedningsträning, t.ex. 10 förare med max 5 → 2 grupper om 5. - **Heatordning:** snabbaste heatet sist (standard) eller först. Finns också per race i Race Setup. Varje deltävling sköts sedan från sin rad: diff --git a/package-lock.json b/package-lock.json index 9a87c9a..55ca27e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.44.1", + "version": "1.45.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.44.1", + "version": "1.45.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index 699f543..2701b32 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.44.1", + "version": "1.45.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/src/app.js b/src/app.js index 6dd4bec..4ab7c46 100644 --- a/src/app.js +++ b/src/app.js @@ -15,7 +15,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, applyBumpsForRace as applyBumpsForRaceLogic, buildEventSchedule as buildEventScheduleLogic, normalizeHeatOrder } 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, reseedUpcomingQualifying as reseedUpcomingQualifyingLogic, moveDriversIntoQualifyingHeat as moveDriversIntoQualifyingHeatLogic, parseQualifyingHeatName as parseQualifyingHeatNameLogic, generateFinalsForRace as generateFinalsForRaceLogic, applyBumpsForRace as applyBumpsForRaceLogic, buildEventSchedule as buildEventScheduleLogic, normalizeHeatOrder, planSeedingGroups } from "./event_race_logic.js"; import { 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"; @@ -575,7 +575,7 @@ const getSeriesStandings = (series) => buildSeriesStandings(series, { classNames: new Map(state.classes.map((item) => [item.id, item.name])), }); // One race per date and class, named " # ", with the chosen race format. -const createSeriesEvents = (series, dates, presetId, format = {}, { heatOrder = "", seedPractice = false, seedPracticeMin = 5, seedLaps = 3, seedMethod = "consecutive" } = {}) => { +const createSeriesEvents = (series, dates, presetId, format = {}, { heatOrder = "", seedPractice = false, seedPracticeMin = 5, seedLaps = 3, seedMethod = "consecutive", seedGroupSize = 0 } = {}) => { const existingDates = new Set(state.events.filter((event) => series.eventIds.includes(event.id)).map((event) => event.date)); const allDates = [...new Set([...existingDates, ...dates])].sort(); let created = 0; @@ -591,6 +591,7 @@ const createSeriesEvents = (series, dates, presetId, format = {}, { heatOrder = // A practice before qualifying seeds the heats (no driver list: it follows the round's // participants, set later). if (seedPractice) { + event.raceConfig.seedGroupSize = Math.max(0, Math.round(Number(seedGroupSize) || 0)); state.sessions.push(buildRaceSession(event.id, t("series.seed_practice_name"), "practice", Math.max(1, Math.round(seedPracticeMin)), { startMode: "mass", seedBestLapCount: seedLaps, seedMethod, })); @@ -642,6 +643,7 @@ const setSeriesRoundFormat = (eventId, values) => { config.finalLegs = Math.max(1, Math.round(Number(values.finalLegs ?? config.finalLegs) || 1)); config.carsPerHeat = Math.max(2, Math.round(Number(values.carsPerHeat ?? config.carsPerHeat) || 2)); config.carsPerFinal = Math.max(2, Math.round(Number(values.carsPerHeat ?? config.carsPerFinal) || config.carsPerFinal || 2)); + config.seedGroupSize = Math.max(0, Math.round(Number(values.seedGroupSize ?? config.seedGroupSize) || 0)); // Two of three finals count (or all, with fewer than three). config.countedFinalLegs = config.finalLegs >= 3 ? config.finalLegs - 1 : config.finalLegs; config.presetId = "custom"; @@ -688,6 +690,38 @@ const generateSeriesRoundFinals = (eventId) => { saveState(); return created; }; +// Today's drivers in series-standings order (class table), the rest after them in entry +// order - the first round, and guests in a members-only series. +const rankForSeeding = (event) => { + const series = (state.series || []).find((item) => item.eventIds.includes(event.id)); + const table = series ? getSeriesStandings(series).find((item) => item.classId === event.classId) : null; + const rank = new Map((table?.rows || []).map((row) => [row.driverId, row.rank])); + return getEventDrivers(event).map((driver, index) => ({ id: driver.id, index })) + .sort((a, b) => (rank.get(a.id) ?? Infinity) - (rank.get(b.id) ?? Infinity) || a.index - b.index) + .map((item) => item.id); +}; +// The round's seeding practice is (re)split into groups from today's drivers each time it is +// opened, until one group has started - so late entries and unticked drivers are taken in. +const prepareSeedingGroups = (eventId) => { + const event = findSeriesEvent(eventId); + const seeding = event ? getSessionsForEvent(eventId).filter((session) => session.type === "practice") : []; + if (!seeding.length || seeding.some((session) => session.status !== "ready")) return; + const groups = planSeedingGroups(rankForSeeding(event), event.raceConfig.seedGroupSize, event.raceConfig.heatOrder); + if (!groups.length) return; + const template = seeding[0]; + const oldIds = new Set(seeding.map((session) => session.id)); + if (oldIds.has(state.activeSessionId)) state.activeSessionId = null; + state.sessions = state.sessions.filter((session) => !oldIds.has(session.id)); + const baseName = t("series.seed_practice_name"); + groups.forEach((driverIds, index) => state.sessions.push(buildRaceSession(event.id, groups.length > 1 ? `${baseName} ${index + 1}` : baseName, "practice", template.durationMin, { + driverIds, startMode: template.startMode, seedBestLapCount: template.seedBestLapCount, seedMethod: template.seedMethod, + }))); +}; +const runSeriesSeeding = (eventId) => { + prepareSeedingGroups(eventId); + const step = getSeriesRoundNextStep(getSessionsForEvent(eventId)); + if (step.session) runSeriesSession(step.session.id); +}; // The row's run button: make the session the active one and go to Race Day, where only // Start is left to press. const runSeriesSession = (sessionId) => { @@ -731,7 +765,7 @@ const exportSeriesPdf = async (series, tables) => { )), }); }; -const renderSeries = () => renderSeriesView({ state, dom, t, escapeHtml, saveState, renderView, uid, getClassName, getSeriesStandings, createSeriesEvents, getRaceFormatPresets, exportSeriesPdf, printSeries, getSeriesRounds, deleteSeriesRaces, runSeriesSession, setSeriesRoundFormat, setSeriesRoundParticipants, copySeriesRoundParticipants, addDriverToSeriesRound, generateSeriesRoundQualifying, generateSeriesRoundFinals, openSeriesRound }); +const renderSeries = () => renderSeriesView({ state, dom, t, escapeHtml, saveState, renderView, uid, getClassName, getSeriesStandings, createSeriesEvents, getRaceFormatPresets, exportSeriesPdf, printSeries, getSeriesRounds, deleteSeriesRaces, runSeriesSession, runSeriesSeeding, setSeriesRoundFormat, setSeriesRoundParticipants, copySeriesRoundParticipants, addDriverToSeriesRound, generateSeriesRoundQualifying, generateSeriesRoundFinals, openSeriesRound }); const renderArchive = () => renderResultsArchiveView({ state, dom, t, escapeHtml, formatLap, formatRaceClock, renderTable, getClassName, getEventName, buildLeaderboard, getCompetitorPassings, @@ -1026,6 +1060,10 @@ const TRANSLATIONS = { "series.created_rounds": "{count} race skapade. De finns i listan nedan och under Race Setup.", "series.created_none": "Inga nya race skapades: seriens klasser har redan race på de datumen.", "series.run_seeding": "Seedningsträning", + "series.run_seeding_groups": "Seedningsträning ({count} grupper)", + "series.seed_group_size": "Max förare per seedningsgrupp", + "series.col_seed_group": "Seedgrupp", + "series.col_seed_group_hint": "Max förare per seedningsgrupp (0 = alla i samma). Grupperna delas efter serieställningen när du trycker ▶ Seedningsträning.", "series.run_session": "Kör {name}", "series.show_live": "Pågår: {name}", "series.skip_seeding": "Hoppa över – generera kval", @@ -1652,7 +1690,7 @@ const TRANSLATIONS = { "guide.series_day_1": "1. Allt görs i tabellen i steg 3, en rad per race (datum och klass).", "guide.series_day_2": "2. Klicka på antalet förare och bocka ur dem som inte kör. Kopiera från förra tar samma startfält som förra deltävlingen i klassen; Ny förare lägger in en efteranmäld förare och bockar i hen.", "guide.series_day_3": "3. Ändra vid behov antal kval, finaler och max bilar per heat för just den deltävlingen - det kan skilja mellan deltävlingar och klasser.", - "guide.series_day_4": "4. Knappen på raden visar nästa steg. Börja med ▶ Seedningsträning: den väljer klassens träning och öppnar Race Day - tryck Starta. Kör alla klassers träningar först om ni har flera klasser.", + "guide.series_day_4": "4. Knappen på raden visar nästa steg. Börja med ▶ Seedningsträning: den delar dagens förare i seedningsgrupper (max enligt kolumnen Seedgrupp, efter serieställningen - första deltävlingen i anmälningsordning), väljer första gruppen och öppnar Race Day - tryck Starta. Sedan ▶ Seedningsträning 2 osv. Grupperna delas om tills första gruppen startat, så efteranmälda kommer med.", "guide.series_day_5": "5. Skapa kval: heaten delas efter träningstiderna (lika snabba tillsammans, snabbaste heatet sist) och jämnt efter fältet (9 förare, max 6 -> 5 + 4). Sedan visar raden ▶ Kör Q1 H1, Q1 H2 ... och på Race Day väljer ▶ Nästa nästa heat. Reseeda kommande kval (i racet under Race Setup) delar om efter kvalrankingen.", "guide.series_day_6": "6. När kvalet är klart: Skapa finaler, sedan ▶ Kör C Final 1, B Final 1, A Final 1, C Final 2 ... Status visar var deltävlingen är. Öppna tar dig till racet i Race Setup. Ställningen i steg 4 uppdateras av sig själv.", "guide.series_points_title": "Poäng och ställning", @@ -2891,6 +2929,10 @@ const TRANSLATIONS = { "series.created_rounds": "{count} races created. They are listed below and under Race Setup.", "series.created_none": "No new races were created: the series' classes already have races on those dates.", "series.run_seeding": "Seeding practice", + "series.run_seeding_groups": "Seeding practice ({count} groups)", + "series.seed_group_size": "Max drivers per seeding group", + "series.col_seed_group": "Seed group", + "series.col_seed_group_hint": "Max drivers per seeding group (0 = all together). The groups are split on the series standings when you press ▶ Seeding practice.", "series.run_session": "Run {name}", "series.show_live": "Running: {name}", "series.skip_seeding": "Skip – generate qualifying", @@ -3517,7 +3559,7 @@ const TRANSLATIONS = { "guide.series_day_1": "1. Everything is done in the table in step 3, one row per race (date and class).", "guide.series_day_2": "2. Click the number of drivers and untick those not racing. Copy from previous takes the field of the previous round in the class; New driver registers a late entry and ticks them.", "guide.series_day_3": "3. Change qualifying rounds, finals and max cars per heat for that round if needed - it can differ between rounds and classes.", - "guide.series_day_4": "4. The button on the row shows the next step. Start with ▶ Seeding practice: it selects the class's practice and opens Race Day - press Start. With several classes, run every class's practice first.", + "guide.series_day_4": "4. The button on the row shows the next step. Start with ▶ Seeding practice: it splits today's drivers into seeding groups (max per the Seed group column, on the series standings - entry order in the first round), selects the first group and opens Race Day - press Start. Then ▶ Seeding practice 2 and so on. The groups are re-split until the first one has started, so late entries are included.", "guide.series_day_5": "5. Create qualifying: the heats are split on the practice times (equal pace together, fastest heat last) and evenly by the field (9 drivers, max 6 -> 5 + 4). The row then shows ▶ Run Q1 H1, Q1 H2 ... and on Race Day ▶ Next selects the next heat. Reseed upcoming qualifying (in the race under Race Setup) re-splits on the qualifying standings.", "guide.series_day_6": "6. When qualifying is done: Create finals, then ▶ Run C Final 1, B Final 1, A Final 1, C Final 2 ... Status shows where the round is. Open goes to the race in Race Setup. The standings in step 4 update by themselves.", "guide.series_points_title": "Points and standings", diff --git a/src/event_race_logic.js b/src/event_race_logic.js index cd43fcb..edefb41 100644 --- a/src/event_race_logic.js +++ b/src/event_race_logic.js @@ -216,6 +216,7 @@ export function buildRaceFormatConfigFromForm(form, event, { normalizeStartMode, bumpCount: Math.max(0, Number(form.get("bumpCount") || 0) || 0), reserveBumpSlots: form.get("reserveBumpSlots") === "on", heatOrder: normalizeHeatOrder(form.get("heatOrder") ?? event.raceConfig.heatOrder), + seedGroupSize: Math.max(0, Math.round(Number(form.get("seedGroupSize") ?? event.raceConfig.seedGroupSize) || 0)), driverIds: event.raceConfig.driverIds || [], participantsConfigured: event.raceConfig.participantsConfigured !== false, finalsSource: String(form.get("finalsSource") || "qualifying") === "practice" ? "practice" : "qualifying", @@ -261,6 +262,8 @@ export function normalizeEvent(event, { normalizeBrandingConfig, normalizeStartM bumpCount: Math.max(0, Number(event?.raceConfig?.bumpCount || 0) || 0), reserveBumpSlots: event?.raceConfig?.reserveBumpSlots !== false, heatOrder: normalizeHeatOrder(event?.raceConfig?.heatOrder), + // Max drivers per seeding-practice group (series rounds); 0 = everyone in one practice. + seedGroupSize: Math.max(0, Math.round(Number(event?.raceConfig?.seedGroupSize) || 0)), driverIds: Array.isArray(event?.raceConfig?.driverIds) ? event.raceConfig.driverIds : [], participantsConfigured: Boolean(event?.raceConfig?.participantsConfigured), finalsSource: event?.raceConfig?.finalsSource === "practice" ? "practice" : "qualifying", @@ -662,6 +665,16 @@ export function normalizeHeatOrder(value) { return HEAT_ORDERS.includes(String(value || "")) ? String(value) : "fastest_first"; } +// Seeding practice in groups of at most groupSize (0 = everyone together), split evenly like +// heats. rankedDriverIds come best first (the series standings), so drivers close in the +// standings share a group, and the heat order decides whether the top group runs last. +export function planSeedingGroups(rankedDriverIds, groupSize, heatOrder) { + const ids = [...new Set((rankedDriverIds || []).filter(Boolean))]; + if (!ids.length) return []; + const size = Number(groupSize) > 0 ? Math.round(Number(groupSize)) : ids.length; + return buildSeededHeats(ids, Math.max(1, size), heatOrder); +} + // Seeded rows (fastest first) split into heats in running order (heat 1 first). export function buildSeededHeats(rows, carsPerHeat, heatOrder) { const heats = splitIntoBalancedGroups(rows, carsPerHeat); diff --git a/src/series_logic.js b/src/series_logic.js index 3c1373f..f3b7868 100644 --- a/src/series_logic.js +++ b/src/series_logic.js @@ -175,7 +175,9 @@ export function getSeriesRoundNextStep(sessions = []) { const has = (type) => ordered.some((session) => session.type === type); if (!has("qualification")) { const practice = ready("practice"); - return practice ? { kind: "seeding", session: practice } : { kind: "make_qualifying" }; + // notStarted: no seeding group has run yet (the groups can still be re-split). + const notStarted = ordered.filter((session) => session.type === "practice").every((session) => session.status === "ready"); + return practice ? { kind: "seeding", session: practice, notStarted } : { kind: "make_qualifying" }; } const heat = ready("qualification"); if (heat) return { kind: "qualifying", session: heat }; diff --git a/src/series_view.js b/src/series_view.js index 9ac07cd..526fb4e 100644 --- a/src/series_view.js +++ b/src/series_view.js @@ -92,7 +92,13 @@ function renderNextStep(round, { t, escapeHtml }) { const run = (label, live = false) => ``; const makeQualifying = (label, primary) => ``; if (step.kind === "live") return run(t("series.show_live", { name: step.session.name }), true); - if (step.kind === "seeding") return run(t("series.run_seeding")) + makeQualifying(t("series.skip_seeding"), false); + if (step.kind === "seeding") { + // Before the first group starts, the label says how many groups today's field gives. + const size = Number(round.event.raceConfig?.seedGroupSize) || 0; + const groups = step.notStarted && size > 0 ? Math.ceil(round.participantIds.length / size) : 1; + const label = !step.notStarted ? step.session.name : groups > 1 ? t("series.run_seeding_groups", { count: groups }) : t("series.run_seeding"); + return run(label).replace('data-round-action="run"', 'data-round-action="seeding"') + (step.notStarted ? makeQualifying(t("series.skip_seeding"), false) : ""); + } if (step.kind === "make_qualifying") return makeQualifying(t("series.make_qualifying"), true); if (step.kind === "qualifying" || step.kind === "final") return run(t("series.run_session", { name: step.session.name })); if (step.kind === "make_finals") return ``; @@ -104,7 +110,7 @@ function renderRoundsTable(rounds, { t, escapeHtml }) { const number = (round, name, value, min) => ``; return `
- + ${rounds.map((round) => { const config = round.event.raceConfig || {}; const action = renderNextStep(round, { t, escapeHtml }); @@ -116,10 +122,11 @@ function renderRoundsTable(rounds, { t, escapeHtml }) { + - ${expandedRoundId === round.event.id ? `` : ""}`; + ${expandedRoundId === round.event.id ? `` : ""}`; }).join("")}
${t("series.col_date")}${t("series.col_race")}${t("series.col_drivers")}${t("series.col_qual_short")}${t("series.col_finals")}${t("series.col_per_heat")}${t("series.col_status")}
${t("series.col_date")}${t("series.col_race")}${t("series.col_drivers")}${t("series.col_qual_short")}${t("series.col_finals")}${t("series.col_per_heat")}${t("series.col_seed_group")}${t("series.col_status")}
${number(round, "qualifyingRounds", config.qualifyingRounds || 1, 1)} ${number(round, "finalLegs", config.finalLegs || 1, 1)} ${number(round, "carsPerHeat", config.carsPerHeat || 8, 2)}${number(round, "seedGroupSize", config.seedGroupSize || 0, 0)} ${t(`series.status_${round.status}`)}${round.qualHeatCount ? `
${t("series.heats_made", { heats: round.qualHeatCount })}` : ""}
${action}
${renderRoundParticipants(round, { t, escapeHtml })}
${renderRoundParticipants(round, { t, escapeHtml })}
`; } @@ -156,7 +163,7 @@ function renderStandingsTable(table, { t, escapeHtml }) { export function renderSeriesView(deps) { const { state, dom, t, escapeHtml, saveState, renderView, uid, getClassName, getSeriesStandings, createSeriesEvents, getRaceFormatPresets, exportSeriesPdf, printSeries, - getSeriesRounds, deleteSeriesRaces, runSeriesSession, setSeriesRoundFormat, setSeriesRoundParticipants, copySeriesRoundParticipants, addDriverToSeriesRound, generateSeriesRoundQualifying, generateSeriesRoundFinals, openSeriesRound, + getSeriesRounds, deleteSeriesRaces, runSeriesSession, runSeriesSeeding, setSeriesRoundFormat, setSeriesRoundParticipants, copySeriesRoundParticipants, addDriverToSeriesRound, generateSeriesRoundQualifying, generateSeriesRoundFinals, openSeriesRound, } = deps; const list = state.series || []; if (!list.some((item) => item.id === selectedSeriesId)) selectedSeriesId = list[0]?.id || ""; @@ -187,6 +194,7 @@ export function renderSeriesView(deps) { +

${t("series.seed_hint")}

@@ -277,6 +285,7 @@ export function renderSeriesView(deps) { // "Best lap" = no lap-count metric: practice is then ranked on each driver's best lap. seedLaps: seedMethod === "best_lap" ? 0 : Math.max(1, Number(data.get("seedLaps")) || 3), seedMethod: seedMethod === "best_lap" ? "best_sum" : seedMethod, + seedGroupSize: Math.max(0, Number(data.get("seedGroupSize")) || 0), }); renderView(); // Always say what happened: clicking again for dates already in the series creates nothing. @@ -306,6 +315,7 @@ export function renderSeriesView(deps) { if (action === "toggle") expandedRoundId = expandedRoundId === eventId ? "" : eventId; if (action === "open") { openSeriesRound(eventId); return; } if (action === "run") { runSeriesSession(button.dataset.roundSession); return; } + if (action === "seeding") { runSeriesSeeding(eventId); return; } if (action === "qualifying" && !generateSeriesRoundQualifying(eventId)) window.alert(t("series.no_participants")); if (action === "finals") generateSeriesRoundFinals(eventId); if (action === "remove") { diff --git a/tests/browser_series.js b/tests/browser_series.js index f06cb12..74e858d 100644 --- a/tests/browser_series.js +++ b/tests/browser_series.js @@ -90,11 +90,18 @@ export async function runSeriesSmoke({ evaluate, navigate, savedState, waitFor, await waitFor(async () => JSON.stringify([...(await savedState()).events.find((item) => item.id === roundTwo.id).raceConfig.driverIds].sort()) === JSON.stringify([...roundOneIds].sort()), "round 2 copied from round 1"); // The row's next step is the seeding practice: one click selects it and opens Race Day. - assert.equal(await inRound(roundOne.id, `return row.querySelector('[data-round-action="run"]')?.textContent.trim();`), "▶ Seeding practice"); - await inRound(roundOne.id, `row.querySelector('[data-round-action="run"]').click();`); + // Max 2 per seeding group, 3 drivers today: two groups (2 + 1), split when the button is pressed. + await inRound(roundOne.id, `const input = row.querySelector('input[name="seedGroupSize"]'); input.value = "2"; input.dispatchEvent(new Event("change"));`); + await waitFor(async () => (await savedState()).events.find((item) => item.id === roundOne.id).raceConfig.seedGroupSize === 2, "seed group size saved"); + await waitFor(async () => (await inRound(roundOne.id, `return row.querySelector('[data-round-action="seeding"]')?.textContent.trim();`)) === "▶ Seeding practice (2 groups)", "button says how many groups"); + await inRound(roundOne.id, `row.querySelector('[data-round-action="seeding"]').click();`); await waitFor(async () => (await evaluate(`new URL(location.href).searchParams.get("view")`)) === "race_day", "Race Day opened"); - const practiceId = (await savedState()).sessions.find((session) => session.eventId === roundOne.id && session.type === "practice").id; - await waitFor(async () => (await savedState()).activeSessionId === practiceId, "seeding practice is the active session"); + const seedingGroups = async () => (await savedState()).sessions.filter((session) => session.eventId === roundOne.id && session.type === "practice"); + await waitFor(async () => (await seedingGroups()).length === 2, "seeding split into two groups"); + const groups = await seedingGroups(); + assert.deepEqual(groups.map((session) => [session.name, session.driverIds.length]), [["Seeding practice 1", 1], ["Seeding practice 2", 2]], "fastest group last: the 2 at the top of the order run second"); + const practiceId = groups[0].id; + await waitFor(async () => (await savedState()).activeSessionId === practiceId, "first seeding group is the active session"); assert.ok(await evaluate(`Boolean(document.getElementById("raceDayStart"))`), "only Start is left to press"); await navigate("series", "seriesNew"); await evaluate(`document.querySelector('[data-series-select="${saved.id}"]')?.click()`); diff --git a/tests/series_next_step.test.js b/tests/series_next_step.test.js index 7258286..ed8c92d 100644 --- a/tests/series_next_step.test.js +++ b/tests/series_next_step.test.js @@ -1,6 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { orderSessionsForRunning } from "../src/event_race_logic.js"; +import { orderSessionsForRunning, planSeedingGroups } from "../src/event_race_logic.js"; import { getSeriesRoundNextStep } from "../src/series_logic.js"; import { buildRaceDayQueue } from "../src/race_day_logic.js"; @@ -22,7 +22,8 @@ test("Race Day's next heat follows the running order", () => { }); test("a series round's next step walks seeding -> qualifying -> heats -> finals -> done", () => { - assert.deepEqual(getSeriesRoundNextStep([s("Seeding", "practice")]), { kind: "seeding", session: s("Seeding", "practice") }); + assert.deepEqual(getSeriesRoundNextStep([s("Seeding", "practice")]), { kind: "seeding", session: s("Seeding", "practice"), notStarted: true }); + assert.deepEqual(getSeriesRoundNextStep([s("Seeding 1", "practice", "finished"), s("Seeding 2", "practice")]), { kind: "seeding", session: s("Seeding 2", "practice"), notStarted: false }); assert.deepEqual(getSeriesRoundNextStep([s("Seeding", "practice", "finished")]), { kind: "make_qualifying" }); assert.equal(getSeriesRoundNextStep([s("Seeding", "practice", "running")]).kind, "live"); const quals = [s("Q2 H1", "qualification"), s("Q1 H1", "qualification", "finished"), s("Q1 H2", "qualification")]; @@ -31,3 +32,13 @@ test("a series round's next step walks seeding -> qualifying -> heats -> finals assert.equal(getSeriesRoundNextStep([s("Q1 H1", "qualification", "finished"), s("A Final 1", "final"), s("B Final 1", "final")]).session.name, "B Final 1"); assert.deepEqual(getSeriesRoundNextStep([s("Q1 H1", "qualification", "finished"), s("A Final 1", "final", "finished")]), { kind: "done" }); }); + +test("seeding groups: even split by max size, top of the standings last with fastest-last", () => { + const ids = Array.from({ length: 10 }, (_, index) => `d${index + 1}`); + assert.deepEqual(planSeedingGroups(ids, 5, "fastest_first"), [ids.slice(0, 5), ids.slice(5)]); + assert.deepEqual(planSeedingGroups(ids, 5, "fastest_last"), [ids.slice(5), ids.slice(0, 5)]); + assert.deepEqual(planSeedingGroups(ids.slice(0, 6), 3, "fastest_first").map((group) => group.length), [3, 3]); + assert.deepEqual(planSeedingGroups(ids, 0, "fastest_first"), [ids], "0 = everyone together"); + const fifty = Array.from({ length: 50 }, (_, index) => `x${index}`); + assert.deepEqual(planSeedingGroups(fifty, 6, "fastest_first").map((group) => group.length), [6, 6, 6, 6, 6, 5, 5, 5, 5]); +});