feat(export): CSV for a whole race day from the results archive and series rounds (1.89.40)

This commit is contained in:
larssand committed 2026-11-15 21:40:54 +01:00
1 parent 10b5d0a447
commit 7af4a81aaa
12 files changed
+212 -14

No files matched your search

+6
View File
@@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.89.40 - 2026-11-15
### Added
- **CSV for a whole race day.** In the Results archive, pick the same date in From and To (and a class, or all classes) and press **📄 CSV for the race day**. Each series round also has a 📄 shortcut for its date and class. The file has a summary per heat (place, laps, total time, best and average lap, the same order as the result lists) and then every lap in running order with transponder, lap time, time of day and whether the lap counted. It opens in columns in Excel (semicolons, UTF-8 with BOM).
## 1.89.39
### Added
+1 -1
View File
@@ -980,7 +980,7 @@ Verified: unit tests in `tests/local_cache.test.js`; `tests/browser_decoder_url.
Asked for after the first ÖRC Winter round, where a qualifying went wrong and the club had to rebuild the day's result by hand. Today the only exports are a summary PDF per race (practice/qualifying/final standings, no heat details or lap times) and a raw JSON package. Nothing covers "everything run today, per class" in a form people can read or open in Excel, and results only live in RC RaceCore.
- [ ] **CSV export for a whole race day.** Pick a date and a class (or all classes). One row per lap from every session that day: class, session (in running order), driver, transponder, lap number, lap time, time of day, plus a session summary (position, laps, total time, best lap, average). Frontend only: reuse `buildLeaderboard`, `orderSessionsForRunning` and the existing file download helper; no server or schema change. Button in the Results archive when filtered on a date, with a shortcut on the series round.
- [x] **CSV export for a whole race day.** Done in 1.89.40 (`src/race_day_export_logic.js`; semicolon CSV with BOM so Excel opens it in columns). Pick a date and a class (or all classes). One row per lap from every session that day: class, session (in running order), driver, transponder, lap number, lap time, time of day, plus a session summary (position, laps, total time, best lap, average). Frontend only: reuse `buildLeaderboard`, `orderSessionsForRunning` and the existing file download helper; no server or schema change. Button in the Results archive when filtered on a date, with a shortcut on the series round.
- [ ] **Readable day PDF per class (optional, after the CSV).** The day result used for series points (manual ✎ Result if set), then every session in running order with its full result. Lap-by-lap times stay in the CSV.
- [ ] **Publish to an external results site (e.g. House of RC).** Planned in detail in [House of RC integration](#house-of-rc-integration-entries-in-results-out-planned-2026-11-07) below.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.89.39",
"version": "1.89.40",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.89.39",
"version": "1.89.40",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.89.39",
"version": "1.89.40",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+38 -7
View File
@@ -15,6 +15,7 @@ import { flagHtml, driverCountryCode, countryChoices, setDriverCountryResolver,
import { renderRaceDayView, refreshRaceDayWarmup, refreshRaceDayPrologueClock, updateRaceDayStartDisplay, refreshRaceDayLive } from "./race_day_view.js";
import { assignMarshals, normalizeRaceDays, getRaceDay, upsertRaceDay, orderDaySessions, buildDaySchedule, getAutopilotAction, moveInDayOrder, pickBoardDate, getDueCall, withRaceSetupStart, eventScheduleFromDayRows } from "./day_schedule_logic.js";
import { buildRaceOverview, buildRaceOverviewCsvRows, withQualifyingPlaces, qualifyingPlaces } from "./race_overview_logic.js";
import { buildRaceDayCsvRows, raceDayCsvFilename } from "./race_day_export_logic.js";
import { renderLapChartSvg } from "./lap_chart_logic.js";
import { participantCopySources } from "./participant_picker.js";
import { renderRaceOverviewPanel, bindRaceOverviewPanel } from "./race_overview_view.js";
@@ -1225,9 +1226,9 @@ const exportSeriesPdf = async (series, tables) => {
)),
});
};
const renderSeries = () => renderSeriesView({ mergeDrivers, 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 renderSeries = () => renderSeriesView({ mergeDrivers, exportRaceDayCsv, 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({
getBackendUrl,
getBackendUrl, exportRaceDayCsv,
state, dom, t, escapeHtml, formatLap, formatRaceClock, renderTable,
getClassName, getEventName, buildLeaderboard, getCompetitorPassings,
exportRaceResultsPdf, buildRacePackagePayload, downloadJsonFile, sanitizeFilenameSegment,
@@ -1637,6 +1638,15 @@ const TRANSLATIONS = {
"archive.all_drivers": "Alla förare",
"archive.date_from": "Från datum",
"archive.date_to": "Till datum",
"archive.day_csv": "CSV för racedagen",
"archive.day_csv_hint": "Välj samma datum i Från och Till (och ev. en klass) för att exportera hela dagens varv.",
"archive.day_csv_empty": "Inga avslutade heat det datumet.",
"series.day_csv": "CSV för dagen",
"export.class": "Klass", "export.race": "Race", "export.order": "Ordning", "export.session": "Heat",
"export.lap": "Varv", "export.lap_time": "Varvtid", "export.time_of_day": "Klockslag", "export.counted": "Räknat",
"export.position": "Placering", "export.laps": "Varv", "export.total_time": "Totaltid", "export.best_lap": "Bästa varv",
"export.average_lap": "Snittvarv", "export.summary": "Sammanfattning per heat", "export.laps_all": "Alla varv",
"export.yes": "Ja", "export.no": "Nej",
"archive.date": "Datum",
"archive.event": "Event",
"archive.session": "Session",
@@ -4026,6 +4036,15 @@ const TRANSLATIONS = {
"archive.all_drivers": "All drivers",
"archive.date_from": "From date",
"archive.date_to": "To date",
"archive.day_csv": "CSV for the race day",
"archive.day_csv_hint": "Pick the same date in From and To (and a class if you like) to export every lap of that day.",
"archive.day_csv_empty": "No finished heats on that date.",
"series.day_csv": "CSV for the day",
"export.class": "Class", "export.race": "Race", "export.order": "Order", "export.session": "Heat",
"export.lap": "Lap", "export.lap_time": "Lap time", "export.time_of_day": "Time of day", "export.counted": "Counted",
"export.position": "Position", "export.laps": "Laps", "export.total_time": "Total time", "export.best_lap": "Best lap",
"export.average_lap": "Average lap", "export.summary": "Summary per heat", "export.laps_all": "All laps",
"export.yes": "Yes", "export.no": "No",
"archive.date": "Date",
"archive.event": "Event",
"archive.session": "Session",
@@ -7180,13 +7199,25 @@ function downloadJsonFile(filename, payload) {
downloadBlobFile(filename, new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" }));
}
function rowToCsv(row) {
return row.map((value) => `"${String(value || "").replaceAll('"', '""')}"`).join(",");
function rowToCsv(row, separator = ",") {
return row.map((value) => `"${String(value || "").replaceAll('"', '""')}"`).join(separator);
}
function downloadCsvFile(filename, rows) {
const csv = rows.map((row) => rowToCsv(row)).join("\n");
downloadBlobFile(filename, new Blob([csv], { type: "text/csv;charset=utf-8" }));
// excel: semicolons and a BOM, so Excel with Swedish settings opens it in columns with å/ä/ö.
function downloadCsvFile(filename, rows, { excel = false } = {}) {
const csv = rows.map((row) => rowToCsv(row, excel ? ";" : ",")).join(excel ? "\r\n" : "\n");
downloadBlobFile(filename, new Blob([excel ? "\uFEFF" + csv : csv], { type: "text/csv;charset=utf-8" }));
}
// Every lap of a race day (one class or all) plus a summary per heat, as one CSV.
function exportRaceDayCsv(date, classId = "") {
const rows = buildRaceDayCsvRows(state, {
date, classId, t, formatLap, getClassName, buildLeaderboard,
getPassings: (session, row) => getCompetitorPassings(session, row, { includeInvalid: true }),
invalidLabel: (passing) => getPassingValidationLabel(passing),
});
if (rows.length <= 5) { window.alert(t("archive.day_csv_empty")); return; }
downloadCsvFile(raceDayCsvFilename(date, classId ? getClassName(classId) : ""), rows, { excel: true });
}
function buildDataExportPayload() {
+77
View File
@@ -0,0 +1,77 @@
// CSV export of a whole race day: every lap from every finished heat that day (one class or
// all), plus a summary per heat. Pure - the caller passes the helpers it already has
// (buildLeaderboard for the result as shown, the passings of one competitor), so the export
// shows the same order, penalties and judging changes as the result lists.
import { orderSessionsForRunning } from "./event_race_logic.js";
export function raceDayDate(session, event) {
return event?.date || (session?.endedAt ? new Date(session.endedAt).toISOString().slice(0, 10) : "");
}
// The finished heats of the day in running order: race by race (sorted by class, then name),
// each race's heats as Race Setup runs them.
export function raceDaySessions(state, { date, classId = "" } = {}) {
const events = new Map((state?.events || []).map((event) => [event.id, event]));
const byEvent = new Map();
(state?.sessions || []).forEach((session) => {
if (session?.status !== "finished") return;
const event = events.get(session.eventId) || null;
if (!date || raceDayDate(session, event) !== date) return;
if (classId && event?.classId !== classId) return;
const key = event?.id || `session:${session.id}`;
if (!byEvent.has(key)) byEvent.set(key, { event, sessions: [] });
byEvent.get(key).sessions.push(session);
});
return [...byEvent.values()]
.sort((a, b) => String(a.event?.classId || "").localeCompare(String(b.event?.classId || ""))
|| String(a.event?.name || "").localeCompare(String(b.event?.name || ""), "sv"))
.flatMap(({ event, sessions }) => orderSessionsForRunning(sessions, event?.sessionOrder || []).map((session) => ({ session, event })));
}
const defaultClock = (timestamp) => (timestamp ? new Date(timestamp).toTimeString().slice(0, 8) : "");
const nameOf = (row) => row.displayName || row.driverName || row.teamName || "";
// One row per lap; a lap that was not counted (under the minimum lap time, removed) has no lap
// number and says why.
export function buildRaceDayLapRows(state, options = {}) {
const { buildLeaderboard, getPassings, getClassName = () => "", formatLap = String, formatClock = defaultClock, invalidLabel = () => "", t = (key) => key } = options;
const rows = [[t("export.class"), t("export.race"), t("export.order"), t("export.session"), t("table.driver"), t("table.transponder"), t("export.lap"), t("export.lap_time"), t("export.time_of_day"), t("export.counted")]];
raceDaySessions(state, options).forEach(({ session, event }, index) => {
buildLeaderboard(session).forEach((row) => {
let lap = 0;
getPassings(session, row).forEach((passing) => {
const counted = passing.validLap !== false;
if (counted) lap += 1;
rows.push([getClassName(event?.classId || ""), event?.name || "", String(index + 1), session.name || "", nameOf(row), String(passing.transponder || row.transponder || ""),
counted ? String(lap) : "", formatLap(Number(passing.lapMs || 0)), formatClock(Number(passing.timestamp || 0)), counted ? t("export.yes") : invalidLabel(passing) || t("export.no")]);
});
});
});
return rows;
}
// One row per driver and heat: place, laps, total time, best and average lap.
export function buildRaceDaySummaryRows(state, options = {}) {
const { buildLeaderboard, getPassings, getClassName = () => "", formatLap = String, t = (key) => key } = options;
const rows = [[t("export.class"), t("export.race"), t("export.order"), t("export.session"), t("export.position"), t("table.driver"), t("table.transponder"), t("export.laps"), t("export.total_time"), t("export.best_lap"), t("export.average_lap")]];
raceDaySessions(state, options).forEach(({ session, event }, index) => {
buildLeaderboard(session).forEach((row, place) => {
const laps = getPassings(session, row).filter((passing) => passing.validLap !== false).map((passing) => Number(passing.lapMs || 0)).filter((ms) => ms > 0);
const average = laps.length ? Math.round(laps.reduce((sum, ms) => sum + ms, 0) / laps.length) : 0;
rows.push([getClassName(event?.classId || ""), event?.name || "", String(index + 1), session.name || "", String(place + 1), nameOf(row), String(row.transponder || ""),
String(row.laps || 0), row.totalElapsedMs ? formatLap(Number(row.totalElapsedMs)) : "", row.bestLapMs ? formatLap(Number(row.bestLapMs)) : "", average ? formatLap(average) : ""]);
});
});
return rows;
}
// Both in one file: the summary first, a blank row, then every lap.
export function buildRaceDayCsvRows(state, options = {}) {
const t = options.t || ((key) => key);
return [[t("export.summary")], ...buildRaceDaySummaryRows(state, options), [], [t("export.laps_all")], ...buildRaceDayLapRows(state, options)];
}
export function raceDayCsvFilename(date, className = "") {
const part = String(className || "").trim().replace(/[^a-z0-9åäöÅÄÖ_-]+/gi, "_").replace(/^_+|_+$/g, "");
return `racedag_${date}${part ? `_${part}` : ""}.csv`;
}
+10
View File
@@ -144,9 +144,12 @@ export function renderResultsArchiveView(deps) {
getTrackLayoutLabel, renderRaceOverview = () => "", bindRaceOverview = () => {},
getQualifyingPlaces = () => new Map(),
getBackendUrl = () => "",
exportRaceDayCsv = () => {},
} = deps;
const filters = getArchiveFilters();
// A whole race day as CSV: one date picked (from = to), the class filter or all classes.
const dayExportDate = filters.dateFrom && filters.dateFrom === filters.dateTo ? filters.dateFrom : "";
const allRows = buildArchiveRows(state, { getEventName, getClassName, getTrackLayoutLabel, buildLeaderboard });
const filteredRows = allRows.filter((row) => matchesArchiveFilters(row, filters));
const selectedSessionId = getSelectedSessionId();
@@ -205,6 +208,10 @@ export function renderResultsArchiveView(deps) {
<label><span>${t("archive.date_from")}</span><input id="archiveDateFrom" type="date" value="${escapeHtml(filters.dateFrom)}" /></label>
<label><span>${t("archive.date_to")}</span><input id="archiveDateTo" type="date" value="${escapeHtml(filters.dateTo)}" /></label>
</div>
<div class="archive-day-export">
<button type="button" class="btn" id="archiveDayCsv" ${dayExportDate ? "" : "disabled"}>📄 ${t("archive.day_csv")}</button>
<span class="hint">${dayExportDate ? escapeHtml(dayExportDate) : t("archive.day_csv_hint")}</span>
</div>
</div>
<div class="panel-body" id="archiveResultsBody">
${groups.length ? table : `<p>${t("archive.no_results")}</p>`}
@@ -275,6 +282,9 @@ export function renderResultsArchiveView(deps) {
setArchiveFilters({ ...filters, dateTo: event.currentTarget.value });
rerender();
});
document.getElementById("archiveDayCsv")?.addEventListener("click", () => {
if (dayExportDate) exportRaceDayCsv(dayExportDate, filters.classId || "");
});
document.querySelectorAll("[data-archive-event]").forEach((button) => {
button.addEventListener("click", () => {
setSelectedEventKey(button.dataset.archiveEvent);
+3 -2
View File
@@ -156,7 +156,7 @@ function renderRoundsTable(rounds, { t, escapeHtml, state }) {
<td>${number(round, "carsPerHeat", config.carsPerHeat || 8, 2)}</td>
<td>${number(round, "seedGroupSize", config.seedGroupSize || 0, 0)}</td>
<td><span class="pill series-status-${round.status}">${t(`series.status_${round.status}`)}</span>${round.manualResult ? `<br><span class="pill series-result-pill">${t("series.result_manual")}</span>` : ""}${round.qualHeatCount ? `<br><small>${t("series.heats_made", { heats: round.qualHeatCount })}</small>` : ""}</td>
<td><div class="series-round-actions">${action}<button class="btn btn-mini" type="button" data-round-action="result" title="${escapeHtml(t("series.result_title"))}">✎ ${t("series.result_button")}</button><button class="btn btn-mini" type="button" data-round-action="open">${t("series.open_race")}</button><button class="btn btn-mini" type="button" data-round-action="remove" title="${escapeHtml(t("series.remove_round"))}">✕</button></div></td>
<td><div class="series-round-actions">${action}<button class="btn btn-mini" type="button" data-round-action="result" title="${escapeHtml(t("series.result_title"))}">✎ ${t("series.result_button")}</button><button class="btn btn-mini" type="button" data-round-action="open">${t("series.open_race")}</button>${round.event.date && round.status !== "not_started" ? `<button class="btn btn-mini" type="button" data-round-action="day_csv" title="${escapeHtml(t("series.day_csv"))}">📄</button>` : ""}<button class="btn btn-mini" type="button" data-round-action="remove" title="${escapeHtml(t("series.remove_round"))}">✕</button></div></td>
</tr>
${expandedRoundId === round.event.id ? `<tr class="series-round-detail"><td colspan="9">${renderRoundParticipants(round, { t, escapeHtml, classes: state?.classes || [] })}</td></tr>` : ""}
${resultRoundId === round.event.id ? `<tr class="series-round-detail"><td colspan="9">${renderRoundResultEditor(round, { t, escapeHtml, state })}</td></tr>` : ""}`;
@@ -203,7 +203,7 @@ function renderStandingsTable(table, { t, escapeHtml, drivers = null }) {
export function renderSeriesView(deps) {
const {
state, dom, t, escapeHtml, saveState, renderView, uid, getClassName, getSeriesStandings, createSeriesEvents, getRaceFormatPresets, exportSeriesPdf, printSeries,
mergeDrivers = () => false, getSeriesRounds, deleteSeriesRaces, runSeriesSession, runSeriesSeeding, setSeriesRoundFormat, setSeriesRoundParticipants, copySeriesRoundParticipants, addDriverToSeriesRound, generateSeriesRoundQualifying, generateSeriesRoundFinals, openSeriesRound,
mergeDrivers = () => false, exportRaceDayCsv = () => {}, 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 || "";
@@ -366,6 +366,7 @@ export function renderSeriesView(deps) {
if (!resultDraft.length) resultDraft = [...(round?.participantIds || [])];
}
if (action === "open") { openSeriesRound(eventId); return; }
if (action === "day_csv") { const event = state.events.find((item) => item.id === eventId); if (event) exportRaceDayCsv(event.date, event.classId || ""); 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"));
+2
View File
@@ -5118,3 +5118,5 @@ tr.is-selected td { background: color-mix(in srgb, var(--danger) 12%, transparen
.participant-group > .hint { margin: 0 0 12px; }
.participant-only-selected { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; cursor: pointer; }
.participant-only-selected input { width: auto; margin: 0; }
.archive-day-export { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-top: 12px; }
+5 -1
View File
@@ -24,11 +24,15 @@ export async function runArchiveQualifyingSmoke({ evaluate, navigate, savedState
await navigate("archive", "archiveDriverFilter");
await waitFor(async () => evaluate(`Boolean(document.querySelector('[data-archive-event="aq_event"]'))`), "the race is in the archive");
// Race day CSV: off until one date is picked (from = to).
assert.equal(await evaluate(`document.getElementById("archiveDayCsv").disabled`), true, "day CSV waits for a date");
for (const id of ["archiveDateFrom", "archiveDateTo"]) await evaluate(`(() => { const input = document.getElementById("${id}"); input.value = "${event.date}"; input.dispatchEvent(new Event("change")); })()`);
await waitFor(async () => evaluate(`document.getElementById("archiveDayCsv")?.disabled === false`), "day CSV is on for one date");
await evaluate(`document.querySelector('[data-archive-event="aq_event"]').click()`);
await waitFor(async () => evaluate(`Boolean(document.querySelector('[data-archive-open="aq_f1"]'))`), "the final heat is listed");
await evaluate(`document.querySelector('[data-archive-open="aq_f1"]').click()`);
await waitFor(async () => evaluate(`Boolean(document.querySelector(".archive-detail .tq-badge"))`), "the final heat shows TQ");
const rows = await evaluate(`[...document.querySelectorAll(".archive-detail tbody tr")].slice(0, 2).map((row) => [...row.children].slice(0, 3).map((cell) => cell.textContent.trim()))`);
assert.deepEqual(rows, [["1", "2", "AQ Winner"], ["2", "TQ", "AQ Pole"]], "winner qualified 2nd, the pole sitter finished 2nd");
console.log("PASS results archive: a final heat shows each driver's qualifying place with TQ for the top qualifier");
console.log("PASS results archive: a final heat shows each driver's qualifying place with TQ for the top qualifier; day CSV turns on for one date");
}
+66
View File
@@ -0,0 +1,66 @@
import test from "node:test";
import assert from "node:assert/strict";
import { raceDaySessions, buildRaceDayLapRows, buildRaceDaySummaryRows, buildRaceDayCsvRows, raceDayCsvFilename } from "../src/race_day_export_logic.js";
const passing = (driverId, timestamp, lapMs, extra = {}) => ({ driverId, competitorKey: `driver_${driverId}`, transponder: `T${driverId}`, timestamp, lapMs, ...extra });
const state = () => ({
classes: [{ id: "4wd", name: "4WD" }, { id: "2wd", name: "2WD" }],
events: [{ id: "r4", name: "Cup 4WD", classId: "4wd", date: "2026-11-15" }, { id: "r2", name: "Cup 2WD", classId: "2wd", date: "2026-11-15" }, { id: "old", name: "Cup 4WD", classId: "4wd", date: "2026-11-01" }],
sessions: [
{ id: "a1", eventId: "r4", name: "A1", type: "final", status: "finished", finalLeg: 1 },
{ id: "q1", eventId: "r4", name: "Q1 H1", type: "qualifying", status: "finished" },
{ id: "q2", eventId: "r4", name: "Q2 H1", type: "qualifying", status: "ready" },
{ id: "b1", eventId: "r2", name: "Q1 H1", type: "qualifying", status: "finished" },
{ id: "x", eventId: "old", name: "Q1 H1", type: "qualifying", status: "finished" },
],
resultsBySession: {
q1: { passings: [passing("anna", 1000, 20000), passing("anna", 2000, 4000, { validLap: false, invalidReason: "below_min" }), passing("anna", 3000, 22000), passing("bo", 1500, 21000)] },
a1: { passings: [passing("bo", 5000, 19000)] },
b1: { passings: [passing("cid", 7000, 25000)] },
},
});
const helpers = (s) => ({
buildLeaderboard: (session) => {
const ids = [...new Set((s.resultsBySession[session.id]?.passings || []).map((p) => p.driverId))];
return ids.map((id) => ({ key: `driver_${id}`, driverId: id, driverName: id, transponder: `T${id}`, laps: s.resultsBySession[session.id].passings.filter((p) => p.driverId === id && p.validLap !== false).length, totalElapsedMs: 42000, bestLapMs: 20000 }));
},
getPassings: (session, row) => s.resultsBySession[session.id].passings.filter((p) => p.competitorKey === row.key),
getClassName: (id) => s.classes.find((c) => c.id === id)?.name || "",
formatLap: (ms) => (ms / 1000).toFixed(3),
formatClock: (ts) => `t${ts}`,
invalidLabel: (p) => p.invalidReason,
});
test("the day's finished heats only, race by race in running order, one class or all", () => {
const s = state();
assert.deepEqual(raceDaySessions(s, { date: "2026-11-15" }).map(({ session }) => session.id), ["b1", "q1", "a1"]);
assert.deepEqual(raceDaySessions(s, { date: "2026-11-15", classId: "4wd" }).map(({ session }) => session.id), ["q1", "a1"]);
assert.deepEqual(raceDaySessions(s, { date: "2026-11-01" }).map(({ session }) => session.id), ["x"]);
assert.deepEqual(raceDaySessions(s, {}), []);
});
test("one row per lap; a lap not counted has no lap number and says why", () => {
const s = state();
const rows = buildRaceDayLapRows(s, { date: "2026-11-15", classId: "4wd", ...helpers(s) });
assert.equal(rows.length, 1 + 4 + 1);
assert.deepEqual(rows[1], ["4WD", "Cup 4WD", "1", "Q1 H1", "anna", "Tanna", "1", "20.000", "t1000", "export.yes"]);
assert.deepEqual(rows[2].slice(6), ["", "4.000", "t2000", "below_min"]);
assert.equal(rows[3][6], "2");
assert.deepEqual(rows[5].slice(2, 5), ["2", "A1", "bo"]);
});
test("summary per heat: place, laps, times, average of counted laps only", () => {
const s = state();
const rows = buildRaceDaySummaryRows(s, { date: "2026-11-15", classId: "4wd", ...helpers(s) });
assert.deepEqual(rows[1], ["4WD", "Cup 4WD", "1", "Q1 H1", "1", "anna", "Tanna", "2", "42.000", "20.000", "21.000"]);
assert.equal(rows[2][4], "2");
const all = buildRaceDayCsvRows(s, { date: "2026-11-15", ...helpers(s) });
assert.deepEqual(all[0], ["export.summary"]);
assert.ok(all.some((row) => row.length === 0));
});
test("file name has the date and the class", () => {
assert.equal(raceDayCsvFilename("2026-11-15", "4WD"), "racedag_2026-11-15_4WD.csv");
assert.equal(raceDayCsvFilename("2026-11-15", ""), "racedag_2026-11-15.csv");
assert.equal(raceDayCsvFilename("2026-11-15", "Open Class / 1:10"), "racedag_2026-11-15_Open_Class_1_10.csv");
});
+1
View File
@@ -38,6 +38,7 @@ import "./public_training_profile.test.js";
import "./race_timing_logic.test.js";
import "./track_layouts_logic.test.js";
import "./race_day_logic.test.js";
import "./race_day_export.test.js";
import "./backup_service.test.js";
import "./judging_logic.test.js";
import "./session_control.test.js";