feat(houseofrc): preview and send results to the event's entries, heats or final placings (1.83.0)
This commit is contained in:
1 parent
f4a62b92d2
commit
ebdc6104e6
17 files changed
+295
-15
No files matched your search
@@ -8,6 +8,11 @@ The application version is maintained in `package.json` and displayed in the adm
|
||||
|
||||
No changes recorded yet.
|
||||
|
||||
## 1.83.0
|
||||
|
||||
- **Results to House of RC:** a race made from House of RC has **📤 Send results to House of RC** under Manage → Participants. It previews what each entry gets – qualifying placing (TQ), placing and main, every heat with laps, time and best lap – and sends it in one go; if House of RC refuses anything, nothing is written and the reason is shown.
|
||||
- Two modes: **Heats and qualifying** can be sent after every heat (no final placing, so House of RC doesn't notify the drivers yet), and **Final results** adds the placings once the finals are run. Sending again updates the same entries. Drivers added by hand, without a House of RC entry, are listed as not sent.
|
||||
|
||||
## 1.82.0
|
||||
|
||||
- **Late entries and withdrawals:** a race made from House of RC has **🔄 Fetch changes from House of RC** under Manage → Participants. It lists new entries of the race's class (➕, ticked) and participants whose entry is withdrawn or on the waiting list (➖, ticked); **Update participants** applies them the same way as ticking participants by hand, so only heats that haven't run change. Drivers added by hand are never touched.
|
||||
|
||||
@@ -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. Posting results back is being built together with House of RC (see ROADMAP.md).
|
||||
- **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.
|
||||
- **`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.
|
||||
|
||||
+1
-1
@@ -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. Att skicka tillbaka resultat byggs tillsammans med House of RC (se ROADMAP.md).
|
||||
- **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.
|
||||
- **`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.
|
||||
|
||||
+2
-2
@@ -1010,8 +1010,8 @@ Status 2026-11-08 (1.78.0-1.80.0):
|
||||
- [x] 1.81.0: House of RC added a timing API (2026-11-08). The club's organization key (from `/v1/me`, e.g. Jämtlands MK = 233) lists its events (`/v1/events?parent_id=`), and `GET /v1/timing/events/{id}/entries` gives the classes, entries (status, driver number, transponders, club, car) and drivers. The old `/results` is gone. Contact details are dropped on the server.
|
||||
|
||||
Next:
|
||||
- [ ] **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):** post after every heat, with that heat's results in `data`; House of RC would add a view showing only the latest heat.
|
||||
- [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.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?
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "rc-racecore",
|
||||
"version": "1.82.0",
|
||||
"version": "1.83.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "rc-racecore",
|
||||
"version": "1.82.0",
|
||||
"version": "1.83.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^12.11.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "rc-racecore",
|
||||
"version": "1.82.0",
|
||||
"version": "1.83.0",
|
||||
"private": true,
|
||||
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
|
||||
"engines": {
|
||||
|
||||
@@ -496,6 +496,10 @@ app.post("/api/houseofrc/entries", async (req, res) => {
|
||||
const result = await houseOfRc.getEventEntries(req.body?.eventId);
|
||||
res.status(result.ok ? 200 : result.status === 400 ? 400 : 502).json(result);
|
||||
});
|
||||
app.post("/api/houseofrc/results", async (req, res) => {
|
||||
const result = await houseOfRc.postResults(req.body?.eventId, req.body?.entries);
|
||||
res.status(result.ok ? 200 : result.status === 400 ? 400 : 502).json(result);
|
||||
});
|
||||
|
||||
app.post("/api/state", (req, res) => {
|
||||
if (!req.body || typeof req.body !== "object") {
|
||||
|
||||
+30
-6
@@ -44,8 +44,9 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
|
||||
return status();
|
||||
}
|
||||
|
||||
// GET against the API with the club key. Returns { ok, status, data, error, retryAfter }.
|
||||
async function get(apiPath, query = {}) {
|
||||
// A call to the API with the club key (GET, or POST with a JSON body).
|
||||
// Returns { ok, status, data, error, retryAfter }; a refused write (422) keeps its answer in data.
|
||||
async function get(apiPath, query = {}, { method = "GET", body } = {}) {
|
||||
const key = getKey();
|
||||
if (!key) return { ok: false, status: 0, error: "not_configured" };
|
||||
const url = new URL(baseUrl + apiPath);
|
||||
@@ -54,14 +55,16 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
|
||||
});
|
||||
try {
|
||||
const response = await fetchImpl(url, {
|
||||
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${key}`, Accept: "application/json", ...(body ? { "Content-Type": "application/json" } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
const data = await response.json().catch(() => null);
|
||||
if (response.ok) return { ok: true, status: response.status, data };
|
||||
const error = response.status === 401 || response.status === 403 ? "unauthorized"
|
||||
: response.status === 429 ? "rate_limited" : "http_error";
|
||||
return { ok: false, status: response.status, error, retryAfter: Number(response.headers.get("retry-after")) || 0 };
|
||||
: response.status === 429 ? "rate_limited" : response.status === 422 ? "rejected" : "http_error";
|
||||
return { ok: false, status: response.status, error, ...(response.status === 422 ? { data } : {}), retryAfter: Number(response.headers.get("retry-after")) || 0 };
|
||||
} catch (error) {
|
||||
return { ok: false, status: 0, error: error?.name === "TimeoutError" ? "timeout" : "unreachable" };
|
||||
}
|
||||
@@ -166,7 +169,28 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
|
||||
return { ok: true, status: 200, event: pickEvent(data.event || { id }), classes, entries };
|
||||
}
|
||||
|
||||
return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries };
|
||||
// Results back to the event's entries (all or nothing, see the API docs). entries:
|
||||
// [{ id, ranking?, qualification?, tq?, points?, laps_time?, data? }]. Only the count and
|
||||
// each entry's id and ranking come back to the browser.
|
||||
const RESULT_FIELDS = ["ranking", "qualification", "tq", "points", "laps_time", "data"];
|
||||
async function postResults(eventId, entries) {
|
||||
const id = Number(eventId);
|
||||
if (!Number.isInteger(id) || id < 1) return { ok: false, status: 400, error: "invalid_event" };
|
||||
if (!Array.isArray(entries) || !entries.length || entries.length > 2000) return { ok: false, status: 400, error: "invalid_entries" };
|
||||
const body = { entries: entries.map((entry) => Object.fromEntries([["id", Number(entry?.id)], ...RESULT_FIELDS.filter((field) => entry && field in entry).map((field) => [field, entry[field]])])) };
|
||||
if (body.entries.some((entry) => !Number.isInteger(entry.id) || entry.id < 1)) return { ok: false, status: 400, error: "invalid_entries" };
|
||||
const result = await get(`/v1/timing/events/${id}/entries`, {}, { method: "POST", body });
|
||||
if (!result.ok) {
|
||||
if (result.status === 403) return { ...result, error: "not_your_event" };
|
||||
if (result.status === 404) return { ...result, error: "event_not_found" };
|
||||
if (result.status === 422) return { ok: false, status: 422, error: "rejected", message: String(result.data?.message || ""), errors: result.data?.errors || {} };
|
||||
return result;
|
||||
}
|
||||
const data = result.data?.data || {};
|
||||
return { ok: true, status: 200, updated: Number(data.updated) || 0, entries: (data.entries || []).map((entry) => ({ id: entry.id, ranking: entry.ranking ?? null })) };
|
||||
}
|
||||
|
||||
return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries, postResults };
|
||||
}
|
||||
|
||||
module.exports = { createHouseOfRc, DEFAULT_BASE_URL };
|
||||
+39
@@ -2213,6 +2213,25 @@ 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.results_button": "Skicka resultat till House of RC",
|
||||
"houseofrc.results_hint": "Förhandsgranska och skicka resultatet till {name}",
|
||||
"houseofrc.results_title": "Skicka resultat till House of RC",
|
||||
"houseofrc.results_mode_heats": "Heat och kval (efter varje heat)",
|
||||
"houseofrc.results_mode_final": "Slutresultat (med finalplacering)",
|
||||
"houseofrc.results_heats_hint": "Skickar varje heat och kvalplaceringen. Ingen slutplacering, så ingen förare får något meddelande ännu – kan skickas efter varje heat.",
|
||||
"houseofrc.results_final_hint": "Skickar också slutplaceringen och finalen. Förarna får meddelande från House of RC första gången de får en placering.",
|
||||
"houseofrc.results_col_driver": "Förare",
|
||||
"houseofrc.results_col_qual": "Kval",
|
||||
"houseofrc.results_col_final": "Placering",
|
||||
"houseofrc.results_col_heats": "Heat",
|
||||
"houseofrc.results_col_best": "Bästa varv",
|
||||
"houseofrc.results_missing": "Skickas inte (ingen anmälan på House of RC): {names}",
|
||||
"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})",
|
||||
"houseofrc.refresh_title": "Ändrade anmälningar",
|
||||
"houseofrc.refresh_nothing": "Inga ändringar – deltagarna stämmer med House of RC.",
|
||||
@@ -4433,6 +4452,25 @@ 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.results_button": "Send results to House of RC",
|
||||
"houseofrc.results_hint": "Preview and send the results to {name}",
|
||||
"houseofrc.results_title": "Send results to House of RC",
|
||||
"houseofrc.results_mode_heats": "Heats and qualifying (after every heat)",
|
||||
"houseofrc.results_mode_final": "Final results (with final placings)",
|
||||
"houseofrc.results_heats_hint": "Sends every heat and the qualifying placing. No final placing, so no driver is notified yet – can be sent after every heat.",
|
||||
"houseofrc.results_final_hint": "Also sends the final placings and mains. Drivers are notified by House of RC the first time they get a placing.",
|
||||
"houseofrc.results_col_driver": "Driver",
|
||||
"houseofrc.results_col_qual": "Qual.",
|
||||
"houseofrc.results_col_final": "Placing",
|
||||
"houseofrc.results_col_heats": "Heats",
|
||||
"houseofrc.results_col_best": "Best lap",
|
||||
"houseofrc.results_missing": "Not sent (no House of RC entry): {names}",
|
||||
"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})",
|
||||
"houseofrc.refresh_title": "Changed entries",
|
||||
"houseofrc.refresh_nothing": "No changes – the participants match House of RC.",
|
||||
@@ -7482,6 +7520,7 @@ function renderEventManager(eventId) {
|
||||
escapeHtml,
|
||||
normalizeEvent,
|
||||
normalizeDriver,
|
||||
getRaceOverview,
|
||||
ensureRaceParticipantsConfigured,
|
||||
getSessionsForEvent,
|
||||
buildEventSchedule,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { openHouseOfRcEntryRefresh } from "./houseofrc_view.js";
|
||||
import { openHouseOfRcEntryRefresh, openHouseOfRcResultsPost } from "./houseofrc_view.js";
|
||||
import { mountSponsorSetup } from "./sponsor_event_view.js";
|
||||
import { mountTeamRaceSetup } from "./team_race_setup_view.js";
|
||||
import { orderSessionsForRunning, moveSessionInRunningOrder, applyFormatToPendingSessions, syncParticipantsToSessions } from "./event_race_logic.js";
|
||||
@@ -24,6 +24,7 @@ export function renderEventManagerView(context) {
|
||||
escapeHtml,
|
||||
normalizeEvent,
|
||||
normalizeDriver,
|
||||
getRaceOverview,
|
||||
ensureRaceParticipantsConfigured,
|
||||
getSessionsForEvent,
|
||||
getSelectedTeamEditId,
|
||||
@@ -613,6 +614,11 @@ export function renderEventManagerView(context) {
|
||||
},
|
||||
}));
|
||||
|
||||
// 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,
|
||||
}));
|
||||
|
||||
document.getElementById("selectAllParticipants")?.addEventListener("click", () => {
|
||||
document.querySelectorAll(".race-participant").forEach((node) => {
|
||||
node.checked = true;
|
||||
|
||||
@@ -189,6 +189,7 @@ export function renderEventManagerMarkup(context) {
|
||||
<button id="selectAllParticipants" class="btn" type="button">${t("events.select_all_participants")}</button>
|
||||
<button id="clearParticipants" class="btn btn-danger" type="button">${t("events.clear_participants")}</button>
|
||||
${event.houseOfRc?.eventId ? `<button id="houseOfRcRefreshEntries" class="btn" type="button" title="${escapeHtml(t("houseofrc.refresh_hint", { name: event.houseOfRc.name || "" }))}">🔄 ${t("houseofrc.refresh_button")}</button>` : ""}
|
||||
${event.houseOfRc?.eventId ? `<button id="houseOfRcSendResults" class="btn" type="button" title="${escapeHtml(t("houseofrc.results_hint", { name: event.houseOfRc.name || "" }))}">📤 ${t("houseofrc.results_button")}</button>` : ""}
|
||||
</div>
|
||||
${(() => {
|
||||
const card = (driver) => {
|
||||
|
||||
@@ -168,3 +168,65 @@ export function applyHouseOfRcEntryChanges(event, drivers, diff, { addIndexes, r
|
||||
const before = event.raceConfig.driverIds || [];
|
||||
return [...before.filter((id) => !removeIds.has(id)), ...addedIds.filter((id) => !before.includes(id))];
|
||||
}
|
||||
|
||||
// A lap or race time as House of RC writes it: "13.201", "1:02.345".
|
||||
export function formatHouseOfRcTime(ms) {
|
||||
const total = Math.round(Number(ms));
|
||||
if (!Number.isFinite(total) || total <= 0 || total >= Number.MAX_SAFE_INTEGER / 2) return "";
|
||||
const minutes = Math.floor(total / 60000);
|
||||
const seconds = ((total % 60000) / 1000).toFixed(3);
|
||||
return minutes ? `${minutes}:${seconds.padStart(6, "0")}` : seconds;
|
||||
}
|
||||
|
||||
// Our results for House of RC's entries (POST /v1/timing/events/{id}/entries), from the race
|
||||
// overview (buildRaceOverview). Only participants linked to an entry are sent.
|
||||
// final: false - heats and qualifying only (semi-live; nobody is told yet)
|
||||
// final: true - also the final placings (`ranking`, which notifies the driver the first time)
|
||||
// Returns { entries, rows (for the preview), missing (participants without an entry) }.
|
||||
export function buildHouseOfRcResults(event, overview, { final = false, drivers = [] } = {}) {
|
||||
const entryIds = event?.houseOfRc?.entryIds || {};
|
||||
const participants = event?.raceConfig?.driverIds || [];
|
||||
const phase = (type) => overview?.phases?.find((item) => item.type === type);
|
||||
const qualifying = phase("qualification");
|
||||
const finals = phase("final");
|
||||
const qualRank = new Map((qualifying?.standings || []).map((row) => [row.driverId, Number(row.rank) || null]));
|
||||
// A driver bumped up from a lower main is in both: placed by the higher one (listed first).
|
||||
const finalRows = (finals?.standings || []).filter((row, index, all) => all.findIndex((other) => other.driverId === row.driverId) === index);
|
||||
const heatsOf = (driverId) => ["qualification", "final"].flatMap((type) => (phase(type)?.heats || []).flatMap(({ session, rows }) => {
|
||||
const row = rows.find((item) => item.driverId === driverId);
|
||||
if (!row) return [];
|
||||
const time = formatHouseOfRcTime(row.timeMs);
|
||||
return [{ heat: session.name || "", laps: row.laps, time: row.raceStatus ? row.raceStatus.toUpperCase() : time, best_lap: formatHouseOfRcTime(row.bestLapMs), position: row.pos, _type: type, _laps_time: time ? `${row.laps}/${time}` : "" }];
|
||||
}));
|
||||
const nameOf = (driverId) => drivers.find((driver) => driver.id === driverId)?.name || driverId;
|
||||
const missing = participants.filter((driverId) => entryIds[driverId] == null).map(nameOf);
|
||||
const rows = [];
|
||||
const entries = participants.filter((driverId) => entryIds[driverId] != null).map((driverId) => {
|
||||
const heats = heatsOf(driverId);
|
||||
const bestLap = heats.map((heat) => heat.best_lap).filter(Boolean).sort((a, b) => toMs(a) - toMs(b))[0] || "";
|
||||
const qualification = qualRank.get(driverId) || null;
|
||||
const result = { best_lap: bestLap, heats: heats.map(({ _type, _laps_time, ...heat }) => heat) };
|
||||
// No qualifying run yet: leave House of RC's qualification as it is.
|
||||
const entry = { id: entryIds[driverId], ...(qualRank.size ? { qualification, tq: qualification === 1 } : {}) };
|
||||
const finalIndex = finalRows.findIndex((row) => row.driverId === driverId);
|
||||
if (final && finalIndex >= 0) {
|
||||
const row = finalRows[finalIndex];
|
||||
const lastFinal = heats.filter((heat) => heat._type === "final").pop();
|
||||
entry.ranking = finalIndex + 1;
|
||||
entry.laps_time = lastFinal?._laps_time || "";
|
||||
result.main = row.mainKey || String(row.rank).replace(/\d+$/, "");
|
||||
const lower = (finals?.standings || []).filter((other) => other.driverId === driverId && other !== row).map((other) => other.mainKey || String(other.rank).replace(/\d+$/, ""));
|
||||
if (lower.length) result.bumped_from = lower;
|
||||
result.main_position = Number(String(row.rank).replace(/^\D+/, "")) || null;
|
||||
}
|
||||
entry.data = { result };
|
||||
rows.push({ driverId, name: nameOf(driverId), entryId: entryIds[driverId], qualification, ranking: entry.ranking ?? null, main: result.main || "", heats: heats.length, bestLap, lapsTime: entry.laps_time || "" });
|
||||
return entry;
|
||||
});
|
||||
return { entries, rows: rows.sort((a, b) => (a.ranking ?? 1e9) - (b.ranking ?? 1e9) || (a.qualification ?? 1e9) - (b.qualification ?? 1e9)), missing };
|
||||
}
|
||||
|
||||
const toMs = (text) => {
|
||||
const [minutes, seconds] = String(text).includes(":") ? String(text).split(":") : ["0", text];
|
||||
return Number(minutes) * 60000 + Number(seconds) * 1000;
|
||||
};
|
||||
+60
-1
@@ -1,4 +1,4 @@
|
||||
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass, rememberHouseOfRcClass, diffHouseOfRcEntries, applyHouseOfRcEntryChanges } from "./houseofrc_logic.js";
|
||||
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass, rememberHouseOfRcClass, diffHouseOfRcEntries, applyHouseOfRcEntryChanges, buildHouseOfRcResults } 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).
|
||||
@@ -20,7 +20,11 @@ export function describeHouseOfRcError(t, code, body = {}) {
|
||||
timeout: "houseofrc.err_unreachable",
|
||||
unreachable: "houseofrc.err_unreachable",
|
||||
invalid_key: "houseofrc.err_invalid_key",
|
||||
not_your_event: "houseofrc.err_not_your_event",
|
||||
event_not_found: "houseofrc.err_event_not_found",
|
||||
invalid_event: "houseofrc.err_event_not_found",
|
||||
}[body.error];
|
||||
if (body.error === "rejected") return t("houseofrc.err_rejected", { message: [body.message, ...Object.values(body.errors || {}).flat()].filter(Boolean).join(" ") || "422" });
|
||||
return key ? t(key, { seconds: body.retryAfter || 60 }) : t("houseofrc.err_other", { status: body.status || code });
|
||||
}
|
||||
|
||||
@@ -346,3 +350,58 @@ export async function openHouseOfRcEntryRefresh({ event, state, t, escapeHtml, m
|
||||
onApply(selectedIds);
|
||||
});
|
||||
}
|
||||
|
||||
// Manage → "Send results to House of RC": a preview of what goes to each entry, then one
|
||||
// all-or-nothing write. "Heats" leaves out the final placings, so nobody is notified yet
|
||||
// and it can be sent after every heat; "Final results" adds them.
|
||||
export function openHouseOfRcResultsPost({ event, overview, state, t, escapeHtml, saveState }) {
|
||||
const { body, close } = openHorModal({ id: "houseOfRcResultsOverlay", title: t("houseofrc.results_title"), escapeHtml });
|
||||
const hasFinals = Boolean(overview?.phases?.find((phase) => phase.type === "final")?.standings?.length);
|
||||
let final = hasFinals && Boolean(overview?.finished);
|
||||
const render = () => {
|
||||
const { entries, rows, missing } = buildHouseOfRcResults(event, overview, { final, drivers: state.drivers });
|
||||
const where = [event.houseOfRc.name, event.houseOfRc.className].filter(Boolean).join(" – ");
|
||||
body.innerHTML = `
|
||||
<p><strong>${escapeHtml(where)}</strong>${event.houseOfRc.resultsSentAt ? ` <span class="hint">· ${escapeHtml(t("houseofrc.results_last", { time: new Date(event.houseOfRc.resultsSentAt).toLocaleString() }))}</span>` : ""}</p>
|
||||
<div class="hor-choice">
|
||||
<label><input type="radio" name="horResultsMode" value="heats" ${final ? "" : "checked"} /> ${escapeHtml(t("houseofrc.results_mode_heats"))}</label>
|
||||
<label><input type="radio" name="horResultsMode" value="final" ${final ? "checked" : ""} ${hasFinals ? "" : "disabled"} /> ${escapeHtml(t("houseofrc.results_mode_final"))}</label>
|
||||
</div>
|
||||
<p class="hint">${escapeHtml(t(final ? "houseofrc.results_final_hint" : "houseofrc.results_heats_hint"))}</p>
|
||||
<div class="table-wrap"><table class="hor-import-table">
|
||||
<thead><tr><th>${escapeHtml(t("houseofrc.results_col_driver"))}</th><th>${escapeHtml(t("houseofrc.results_col_qual"))}</th><th>${escapeHtml(t("houseofrc.results_col_final"))}</th><th>${escapeHtml(t("houseofrc.results_col_heats"))}</th><th>${escapeHtml(t("houseofrc.results_col_best"))}</th></tr></thead>
|
||||
<tbody>${rows.map((row) => `<tr data-hor-result-row>
|
||||
<td>${escapeHtml(row.name)}</td>
|
||||
<td>${row.qualification === 1 ? "TQ" : escapeHtml(String(row.qualification ?? "–"))}</td>
|
||||
<td>${row.ranking ? escapeHtml(`${row.ranking} (${row.main})`) : "–"}${row.lapsTime ? ` <span class="hint">${escapeHtml(row.lapsTime)}</span>` : ""}</td>
|
||||
<td>${row.heats}</td><td>${escapeHtml(row.bestLap || "–")}</td>
|
||||
</tr>`).join("")}</tbody></table></div>
|
||||
${missing.length ? `<p class="hint">⚠️ ${escapeHtml(t("houseofrc.results_missing", { names: missing.join(", ") }))}</p>` : ""}
|
||||
<p data-hor-result-status></p>
|
||||
<div class="actions mt-16">
|
||||
<button class="btn btn-primary" type="button" data-hor-send ${entries.length ? "" : "disabled"}>📤 ${escapeHtml(t("houseofrc.results_send", { count: entries.length }))}</button>
|
||||
<button class="btn" type="button" data-hor-close>${escapeHtml(t("houseofrc.results_close"))}</button>
|
||||
</div>`;
|
||||
body.querySelectorAll("[name=horResultsMode]").forEach((radio) => radio.addEventListener("change", () => { final = radio.value === "final"; render(); }));
|
||||
body.querySelector("[data-hor-send]").addEventListener("click", async (click) => {
|
||||
const button = click.currentTarget;
|
||||
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 });
|
||||
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 })}`;
|
||||
});
|
||||
};
|
||||
render();
|
||||
return { close };
|
||||
}
|
||||
@@ -44,6 +44,8 @@ export function buildRaceOverview(event, deps) {
|
||||
laps: Number(row.laps || 0),
|
||||
result: row.resultDisplay || "-",
|
||||
bestLapMs: Number(row.bestLapMs || 0) || null,
|
||||
timeMs: Number(row.totalElapsedMs || 0) || null,
|
||||
raceStatus: row.raceStatus || "",
|
||||
})),
|
||||
}));
|
||||
const planned = sessions.filter((session) => session.type === type).length;
|
||||
|
||||
@@ -83,6 +83,10 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w
|
||||
{ entryId: 13, classId: 555, houseOfRcId: 903, name: "HoR Skipped", number: null, transponders: [], club: "", car: "" },
|
||||
{ entryId: 14, classId: 556, houseOfRcId: 904, name: "HoR Other Class", number: null, transponders: [], club: "", car: "" },
|
||||
] });
|
||||
if (String(url).includes("/api/houseofrc/results")) {
|
||||
window.__horPosted = JSON.parse(options.body);
|
||||
return json({ ok: true, updated: window.__horPosted.entries.length, entries: [] });
|
||||
}
|
||||
return realFetch(url, options);
|
||||
};
|
||||
})()`);
|
||||
@@ -137,6 +141,22 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w
|
||||
assert.equal(Object.keys(race.houseOfRc.entryIds).length, 2);
|
||||
}
|
||||
console.log("PASS House of RC re-fetch in Manage: late entries added, withdrawn drivers taken out");
|
||||
|
||||
// Manage → "Send results to House of RC": nothing raced yet, so heats mode, no placings.
|
||||
await waitFor(async () => evaluate(`Boolean(document.getElementById("houseOfRcSendResults"))`), "the send results button in Manage");
|
||||
await evaluate(`document.getElementById("houseOfRcSendResults").click()`);
|
||||
await waitFor(async () => evaluate(`Boolean(document.querySelector("#houseOfRcResultsOverlay [data-hor-send]"))`), "the results preview");
|
||||
assert.equal(await evaluate(`document.querySelectorAll("#houseOfRcResultsOverlay [data-hor-result-row]").length`), 2);
|
||||
assert.equal(await evaluate(`document.querySelector('[name=horResultsMode][value=final]').disabled`), true, "no finals yet: final results cannot be picked");
|
||||
await evaluate(`document.querySelector("#houseOfRcResultsOverlay [data-hor-send]").click()`);
|
||||
await waitFor(async () => evaluate(`Boolean(window.__horPosted)`), "the results are posted");
|
||||
const posted = await evaluate(`window.__horPosted`);
|
||||
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 evaluate(`document.getElementById("houseOfRcResultsOverlay")?.remove()`);
|
||||
console.log("PASS House of RC results: preview in Manage, heats sent to the race's entries without placings");
|
||||
} finally {
|
||||
await evaluate(`document.getElementById("houseOfRcEventOverlay")?.remove()`).catch(() => {});
|
||||
const current = await savedState();
|
||||
|
||||
@@ -105,3 +105,37 @@ test("House of RC re-fetch: late entries are added, withdrawn ones offered for r
|
||||
assert.equal(drivers.find((driver) => driver.id === "late").transponder, "9");
|
||||
assert.deepEqual(diffHouseOfRcEntries({ ...event, raceConfig: { driverIds: ids } }, entries, drivers), { added: [], withdrawn: [] }, "fetching again finds nothing new");
|
||||
});
|
||||
|
||||
test("House of RC results: heats and qualifying without placings, then final placings by main", async () => {
|
||||
const { buildHouseOfRcResults, formatHouseOfRcTime } = await import("../src/houseofrc_logic.js");
|
||||
assert.deepEqual([formatHouseOfRcTime(13201), formatHouseOfRcTime(303412), formatHouseOfRcTime(0)], ["13.201", "5:03.412", ""]);
|
||||
const event = { raceConfig: { driverIds: ["a", "b", "h"] }, houseOfRc: { eventId: 1, entryIds: { a: 11, b: 12, gone: 13 } } };
|
||||
const drivers = [{ id: "a", name: "Anna" }, { id: "b", name: "Bo" }, { id: "h", name: "Hand Added" }];
|
||||
const heat = (name, rows) => ({ session: { name }, rows });
|
||||
const overview = { phases: [
|
||||
{ type: "qualification", standings: [{ driverId: "b", rank: 1 }, { driverId: "a", rank: 2 }], heats: [
|
||||
heat("Kval 1", [{ pos: 1, driverId: "b", laps: 12, timeMs: 300500, bestLapMs: 13201 }, { pos: 2, driverId: "a", laps: 11, timeMs: 301000, bestLapMs: 14002 }]),
|
||||
] },
|
||||
{ type: "final", standings: [{ driverId: "a", rank: "A1" }, { driverId: "b", rank: "A2" }], heats: [
|
||||
heat("A-final", [{ pos: 1, driverId: "a", laps: 22, timeMs: 303412, bestLapMs: 12950 }, { pos: 2, driverId: "b", laps: 21, timeMs: 0, bestLapMs: 13100, raceStatus: "dnf" }]),
|
||||
] },
|
||||
] };
|
||||
const live = buildHouseOfRcResults(event, overview, { drivers });
|
||||
assert.deepEqual(live.missing, ["Hand Added"], "a hand-added driver has no entry to write to");
|
||||
assert.deepEqual(live.entries.map((entry) => entry.id), [11, 12], "only participants; a removed driver's entry is not sent");
|
||||
assert.ok(live.entries.every((entry) => !("ranking" in entry)), "no placing yet, so nobody is notified");
|
||||
const bo = live.entries[1];
|
||||
assert.equal(bo.qualification, 1);
|
||||
assert.equal(bo.tq, true);
|
||||
assert.deepEqual(bo.data.result.heats[1], { heat: "A-final", laps: 21, time: "DNF", best_lap: "13.100", position: 2 });
|
||||
assert.equal(bo.data.result.best_lap, "13.100");
|
||||
const done = buildHouseOfRcResults(event, overview, { final: true, drivers });
|
||||
assert.deepEqual(done.entries.map((entry) => [entry.id, entry.ranking, entry.data.result.main, entry.data.result.main_position]), [[11, 1, "A", 1], [12, 2, "A", 2]]);
|
||||
assert.equal(done.entries[0].laps_time, "22/5:03.412");
|
||||
assert.deepEqual(done.rows.map((row) => row.name), ["Anna", "Bo"], "preview in final order");
|
||||
const bumped = { phases: [{ type: "final", standings: [{ driverId: "b", rank: "A1" }, { driverId: "a", rank: "A2" }, { driverId: "h", rank: "B1" }, { driverId: "b", rank: "B2" }], heats: [] }] };
|
||||
const withBump = buildHouseOfRcResults({ ...event, houseOfRc: { entryIds: { a: 11, b: 12, h: 13 } } }, bumped, { final: true, drivers });
|
||||
assert.deepEqual(withBump.entries.map((entry) => [entry.id, entry.ranking, entry.data.result.main, entry.data.result.bumped_from]), [[11, 2, "A", undefined], [12, 1, "A", ["B"]], [13, 3, "B", undefined]], "a bumped driver counts once, in the higher main");
|
||||
const noQual = buildHouseOfRcResults(event, { phases: [] }, { drivers });
|
||||
assert.ok(!("qualification" in noQual.entries[0]), "before any qualifying, House of RC's value is left alone");
|
||||
});
|
||||
@@ -733,6 +733,20 @@ test("House of RC: the key is stored server-side only, never returned, and the t
|
||||
const mock = createServer((req, res) => {
|
||||
seen.push({ url: req.url, auth: req.headers.authorization });
|
||||
const ok = req.headers.authorization === "Bearer hrc_test_secret_key_1234";
|
||||
if (ok && req.method === "POST" && req.url === "/v1/timing/events/2251/entries") {
|
||||
let raw = "";
|
||||
req.on("data", (chunk) => { raw += chunk; });
|
||||
req.on("end", () => {
|
||||
const body = JSON.parse(raw);
|
||||
seen.at(-1).body = body;
|
||||
const bad = body.entries.filter((entry) => entry.id !== 98765);
|
||||
res.writeHead(bad.length ? 422 : 200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(bad.length
|
||||
? { message: "The given data was invalid.", errors: { "entries.0.id": ["Not an entry of this event."] } }
|
||||
: { data: { updated: 1, entries: [{ id: 98765, ranking: body.entries[0].ranking ?? null, user_id: 68 }] } }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
const forbidden = ok && req.url === "/v1/timing/events/3001/entries";
|
||||
const missing = ok && req.url.startsWith("/v1/timing/events/") && !forbidden && req.url !== "/v1/timing/events/2251/entries";
|
||||
res.writeHead(!ok ? 401 : forbidden ? 403 : missing ? 404 : 200, { "Content-Type": "application/json" });
|
||||
@@ -810,6 +824,16 @@ test("House of RC: the key is stored server-side only, never returned, and the t
|
||||
assert.equal((await (await post("/api/houseofrc/entries", { eventId: "999" })).json()).error, "event_not_found");
|
||||
assert.equal((await (await post("/api/houseofrc/entries", { eventId: "3001" })).json()).error, "not_your_event");
|
||||
|
||||
const sent = await post("/api/houseofrc/results", { eventId: 2251, entries: [{ id: 98765, ranking: 1, qualification: 2, tq: false, laps_time: "22/5:03.412", data: { result: { main: "A", main_position: 1 } }, name: "dropped" }] });
|
||||
assert.equal(sent.status, 200);
|
||||
assert.deepEqual(await sent.json(), { ok: true, status: 200, updated: 1, entries: [{ id: 98765, ranking: 1 }] });
|
||||
assert.equal(seen.at(-1).auth, "Bearer hrc_test_secret_key_1234");
|
||||
assert.deepEqual(Object.keys(seen.at(-1).body.entries[0]), ["id", "ranking", "qualification", "tq", "laps_time", "data"], "only result fields go out");
|
||||
const refused = await (await post("/api/houseofrc/results", { eventId: 2251, entries: [{ id: 111, ranking: 1 }] })).json();
|
||||
assert.equal(refused.error, "rejected");
|
||||
assert.deepEqual(refused.errors, { "entries.0.id": ["Not an entry of this event."] });
|
||||
assert.equal((await post("/api/houseofrc/results", { eventId: 2251, entries: [] })).status, 400);
|
||||
|
||||
const keyFile = join(dataDir, "houseofrc.json");
|
||||
assert.equal(statSync(keyFile).mode & 0o777, 0o600, "only the server user can read the key file");
|
||||
for (const path of ["/api/houseofrc/status", "/api/state"]) {
|
||||
|
||||
Reference in new issue
Block a user