diff --git a/CHANGELOG.md b/CHANGELOG.md index c2772b6..6ec3979 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.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 diff --git a/ROADMAP.md b/ROADMAP.md index 641e2f7..955502c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. diff --git a/package-lock.json b/package-lock.json index 4baa9fd..6df08ee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 7facac8..aa9387e 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/app.js b/src/app.js index c60f6ee..851d139 100644 --- a/src/app.js +++ b/src/app.js @@ -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() { diff --git a/src/race_day_export_logic.js b/src/race_day_export_logic.js new file mode 100644 index 0000000..3d25d55 --- /dev/null +++ b/src/race_day_export_logic.js @@ -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`; +} diff --git a/src/results_archive_view.js b/src/results_archive_view.js index 64cf067..bf592ca 100644 --- a/src/results_archive_view.js +++ b/src/results_archive_view.js @@ -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) { +
${t("archive.no_results")}
`} @@ -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); diff --git a/src/series_view.js b/src/series_view.js index 17018e4..619a558 100644 --- a/src/series_view.js +++ b/src/series_view.js @@ -156,7 +156,7 @@ function renderRoundsTable(rounds, { t, escapeHtml, state }) {