From 3870510d8ccffdf4ac41293afe2d4b495e8f208f Mon Sep 17 00:00:00 2001 From: larssand Date: Sun, 8 Nov 2026 23:19:43 +0100 Subject: [PATCH] feat(houseofrc): send heats automatically after every heat, show send status, warn before sending (1.85.0) --- CHANGELOG.md | 6 +++++ README.md | 2 +- README.sv.md | 2 +- ROADMAP.md | 2 +- package-lock.json | 4 +-- package.json | 2 +- src/app.js | 45 +++++++++++++++++++++++++++++++-- src/event_manager_controller.js | 7 +++++ src/event_manager_view.js | 2 ++ src/houseofrc_logic.js | 43 +++++++++++++++++++++++++++++++ src/houseofrc_view.js | 35 ++++++++++++++++++++----- src/race_day_view.js | 3 ++- src/styles.css | 2 ++ tests/browser_houseofrc.js | 24 +++++++++++++++--- tests/houseofrc_logic.test.js | 28 ++++++++++++++++++++ 15 files changed, 189 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc97521..39bc112 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.85.0 + +- **Send heats to House of RC automatically:** tick **Send heats automatically** under Manage → Participants on a race made from House of RC. After every qualifying heat or final, the race controller sends heats and qualifying by itself – never the final placings, so no driver is notified by mistake. Without internet it tries again every minute until it gets through. +- **Send status** next to the race on Race Day and in Manage: "🏠 Sent 21:19 · heats", "🏠 Sent 22:05 · final results" or "⚠️ Waiting to send – trying again". +- **Checks before sending:** the send window warns about a heat still running, finals not run yet, participants without a House of RC entry, and when nothing has changed since the last send. + ## 1.84.2 - **Video guides re-recorded** for the current interface, plus a new one: **House of RC – fetch entries, late entries and send results** (Guide → Videos and README). README screenshots refreshed. diff --git a/README.md b/README.md index 80dc059..e23d90b 100644 --- a/README.md +++ b/README.md @@ -322,7 +322,7 @@ Erik Eriksson;654321;4WD;Associated;; RaceCore is meant for a trusted race network: - **Admin PIN** (Settings → System & backup, off by default) protects every change through the API. The login lasts 30 days and is throttled against guessing. - **Race Controller Master:** one computer at a time runs the race (the decoder, start, pause, resume, stop, false start, resetting a heat and the autopilot, also from the speaker panel). Judging corrections and the other calls work from any computer. The computer running the server (page opened on `localhost`) becomes master on its own and shows a green line "🎙 You are the Race Controller Master" with **Release master**. Phones and other computers follow the race live (updated every second), show "You are following the race …" and become master only when someone presses the button; that computer then remembers the role. They can also prepare drivers and races. Whoever works as race controller presses **Take over as master**, and the previous master lets go of the decoder within seconds. With the admin PIN on, taking over needs a login. Name the computer under Settings → System, e.g. "Speaker booth". Overlays and OBS are always view-only. -- **House of RC:** under Settings → System → 🏠 House of RC you save the club's API key once (stored on the server only, never shown again) and press **Test connection**. Drivers → **🏠 Fetch from House of RC** fills in names and brands from the transponders (only what you tick), and a known transponder fills in a new driver. With the key of the club running the event, the race wizard's **🏠 Fetch from House of RC** lists the club's events; pick an event and one of its classes, and the name, date, class and entered drivers with their transponders are filled in. Later, Manage → Participants → **🔄 Fetch changes from House of RC** adds late entries and takes out withdrawals. **📤 Send results to House of RC** previews and sends the results to the entries: heats and qualifying during the day, the final placings when the finals are run. Only drivers entered on House of RC (with their own account) get results there; others are listed as not sent. +- **House of RC:** under Settings → System → 🏠 House of RC you save the club's API key once (stored on the server only, never shown again) and press **Test connection**. Drivers → **🏠 Fetch from House of RC** fills in names and brands from the transponders (only what you tick), and a known transponder fills in a new driver. With the key of the club running the event, the race wizard's **🏠 Fetch from House of RC** lists the club's events; pick an event and one of its classes, and the name, date, class and entered drivers with their transponders are filled in. Later, Manage → Participants → **🔄 Fetch changes from House of RC** adds late entries and takes out withdrawals. **📤 Send results to House of RC** previews and sends the results to the entries: heats and qualifying during the day, the final placings when the finals are run. Only drivers entered on House of RC (with their own account) get results there; others are listed as not sent. Tick **Send heats automatically** and the race controller sends heats and qualifying after every heat by itself (semi-live), retrying without internet; the final placings are always sent by hand. - **`RC_ADMIN_ALLOWED_CIDRS`** restricts admin changes to certain addresses or networks, e.g. `192.168.1.0/24`. - **`RC_ALLOWED_ORIGINS`** is for a UI deliberately served from another address. - **Don't expose port 8081 to the internet.** Reads are not PIN protected. Publish only the public overlay and mobile profile paths through a reverse proxy or VPN. diff --git a/README.sv.md b/README.sv.md index 11697a4..04f126a 100644 --- a/README.sv.md +++ b/README.sv.md @@ -335,7 +335,7 @@ Erik Eriksson;654321;4WD;Associated;; RaceCore är tänkt för ett betrott racenätverk: - **Admin-PIN** (Inställningar → System & backup, av som standard) skyddar alla ändringar via API:t. Inloggningen gäller i 30 dagar och är skyddad mot gissning. - **Race Controller Master:** bara en dator åt gången kör racet (decodern, start, paus, fortsätt, stopp, tjuvstart, nollställ heat och autopiloten, även från speakerpanelen). Domarvyns korrigeringar och övriga utrop fungerar från alla datorer. Datorn som kör servern (sidan öppnad på `localhost`) blir master av sig själv och visar en grön rad "🎙 Du är Race Controller Master" med **Släpp master**. Mobiler och andra datorer följer racet live (uppdateras varje sekund), visar "Du följer racet …" och blir master bara när någon trycker på knappen; den datorn minns sedan rollen. De kan också förbereda förare och race. Den som jobbar som race controller trycker **Ta över som master**, och den förra mastern släpper decodern inom några sekunder. Med admin-PIN krävs inloggning för att ta över. Ge datorn ett namn under Inställningar → System, t.ex. "Speakerbåset". Overlays och OBS är alltid bara visning. -- **House of RC:** under Inställningar → System → 🏠 House of RC sparar du klubbens API-nyckel en gång (bara på servern, visas aldrig igen) och trycker **Testa anslutning**. Förare → **🏠 Hämta från House of RC** fyller i namn och märke utifrån transpondrarna (bara det du bockar i), och en känd transponder fyller i en ny förare. Med nyckeln för klubben som arrangerar tävlingen listar Race-guidens **🏠 Hämta från House of RC** klubbens tävlingar; välj tävling och en av dess klasser så fylls namn, datum, klass och anmälda förare med transpondrar i. Senare lägger Hantera → Deltagare → **🔄 Hämta ändringar från House of RC** till sena anmälningar och tar bort avanmälda. **📤 Skicka resultat till House of RC** förhandsgranskar och skickar resultatet till anmälningarna: heat och kval under dagen, slutplaceringen när finalerna är körda. Bara förare som är anmälda på House of RC (med eget konto) får resultat där; övriga listas som inte skickade. +- **House of RC:** under Inställningar → System → 🏠 House of RC sparar du klubbens API-nyckel en gång (bara på servern, visas aldrig igen) och trycker **Testa anslutning**. Förare → **🏠 Hämta från House of RC** fyller i namn och märke utifrån transpondrarna (bara det du bockar i), och en känd transponder fyller i en ny förare. Med nyckeln för klubben som arrangerar tävlingen listar Race-guidens **🏠 Hämta från House of RC** klubbens tävlingar; välj tävling och en av dess klasser så fylls namn, datum, klass och anmälda förare med transpondrar i. Senare lägger Hantera → Deltagare → **🔄 Hämta ändringar från House of RC** till sena anmälningar och tar bort avanmälda. **📤 Skicka resultat till House of RC** förhandsgranskar och skickar resultatet till anmälningarna: heat och kval under dagen, slutplaceringen när finalerna är körda. Bara förare som är anmälda på House of RC (med eget konto) får resultat där; övriga listas som inte skickade. Bocka i **Skicka heat automatiskt** så skickar race controller-datorn heat och kval efter varje heat av sig själv (halvlive) och försöker igen utan internet; slutplaceringen skickas alltid för hand. - **`RC_ADMIN_ALLOWED_CIDRS`** begränsar adminändringar till vissa adresser eller nät, till exempel `192.168.1.0/24`. - **`RC_ALLOWED_ORIGINS`** används för ett gränssnitt som medvetet körs från en annan adress. - **Exponera inte port 8081 mot internet.** Läsningar skyddas inte av PIN. Publicera bara sökvägarna för publik overlay och mobilprofil via reverse proxy eller VPN. diff --git a/ROADMAP.md b/ROADMAP.md index cf1099e..d004040 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1011,7 +1011,7 @@ Status 2026-11-08 (1.78.0-1.80.0): Next: - [x] 1.83.0 **Results back:** `POST /v1/timing/events/{id}/entries` with `{ entries: [{ id, ranking, qualification, points, tq, laps_time, data }] }`, all or nothing, up to 2000 entries. `data.result` is shown on House of RC (`main`, `main_position`, `bumped_from`, `race`, `best_lap`, `average_lap`, `points`, `heats[]`). The race already keeps each driver's entry id (`event.houseOfRc.entryIds`). -- [ ] **Semi-live (Conny's idea):** by hand since 1.83.0 (send "Heats and qualifying" after each heat); still to do: send automatically when a heat finishes. +- [x] 1.85.0 **Semi-live (Conny's idea):** "Send heats automatically" sends heats and qualifying after every heat, with retries; status on Race Day and in Manage. - [x] 1.82.0: re-fetch in Manage (late entries, withdrawals), remembered class mapping, brand differences offered. - [ ] One click for all classes: create one race per House of RC class. - [ ] The URL and JSON body for posting results, with an example of a qualifying-plus-finals result (TQ, A/B/C finals). Can a result be posted again, overwriting the previous one, after a correction? diff --git a/package-lock.json b/package-lock.json index c148e3e..2c8118b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.84.2", + "version": "1.85.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.84.2", + "version": "1.85.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index fe94ae5..d4610de 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.84.2", + "version": "1.85.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 a0c23d8..d761d09 100644 --- a/src/app.js +++ b/src/app.js @@ -6,6 +6,8 @@ import { getOverlayModeLabel, buildOverlayPanels, renderOverlaySidePanel, render import { renderSettings, openSettingsTab } from "./settings.js"; import { buildRaceDayQueue, buildRaceDayPreflight, getRaceDriverIds, shouldOfferFinals } from "./race_day_logic.js"; +import { findHouseOfRcAutoSends } from "./houseofrc_logic.js"; +import { sendHouseOfRcResults, renderHouseOfRcSendStatus } from "./houseofrc_view.js"; import { recordTransponderSighting, buildWarmupCheck, createPrologue, getPrologueRemainingMs, holdPrologue, resumePrologue, setPrologueRemaining, takeDuePrologueCall, formatPrologueTime, getPrologueHandoverMs, normalizePrologueSec, getPrologueMarks } from "./prologue_logic.js"; import { findTransponderConflict, getDriverProfileId } from "./driver_profile_logic.js"; import { renderRaceDayView, refreshRaceDayWarmup, refreshRaceDayPrologueClock, updateRaceDayStartDisplay, refreshRaceDayLive } from "./race_day_view.js"; @@ -518,6 +520,23 @@ function buildHeatCallDrivers(session) { function getDueCallFor(date) { return getDueCall(buildDayRows(date), { day: getDayPlan(date), snoozedUntil: (id) => callSnoozes.get(id) || 0 }); } +// House of RC "send heats automatically": the race controller sends heats and qualifying of +// every race where a heat has finished since the last send; never the final placings. +// A failed send is tried again a minute later (findHouseOfRcAutoSends). +let houseOfRcAutoSendBusy = false; +async function tickHouseOfRcAutoSend() { + if (overlayMode || houseOfRcAutoSendBusy || !isRaceMaster()) return; + const due = findHouseOfRcAutoSends(state); + if (!due.length) return; + houseOfRcAutoSendBusy = true; + try { + for (const event of due) await sendHouseOfRcResults({ event, overview: getRaceOverview(event), state, final: false }); + saveState(); + if (currentView === "race_day") renderView(); + } finally { + houseOfRcAutoSendBusy = false; + } +} function tickDayCalls() { if (overlayMode || !isRaceMaster()) return; if (autopilotDate) { @@ -755,6 +774,7 @@ const renderRaceDay = () => renderRaceDayView({ setCompetitorLapStatus, ...speakerPanelDeps, shouldOfferFinals: (eventId) => shouldOfferFinals(state, eventId), + renderHouseOfRcStatus: (eventId) => renderHouseOfRcSendStatus(state.events.find((event) => event.id === eventId), { t, escapeHtml }), createFinalsForEvent: (eventId) => { const event = state.events.find((item) => item.id === eventId); if (!event || !generateFinalsForRace(event)) return null; @@ -2223,6 +2243,17 @@ const TRANSLATIONS = { "houseofrc.entries_class": "Klass hos oss", "houseofrc.entries_hor_class": "Klass på House of RC", "houseofrc.refresh_button": "Hämta ändringar från House of RC", + "houseofrc.auto_send": "Skicka heat automatiskt", + "houseofrc.auto_send_hint": "Efter varje heat skickar race controller-datorn heat och kval till House of RC (inte slutplaceringen). Utan internet försöker den igen varje minut.", + "houseofrc.status_auto_waiting": "Skickas efter nästa heat", + "houseofrc.status_sent_heats": "Skickat {time} · heat", + "houseofrc.status_sent_final": "Skickat {time} · slutresultat", + "houseofrc.status_failed": "Kunde inte skicka {time}", + "houseofrc.status_failed_retry": "Väntar på att skicka ({time}) – försöker igen", + "houseofrc.warn_running": "Ett heat körs just nu – dess resultat är inte klart.", + "houseofrc.warn_finals_left": "Finaler som inte är körda: {names}.", + "houseofrc.warn_missing": "{count} deltagare saknar anmälan på House of RC och kommer inte med.", + "houseofrc.warn_unchanged": "Inget har ändrats sedan senaste utskicket.", "houseofrc.refresh_link_only": "Kör redan – kopplas till anmälan", "houseofrc.results_button": "Skicka resultat till House of RC", "houseofrc.results_hint": "Förhandsgranska och skicka resultatet till {name}", @@ -2240,7 +2271,6 @@ const TRANSLATIONS = { "houseofrc.results_send": "Skicka ({count})", "houseofrc.results_sending": "Skickar …", "houseofrc.results_sent": "{count} anmälningar uppdaterade på House of RC.", - "houseofrc.results_last": "senast skickat {time}", "houseofrc.results_close": "Stäng", "houseofrc.err_rejected": "House of RC tog inte emot resultatet, inget skrevs: {message}", "houseofrc.refresh_hint": "Nya anmälningar och avanmälningar sedan racet skapades ({name})", @@ -4467,6 +4497,17 @@ const TRANSLATIONS = { "houseofrc.entries_class": "Our class", "houseofrc.entries_hor_class": "Class on House of RC", "houseofrc.refresh_button": "Fetch changes from House of RC", + "houseofrc.auto_send": "Send heats automatically", + "houseofrc.auto_send_hint": "After every heat the race controller sends heats and qualifying to House of RC (not the final placings). Without internet it tries again every minute.", + "houseofrc.status_auto_waiting": "Sent after the next heat", + "houseofrc.status_sent_heats": "Sent {time} · heats", + "houseofrc.status_sent_final": "Sent {time} · final results", + "houseofrc.status_failed": "Could not send {time}", + "houseofrc.status_failed_retry": "Waiting to send ({time}) – trying again", + "houseofrc.warn_running": "A heat is running – its result isn't complete yet.", + "houseofrc.warn_finals_left": "Finals not run yet: {names}.", + "houseofrc.warn_missing": "{count} participants have no House of RC entry and are left out.", + "houseofrc.warn_unchanged": "Nothing has changed since the last send.", "houseofrc.refresh_link_only": "Already racing – linked to the entry", "houseofrc.results_button": "Send results to House of RC", "houseofrc.results_hint": "Preview and send the results to {name}", @@ -4484,7 +4525,6 @@ const TRANSLATIONS = { "houseofrc.results_send": "Send ({count})", "houseofrc.results_sending": "Sending …", "houseofrc.results_sent": "{count} entries updated on House of RC.", - "houseofrc.results_last": "last sent {time}", "houseofrc.results_close": "Close", "houseofrc.err_rejected": "House of RC did not accept the results, nothing was written: {message}", "houseofrc.refresh_hint": "New entries and withdrawals since the race was created ({name})", @@ -6016,6 +6056,7 @@ async function init() { setInterval(tickClock, 1000); updateSyncStatus(); setInterval(updateSyncStatus, 1000); + setInterval(tickHouseOfRcAutoSend, 10000); document.getElementById("syncStatusRetry")?.addEventListener("click", async () => { if (backend.pendingWrites) return; if (localStateDirty || backend.writeError || backend.passingError) { diff --git a/src/event_manager_controller.js b/src/event_manager_controller.js index ef20253..10bbcef 100644 --- a/src/event_manager_controller.js +++ b/src/event_manager_controller.js @@ -614,6 +614,13 @@ export function renderEventManagerView(context) { }, })); + // Send heats and qualifying to House of RC by itself after every heat (see app.js). + document.getElementById("houseOfRcAutoSend")?.addEventListener("change", (change) => { + event.houseOfRc.autoSend = change.currentTarget.checked; + saveState(); + refreshManager(); + }); + // Race made from House of RC: preview and send the results to its entries. document.getElementById("houseOfRcSendResults")?.addEventListener("click", () => openHouseOfRcResultsPost({ event, overview: getRaceOverview(event), state, t, escapeHtml, saveState, diff --git a/src/event_manager_view.js b/src/event_manager_view.js index 721339c..3a2ecf4 100644 --- a/src/event_manager_view.js +++ b/src/event_manager_view.js @@ -1,3 +1,4 @@ +import { renderHouseOfRcSendStatus } from "./houseofrc_view.js"; import { PROLOGUE_OPTIONS_SEC, formatPrologueOption } from "./prologue_logic.js"; import { groupSessionsBySteps } from "./race_list_logic.js"; @@ -190,6 +191,7 @@ export function renderEventManagerMarkup(context) { ${event.houseOfRc?.eventId ? `` : ""} ${event.houseOfRc?.eventId ? `` : ""} + ${event.houseOfRc?.eventId ? ` ${renderHouseOfRcSendStatus(event, { t, escapeHtml })}` : ""} ${(() => { const card = (driver) => { diff --git a/src/houseofrc_logic.js b/src/houseofrc_logic.js index 44a3e0c..b55f7e3 100644 --- a/src/houseofrc_logic.js +++ b/src/houseofrc_logic.js @@ -233,3 +233,46 @@ const toMs = (text) => { const [minutes, seconds] = String(text).includes(":") ? String(text).split(":") : ["0", text]; return Number(minutes) * 60000 + Number(seconds) * 1000; }; + +// What the results are built from: every finished qualifying heat and final, with when it +// ended. A change means there is something new to send. +export function houseOfRcResultsSignature(event, sessions = []) { + return sessions + .filter((session) => session.eventId === event?.id && ["qualification", "final"].includes(session.type) && ["finished", "stopped"].includes(session.status)) + .map((session) => `${session.id}:${Number(session.endedAt) || 0}`) + .sort() + .join("|"); +} + +// Races with "send heats automatically" on that have a finished heat not sent yet. A failed +// try waits retryMs before the next one (no internet at the track: it keeps trying). +export const HOUSE_OF_RC_RETRY_MS = 60000; +export function findHouseOfRcAutoSends(state, now = Date.now()) { + return (state?.events || []).filter((event) => { + const link = event.houseOfRc; + if (!link?.eventId || !link.autoSend) return false; + const signature = houseOfRcResultsSignature(event, state.sessions); + if (!signature) return false; + const last = link.lastSend || {}; + if (last.ok && last.signature === signature) return false; + if (!last.ok && last.at && now - Date.parse(last.at) < HOUSE_OF_RC_RETRY_MS) return false; + return true; + }); +} + +// Before sending: what might not be what you want. [{ key, params }] for houseofrc.warn_. +export function checkHouseOfRcResults(event, overview, { final = false, sessions = [], missing = [] } = {}) { + const warnings = []; + const ofEvent = sessions.filter((session) => session.eventId === event?.id); + const done = (session) => ["finished", "stopped"].includes(session.status); + if (ofEvent.some((session) => ["running", "paused"].includes(session.status))) warnings.push({ key: "running" }); + if (final) { + const finals = ofEvent.filter((session) => session.type === "final"); + const left = finals.filter((session) => !done(session)); + if (left.length) warnings.push({ key: "finals_left", params: { names: left.map((session) => session.name).join(", ") } }); + } + if (missing.length) warnings.push({ key: "missing", params: { count: missing.length } }); + const last = event?.houseOfRc?.lastSend; + if (last?.ok && last.signature === houseOfRcResultsSignature(event, sessions) && Boolean(last.final) === Boolean(final)) warnings.push({ key: "unchanged" }); + return warnings; +} diff --git a/src/houseofrc_view.js b/src/houseofrc_view.js index 3a857d7..53de4e1 100644 --- a/src/houseofrc_view.js +++ b/src/houseofrc_view.js @@ -1,4 +1,4 @@ -import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass, rememberHouseOfRcClass, diffHouseOfRcEntries, applyHouseOfRcEntryChanges, buildHouseOfRcResults } from "./houseofrc_logic.js"; +import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass, rememberHouseOfRcClass, diffHouseOfRcEntries, applyHouseOfRcEntryChanges, buildHouseOfRcResults, houseOfRcResultsSignature, checkHouseOfRcResults } from "./houseofrc_logic.js"; // Settings → System → House of RC: save the club's API key on the server and test it. // The key is never read back; the server only tells whether one is set (and its last 4 chars). @@ -360,9 +360,10 @@ export function openHouseOfRcResultsPost({ event, overview, state, t, escapeHtml let final = hasFinals && Boolean(overview?.finished); const render = () => { const { entries, rows, missing } = buildHouseOfRcResults(event, overview, { final, drivers: state.drivers }); + const warnings = checkHouseOfRcResults(event, overview, { final, sessions: state.sessions, missing }); const where = [event.houseOfRc.name, event.houseOfRc.className].filter(Boolean).join(" – "); body.innerHTML = ` -

${escapeHtml(where)}${event.houseOfRc.resultsSentAt ? ` · ${escapeHtml(t("houseofrc.results_last", { time: new Date(event.houseOfRc.resultsSentAt).toLocaleString() }))}` : ""}

+

${escapeHtml(where)} ${renderHouseOfRcSendStatus(event, { t, escapeHtml })}

@@ -377,6 +378,7 @@ export function openHouseOfRcResultsPost({ event, overview, state, t, escapeHtml ${row.heats}${escapeHtml(row.bestLap || "–")} `).join("")}
${missing.length ? `

⚠️ ${escapeHtml(t("houseofrc.results_missing", { names: missing.join(", ") }))}

` : ""} + ${warnings.length ? `` : ""}

@@ -388,16 +390,14 @@ export function openHouseOfRcResultsPost({ event, overview, state, t, escapeHtml const statusLine = body.querySelector("[data-hor-result-status]"); button.disabled = true; statusLine.textContent = t("houseofrc.results_sending"); - const { status: code, body: data } = await postJson("/api/houseofrc/results", { eventId: event.houseOfRc.eventId, entries }); + const { code, data } = await sendHouseOfRcResults({ event, overview, state, final }); + saveState(); if (code !== 200 || !data.ok) { statusLine.className = "error"; statusLine.textContent = describeHouseOfRcError(t, code, data); button.disabled = false; return; } - event.houseOfRc.resultsSentAt = new Date().toISOString(); - event.houseOfRc.resultsSentFinal = final; - saveState(); statusLine.className = ""; statusLine.textContent = `✅ ${t("houseofrc.results_sent", { count: data.updated })}`; }); @@ -405,3 +405,26 @@ export function openHouseOfRcResultsPost({ event, overview, state, t, escapeHtml render(); return { close }; } + +// One write of the race's results; remembers how it went on the race (event.houseOfRc.lastSend) +// for the status shown in Manage and Race Day, and for the automatic sending after each heat. +// The caller saves the state. +export async function sendHouseOfRcResults({ event, overview, state, final = false }) { + const { entries } = buildHouseOfRcResults(event, overview, { final, drivers: state.drivers }); + const signature = houseOfRcResultsSignature(event, state.sessions); + if (!entries.length) return { code: 400, data: { error: "invalid_entries" } }; + const { status: code, body: data } = await postJson("/api/houseofrc/results", { eventId: event.houseOfRc.eventId, entries }); + const ok = code === 200 && Boolean(data.ok); + event.houseOfRc.lastSend = { at: new Date().toISOString(), final, ok, signature, count: ok ? Number(data.updated) || 0 : 0, error: ok ? "" : String(data.error || code) }; + return { code, data }; +} + +// "🏠 Sent 21:19 · heats", "⚠️ Waiting to send – trying again" or nothing. +export function renderHouseOfRcSendStatus(event, { t, escapeHtml }) { + const last = event?.houseOfRc?.lastSend; + if (!last?.at) return event?.houseOfRc?.autoSend ? `🏠 ${escapeHtml(t("houseofrc.status_auto_waiting"))}` : ""; + const time = new Date(last.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + return last.ok + ? `🏠 ${escapeHtml(t(last.final ? "houseofrc.status_sent_final" : "houseofrc.status_sent_heats", { time }))}` + : `⚠️ ${escapeHtml(t(event.houseOfRc.autoSend ? "houseofrc.status_failed_retry" : "houseofrc.status_failed", { time }))}`; +} diff --git a/src/race_day_view.js b/src/race_day_view.js index aad414c..51cf01c 100644 --- a/src/race_day_view.js +++ b/src/race_day_view.js @@ -267,6 +267,7 @@ export function renderRaceDayView(deps) { renderRaceOverview = () => "", bindRaceOverview = () => {}, renderSpeakerPanel = () => "", bindSpeakerPanel = () => {}, shouldOfferFinals = () => false, createFinalsForEvent = () => null, + renderHouseOfRcStatus = () => "", } = deps; const queue = buildRaceDayQueue(state); const session = queue.current; @@ -317,7 +318,7 @@ export function renderRaceDayView(deps) {
${t("race_day.current")}

${session ? escapeHtml(session.name) : t("race_day.no_session")}

-

${session ? `${escapeHtml(getEventName(session.eventId))} · ${escapeHtml(getSessionTypeLabel(session.type))} · ${escapeHtml(getStartModeLabel(session.startMode))}` : t("race_day.no_session_hint")}

+

${session ? `${escapeHtml(getEventName(session.eventId))} · ${escapeHtml(getSessionTypeLabel(session.type))} · ${escapeHtml(getStartModeLabel(session.startMode))} ${renderHouseOfRcStatus(session.eventId)}` : t("race_day.no_session_hint")}

${renderTrackLayoutBar({ state, t, escapeHtml, showNewButton: false })}
${prologue diff --git a/src/styles.css b/src/styles.css index 3bac075..b190ace 100644 --- a/src/styles.css +++ b/src/styles.css @@ -4947,6 +4947,8 @@ tr:has(> td > .medal-3) { background: linear-gradient(90deg, rgba(205, 127, 60, .hor-import-table { width: 100%; } .hor-import-table th { text-align: left; } .hor-import-table td { vertical-align: middle; } +.hor-warnings { margin: 8px 0; padding-left: 18px; color: var(--warn, #f5b942); } +.hor-auto-send { display: inline-flex; align-items: center; gap: 6px; } .hor-modes { display: flex; flex-wrap: wrap; gap: 8px 20px; margin: 8px 0; } .hor-modes .hor-choice { flex-direction: row; white-space: nowrap; } .hor-modes .hor-choice input { width: auto; min-height: 0; margin: 0; } diff --git a/tests/browser_houseofrc.js b/tests/browser_houseofrc.js index 7414465..80ae6c2 100644 --- a/tests/browser_houseofrc.js +++ b/tests/browser_houseofrc.js @@ -70,7 +70,7 @@ export async function runHouseOfRcSmoke({ evaluate, navigate, savedState, waitFo export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, waitFor, base }) { try { await navigate("race_setup", "raceWizardStepForm"); - await evaluate(`(() => { + const installMock = `(() => { const realFetch = window.fetch; window.fetch = async (url, options) => { const json = (data) => new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } }); @@ -89,7 +89,8 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w } return realFetch(url, options); }; - })()`); + })()`; + await evaluate(installMock); await evaluate(`document.getElementById("raceWizardHouseOfRc").click()`); await waitFor(async () => evaluate(`Boolean(document.querySelector("[data-hor-event]"))`), "the event list"); await evaluate(`document.querySelector('[data-hor-event="2251"]').click()`); @@ -154,9 +155,26 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w assert.equal(posted.eventId, 2251); assert.deepEqual(posted.entries.map((entry) => entry.id).sort(), [11, 16]); assert.ok(posted.entries.every((entry) => !("ranking" in entry)), "no placing sent before the finals"); - await waitFor(async () => Boolean((await savedState()).events.find((item) => item.houseOfRc?.eventId === 2251)?.houseOfRc.resultsSentAt), "when it was sent is saved"); + await waitFor(async () => Boolean((await savedState()).events.find((item) => item.houseOfRc?.eventId === 2251)?.houseOfRc.lastSend?.ok), "how it was sent is saved"); await evaluate(`document.getElementById("houseOfRcResultsOverlay")?.remove()`); console.log("PASS House of RC results: preview in Manage, heats sent to the race's entries without placings"); + + // "Send heats automatically": a qualifying heat finishes, the race controller sends it. + await evaluate(`document.getElementById("houseOfRcAutoSend").click()`); + await waitFor(async () => (await savedState()).events.find((item) => item.houseOfRc?.eventId === 2251)?.houseOfRc.autoSend === true, "auto-send saved"); + { + const saved = await savedState(); + const race = saved.events.find((item) => item.houseOfRc?.eventId === 2251); + const heat = saved.sessions.find((session) => session.eventId === race.id && session.type === "qualification"); + Object.assign(heat, { status: "finished", startedAt: Date.now() - 400000, endedAt: Date.now() - 100000 }); + await fetch(base + "/api/state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(saved) }); + } + await navigate("race_day", "raceDaySessionSelect"); + await evaluate(installMock); + await waitFor(async () => evaluate(`Boolean(window.__horPosted)`), "sent by itself after the heat", 30000); + assert.ok((await evaluate(`window.__horPosted.entries`)).every((entry) => !("ranking" in entry)), "automatic sending never sends placings"); + await waitFor(async () => (await savedState()).events.find((item) => item.houseOfRc?.eventId === 2251)?.houseOfRc.lastSend?.signature, "the send is remembered"); + console.log("PASS House of RC auto-send: a finished heat is sent by the race controller without placings"); } finally { await evaluate(`document.getElementById("houseOfRcEventOverlay")?.remove()`).catch(() => {}); const current = await savedState(); diff --git a/tests/houseofrc_logic.test.js b/tests/houseofrc_logic.test.js index c68d714..a59d7c5 100644 --- a/tests/houseofrc_logic.test.js +++ b/tests/houseofrc_logic.test.js @@ -146,3 +146,31 @@ test("House of RC results: heats and qualifying without placings, then final pla const noQual = buildHouseOfRcResults(event, { phases: [] }, { drivers }); assert.ok(!("qualification" in noQual.entries[0]), "before any qualifying, House of RC's value is left alone"); }); + +test("House of RC auto-send: due after a finished heat, once per change, retried a minute after a failure", async () => { + const { findHouseOfRcAutoSends, houseOfRcResultsSignature, checkHouseOfRcResults, HOUSE_OF_RC_RETRY_MS } = await import("../src/houseofrc_logic.js"); + const event = { id: "e", houseOfRc: { eventId: 9, autoSend: true } }; + const sessions = [ + { id: "p", eventId: "e", type: "practice", status: "finished", endedAt: 1 }, + { id: "q1", eventId: "e", type: "qualification", status: "ready" }, + { id: "f1", eventId: "e", type: "final", status: "ready", name: "A final 1" }, + ]; + const state = { events: [event, { id: "off", houseOfRc: { eventId: 8 } }], sessions }; + assert.deepEqual(findHouseOfRcAutoSends(state), [], "practice alone is not sent"); + sessions[1].status = "finished"; sessions[1].endedAt = 100; + assert.deepEqual(findHouseOfRcAutoSends(state).map((item) => item.id), ["e"]); + const now = Date.parse("2026-11-08T20:00:00Z"); + event.houseOfRc.lastSend = { ok: false, at: new Date(now - 10000).toISOString(), signature: "" }; + assert.deepEqual(findHouseOfRcAutoSends(state, now), [], "failed 10 s ago: wait"); + assert.deepEqual(findHouseOfRcAutoSends(state, now + HOUSE_OF_RC_RETRY_MS).map((item) => item.id), ["e"], "then try again"); + event.houseOfRc.lastSend = { ok: true, at: new Date(now).toISOString(), signature: houseOfRcResultsSignature(event, sessions), final: false }; + assert.deepEqual(findHouseOfRcAutoSends(state, now), [], "sent: nothing new"); + assert.deepEqual(checkHouseOfRcResults(event, null, { final: false, sessions }).map((item) => item.key), ["unchanged"]); + const finalWarnings = checkHouseOfRcResults(event, null, { final: true, sessions, missing: ["Walk In"] }); + assert.deepEqual(finalWarnings.map((item) => item.key), ["finals_left", "missing"]); + assert.equal(finalWarnings[0].params.names, "A final 1"); + sessions[2].status = "running"; + assert.equal(checkHouseOfRcResults(event, null, { sessions })[0].key, "running"); + sessions[2].status = "finished"; sessions[2].endedAt = 200; + assert.deepEqual(findHouseOfRcAutoSends(state, now).map((item) => item.id), ["e"], "a new heat finished: due again"); +});