diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d6f1c..15c97b7 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.31 - 2026-11-14 + +### Added + +- **đ My race today** on the driver's mobile profile (the QR link): on a race day, the driver's next heats with time and grid place, marshal duties and results of today's heats, updated with the profile. The race controller computer posts today's schedule to the server (driver ids only); no new link or router path. + ## 1.89.30 - 2026-11-14 ### Added diff --git a/README.md b/README.md index 50e0e83..6c74fa0 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,7 @@ Rookie gets its own standings with the series' points table, count rule and club **Mobile profile:** - Each driver can get a personal link with a QR code. It shows their own statistics, a practice timer, setup markers and exercises (even laps, step training), and has a choice of practice or race laps. + - **đ My race today:** on a race day the profile shows, on top, the driver's next heats with their time (as on Race Day, breaks and delays included) and grid place in finals, marshal duties, and results of today's heats. The race controller computer sends today's schedule to the server every 15 s (driver ids only, no names), so no new link or router change is needed. No card on days without racing. - A **Standard / Pro** switch at the top. **Pro** is a clean practice view without goals or settings: today's laps, stints, driving time, best, average and personal best, then the stint cards that fold out to every lap. The choice is remembered on the phone and can be linked with `?mode=pro`. - The link uses a random token; no transponders or other drivers are shown. - For use over the internet, set the **public address** once for everyone under Settings â System & backup â Public address (domain / DynDNS), e.g. `https://club.dyndns.org:8443`. Left empty, links use the local network address. diff --git a/README.sv.md b/README.sv.md index 1e307aa..badf69e 100644 --- a/README.sv.md +++ b/README.sv.md @@ -269,6 +269,7 @@ Rookie fĂ„r en egen stĂ€llning med seriens poĂ€ngtabell, rĂ€kneregel och klubbre **Mobilprofil:** - Varje förare kan fĂ„ en personlig lĂ€nk med QR-kod. Den visar förarens egen statistik, en trĂ€ningstimer, setup-markeringar och övningar (jĂ€mna varv, stegtrĂ€ning), och har val för trĂ€nings- eller racevarv. + - **đ Mitt race idag:** en tĂ€vlingsdag visar profilen överst förarens kommande heat med tid (som i Race Day, med pauser och förseningar) och startplats i finaler, marshal-pass och resultat frĂ„n dagens körda heat. Race Controller-datorn skickar dagens schema till servern var 15:e sekund (bara förar-id, inga namn), sĂ„ det krĂ€ver ingen ny lĂ€nk eller Ă€ndring i routern. Dagar utan race syns inget kort. - Ett reglage **Standard / Pro** högst upp. **Pro** Ă€r en ren trĂ€ningsvy utan mĂ„l och instĂ€llningar: dagens varv, stintar, körtid, bĂ€sta, snitt och personbĂ€sta, sedan stintkorten som fĂ€lls ut till alla varv. Valet sparas i telefonen och kan lĂ€nkas med `?mode=pro`. - LĂ€nken anvĂ€nder en slumpad nyckel; inga transpondrar eller andra förare visas. - För anvĂ€ndning via internet, ange **den publika adressen** en gĂ„ng för alla under InstĂ€llningar â System & backup â Publik adress (domĂ€n / DynDNS), till exempel `https://klubben.dyndns.org:8443`. LĂ€mnas den tom anvĂ€nds den lokala nĂ€tverksadressen. diff --git a/docs/javascript-architecture.md b/docs/javascript-architecture.md index 6ab7a4d..6bd091b 100644 --- a/docs/javascript-architecture.md +++ b/docs/javascript-architecture.md @@ -2961,6 +2961,8 @@ Dependency graph: `app.js -> decoder_runtime.js -> decoder_diagnostics.js`; `app `decoder_diagnostics_view.js` mounts inside a details element outside settingsForm. A one-second timer patches only its own text nodes; it skips closed/paused panels, clears the old timer on remount, and self-clears after detachment. Pause affects display, not collection. Clearing diagnostics preserves socket state and timestamps. Copy uses Clipboard API with a selectable readonly textarea fallback for HTTP. Untrusted payloads are assigned through textContent/value, never interpolated into HTML. No SQLite/localStorage writes, backend endpoint, or public overlay exposure is added. Refresh resets diagnostics independently of saved settings. +`my_race_logic.js` (pure) builds the "My race today" snapshot from `buildDayRows(today)`: per session an id, label, planned start, state, grid flag, entrant ids in grid order, marshal ids and, for heats run, leaderboard positions (ids, laps, result text - no names). `app.js` `publishPublicRaceDay()` posts it every 15 s on the race master when it changed to `POST /api/public-race-day`; the server keeps it in `data/public_race_day.json` (never in app state) and `/public-training/api/:token` adds `raceToday` from `pickDriverRaceDay()` in `server/public_training_profile.js` (today only, the profile's own ids). `public_training.js` renders it with `renderMyRace()`. + `check_in_logic.js` (pure) holds the optional race check-in: `raceConfig.checkIn = { driverId: { present, paid } }` (kept by `normalizeEvent` and `buildRaceFormatConfigFromForm`), `checkInRows()` (with today's decoder sightings from `prologue_logic.js`), `checkInSummary()`, `canRemoveNoShows()` (someone checked in, no non-practice session of the race started) and `removeNoShows()` (race participants and unstarted sessions only, never the register). `check_in_view.js` renders the Manage race tab; `app.js` `mountCheckIn()` fills it through the `renderCheckIn` context hook. `decoder_watch.js` (pure) decides the decoder alarm: `decoderAlarm(decoder, session, { startPending, bestLapMs, now })` returns `ok`, `lost` (main link down 3 s or more during a running heat or start count-down, counted from `state.decoder.disconnectedAt`, set on the first `onclose` and cleared on `onopen`) or `silent` (connected, a non-practice heat past its first 30 s, no PASSING since `state.decoder.lastPassingAt` or the start for `silentLimitMs(bestLapMs)` = max(30 s, 3 Ă best lap)). `app.js` `checkDecoderAlarm()` runs every second on the race master with a configured `wsUrl` and `settings.raceAudio.decoderAlarm` on; it renders `#decoderAlarm`, plays `timing_disconnected` (or the WebAudio siren when race audio is off) every 30 s until silenced, and shows 10 s of "working again" after recovery. No backend or SQLite change. diff --git a/package-lock.json b/package-lock.json index 76c7a5d..963d5bf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.89.30", + "version": "1.89.31", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.89.30", + "version": "1.89.31", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index c82b267..2516e53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.89.30", + "version": "1.89.31", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/server.js b/server.js index a27fd0c..f5abab2 100644 --- a/server.js +++ b/server.js @@ -722,6 +722,19 @@ app.get(["/public-overlay", "/public-overlay/:mode"], (req, res) => { res.sendFile(path.join(__dirname, "index.html")); }); +// "My race today" (src/my_race_logic.js): the race master posts its day snapshot here; the public +// profile picks out the driver's own heats. Kept in a file of its own so it never races app state. +const PUBLIC_RACE_DAY_FILE = path.join(DB_DIR, "public_race_day.json"); +let publicRaceDaySnapshot = null; +try { publicRaceDaySnapshot = JSON.parse(fs.readFileSync(PUBLIC_RACE_DAY_FILE, "utf8")); } catch { publicRaceDaySnapshot = null; } +app.post("/api/public-race-day", (req, res) => { + const snapshot = publicTrainingProfile.sanitizePublicRaceDaySnapshot(req.body); + if (!snapshot) { res.status(400).json({ error: "invalid snapshot" }); return; } + publicRaceDaySnapshot = snapshot; + try { fs.writeFileSync(PUBLIC_RACE_DAY_FILE, JSON.stringify(snapshot)); } catch { /* memory copy still serves */ } + res.json({ ok: true }); +}); + app.get("/public-training/api/:shareToken", (req, res) => { try { const stored = readStoredAppState(); @@ -736,6 +749,7 @@ app.get("/public-training/api/:shareToken", (req, res) => { res.status(404).json({ error: "Profile not found" }); return; } + profile.raceToday = publicTrainingProfile.pickDriverRaceDay(publicRaceDaySnapshot, publicTrainingProfile.publicProfileDriverIds(stored.state, String(req.params.shareToken || ""))); res.setHeader("Cache-Control", "no-store"); res.json(profile); } catch (error) { diff --git a/server/public_training_profile.js b/server/public_training_profile.js index d6e78ba..0d39e8c 100644 --- a/server/public_training_profile.js +++ b/server/public_training_profile.js @@ -866,7 +866,61 @@ function getPublicTrainingRecommendation(stats) { return { level: "progression", targetLapMs: Math.round(stats.bestLapMs * 1.05) }; } +// "My race today": one driver's part of the race master's day snapshot (src/my_race_logic.js): +// upcoming heats with time and grid place, marshal duties, and results of heats already run. +// Only for today's date; the driver's other class entries (same profile) count too. +function publicProfileDriverIds(state, shareToken) { + const share = findPublicTrainingShare(state, shareToken); + if (!share) return []; + const profile = getPublicDriverProfile(Array.isArray(state?.drivers) ? state.drivers : [], String(share.driverId || "")); + return profile ? profile.drivers.map((driver) => String(driver.id || "")).filter(Boolean) : []; +} + +function localDateKey(ms) { + const d = new Date(ms); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +} + +function pickDriverRaceDay(snapshot, driverIds, now = Date.now()) { + const ids = new Set((driverIds || []).map(String)); + if (!snapshot || !ids.size || snapshot.date !== localDateKey(now)) return null; + const sessions = Array.isArray(snapshot.sessions) ? snapshot.sessions : []; + const heats = []; + const marshal = []; + const results = []; + sessions.forEach((session) => { + const entryIndex = (session.entries || []).findIndex((id) => ids.has(String(id))); + if (session.state !== "done" && entryIndex >= 0) heats.push({ label: String(session.label || ""), start: Number(session.start) || 0, live: session.state === "live", gridPosition: session.gridStart ? entryIndex + 1 : null }); + if (session.state !== "done" && (session.marshals || []).some((id) => ids.has(String(id)))) marshal.push({ label: String(session.label || ""), start: Number(session.start) || 0, live: session.state === "live" }); + const result = (session.results || []).find((item) => ids.has(String(item.driverId))); + if (session.state === "done" && result) results.push({ label: String(session.label || ""), position: Number(result.position) || 0, laps: Number(result.laps) || 0, result: String(result.result || "") }); + }); + if (!heats.length && !marshal.length && !results.length) return null; + return { heats, marshal, results }; +} + +// Keeps what the race master posts to sane sizes and types. +function sanitizePublicRaceDaySnapshot(input) { + const date = String(input?.date || ""); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null; + const ids = (list) => (Array.isArray(list) ? list : []).slice(0, 60).map((id) => String(id).slice(0, 80)); + const sessions = (Array.isArray(input?.sessions) ? input.sessions : []).slice(0, 200).map((session) => ({ + id: String(session?.id || "").slice(0, 80), + label: String(session?.label || "").slice(0, 120), + start: Math.max(0, Number(session?.start) || 0), + state: ["upcoming", "live", "done"].includes(session?.state) ? session.state : "upcoming", + gridStart: session?.gridStart === true, + entries: ids(session?.entries), + marshals: ids(session?.marshals), + results: (Array.isArray(session?.results) ? session.results : []).slice(0, 60).map((item) => ({ driverId: String(item?.driverId || "").slice(0, 80), position: Math.max(0, Number(item?.position) || 0), laps: Math.max(0, Number(item?.laps) || 0), result: String(item?.result || "").slice(0, 40) })), + })); + return { date, sessions }; +} + module.exports = { + publicProfileDriverIds, + pickDriverRaceDay, + sanitizePublicRaceDaySnapshot, normalizePublicTrainingLayout, buildPublicTrainingProfile, findPublicTrainingShare, diff --git a/src/app.js b/src/app.js index 879c15c..f087d32 100644 --- a/src/app.js +++ b/src/app.js @@ -25,6 +25,7 @@ import { decoderAlarm } from "./decoder_watch.js"; import { resultsAutosavePlan } from "./results_autosave.js"; import { normalizeCheckIn, checkInRows, checkInSummary, canRemoveNoShows, removeNoShows } from "./check_in_logic.js"; import { renderCheckInPanel, bindCheckInPanel, buildCheckInPrintHtml } from "./check_in_view.js"; +import { buildPublicRaceDaySnapshot } from "./my_race_logic.js"; import { RACE_AUDIO_EVENT_DEFINITIONS, createRaceAudioEngine, normalizeRaceAudioSettings, isSilencedDuringRace, formatSpokenLapTime, resolveDriverCallStyle, formatCarCall, formatHeatCallDrivers } from "./race_audio.js"; import { renderRaceFormatField, renderRaceFormatContextCard, getRaceSummaryItems, getRaceSummaryWarnings, renderManageStatusBadge, renderRaceWizardSteps, renderRaceWizardContent, renderRaceStandingsTable } from "./race_setup_ui.js"; @@ -7835,6 +7836,28 @@ function updateConnectionBadge() { dom.connectionBadge.className = `badge ${isOnline ? "badge-online" : "badge-offline"}`; } +// "My race today" (my_race_logic.js): every 15 s the race master posts today's schedule as a small +// snapshot (driver ids, no names) when it changed; drivers' mobile profiles read their part. +let lastPublicRaceDayJson = ""; +async function publishPublicRaceDay() { + if (overlayMode || !isRaceMaster()) return; + const date = todayKey(); + const rows = buildDayRows(date); + const snapshot = buildPublicRaceDaySnapshot({ + date, + rows, + getClassLabel: getDayClassLabel, + getEntries: (session) => getSessionGridEntries(session), + getResults: (session) => buildLeaderboard(session), + isGridStart: (session) => normalizeStartMode(session.startMode) === "position", + }); + const json = JSON.stringify(snapshot); + if (json === lastPublicRaceDayJson || (!rows.length && !lastPublicRaceDayJson)) return; + const response = await fetch(`${getBackendUrl()}/api/public-race-day`, { method: "POST", headers: { "Content-Type": "application/json" }, body: json }); + if (response.ok) lastPublicRaceDayJson = json; +} +if (!overlayMode) setInterval(() => { publishPublicRaceDay().catch(() => {}); }, 15000); + // Optional morning check-in (check_in_logic.js / check_in_view.js) in Manage race. function startOfTodayMs() { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); } function checkInRowsFor(event) { diff --git a/src/my_race_logic.js b/src/my_race_logic.js new file mode 100644 index 0000000..3ddea65 --- /dev/null +++ b/src/my_race_logic.js @@ -0,0 +1,23 @@ +// "My race today" on the driver's mobile profile: the race master turns Today's schedule into a +// small snapshot (no names, no personal data - driver ids only) and posts it to the server, which +// picks out one driver's heats (server/public_training_profile.js). Pure logic. + +// rows: buildDayRows(date) (with marshals). getEntries(session) -> [{ driverId }] in grid order; +// getResults(session) -> leaderboard rows ({ driverId, laps, resultDisplay }) for heats already run. +export function buildPublicRaceDaySnapshot({ date, rows = [], getClassLabel = () => "", getEntries = () => [], getResults = () => [], isGridStart = () => false }) { + return { + date, + sessions: rows.map((row) => ({ + id: String(row.session.id), + label: [getClassLabel(row.session), row.session.name].filter(Boolean).join(" · "), + start: Math.round(Number(row.start) || 0), + state: row.state, + gridStart: Boolean(isGridStart(row.session)), + entries: getEntries(row.session).map((entry) => String(entry.driverId || "")).filter(Boolean), + marshals: (row.marshals || []).map((entry) => String(entry.driverId || "")).filter(Boolean), + results: row.state === "done" + ? getResults(row.session).filter((item) => item.driverId).map((item, index) => ({ driverId: String(item.driverId), position: index + 1, laps: Number(item.laps) || 0, result: String(item.resultDisplay || "") })) + : [], + })), + }; +} diff --git a/src/public_training.css b/src/public_training.css index 98c6f2d..14e98f3 100644 --- a/src/public_training.css +++ b/src/public_training.css @@ -1563,3 +1563,14 @@ button { @media (max-width: 520px) { .profile-pro .profile-stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } .profile-pro-stints .profile-card-body > p { margin: 0 0 6px; color: var(--muted); font-size: 0.86rem; } @media (max-width: 520px) { .profile-mode-switch { position: static; margin-bottom: 12px; } } + +/* "My race today" (renderMyRace in public_training.js). */ +.my-race { border-left: 4px solid #e63946; padding: 16px 18px; } +.my-race h2 { margin: 0 0 8px; } +.my-race h3 { margin: 12px 0 4px; font-size: 0.95rem; } +.my-race p { display: grid; grid-template-columns: 5.5em 1fr; column-gap: 8px; margin: 6px 0; } +.my-race p strong, .my-race p em { grid-column: 2; } +.my-race p span { grid-column: 1; grid-row: 1 / span 2; color: var(--muted, #9aa3ad); font-size: 0.85rem; } +.my-race p em { font-style: normal; color: var(--muted, #9aa3ad); } +.my-race .is-next strong { font-size: 1.15rem; } +.my-race .my-race-marshal span { color: #f5b942; } diff --git a/src/public_training.js b/src/public_training.js index 10d051e..c99f268 100644 --- a/src/public_training.js +++ b/src/public_training.js @@ -20,6 +20,16 @@ let selectedSource = new URLSearchParams(window.location.search).get("source") | const messages = { sv: { + myRaceTitle: "đ Mitt race idag", + myRaceNext: "NĂ€sta", + myRaceLive: "PĂ„ banan nu", + myRaceAt: "kl {time}", + myRaceIn: "om {min} min", + myRaceGrid: "startplats {pos}", + myRaceMarshal: "đŠș Marshal", + myRaceResults: "Resultat", + myRacePlace: "{pos}:a", + myRaceLaps: "{laps} varv", connection_loading: "HĂ€mtar statistik...", connection_current: "Statistiken Ă€r uppdaterad.", connection_failed: "Uppdateringen misslyckades. Visar senast hĂ€mtade data om de finns.", @@ -212,6 +222,16 @@ const messages = { challengeProgress: "{current} / {target}", }, en: { + myRaceTitle: "đ My race today", + myRaceNext: "Next", + myRaceLive: "On track now", + myRaceAt: "at {time}", + myRaceIn: "in {min} min", + myRaceGrid: "grid {pos}", + myRaceMarshal: "đŠș Marshal", + myRaceResults: "Results", + myRacePlace: "P{pos}", + myRaceLaps: "{laps} laps", connection_loading: "Loading statistics...", connection_current: "Statistics are up to date.", connection_failed: "Update failed. Showing previously loaded data if available.", @@ -728,6 +748,8 @@ function renderProfile(data) { ${drivingOtherClass ? `
${escapeHtml(t("drivingOtherClass", { className: drivingOtherClass.className || drivingOtherClass.classId }))}
` : ""} + ${renderMyRace(data.raceToday)} + ${proMode ? renderProSection(stats, stintCards) : ""}${escapeHtml(index === 0 ? t("myRaceNext") : "")}${escapeHtml(item.label)} ${escapeHtml(when(item))}${item.gridPosition ? ` · ${escapeHtml(t("myRaceGrid", { pos: item.gridPosition }))}` : ""}
`).join("")} + ${marshal.map((item) => `${escapeHtml(t("myRaceMarshal"))}${escapeHtml(item.label)} ${escapeHtml(when(item))}
`).join("")} + ${results.length ? `${escapeHtml(item.label)} ${escapeHtml(t("myRacePlace", { pos: item.position }))} · ${escapeHtml(t("myRaceLaps", { laps: item.laps }))}${item.result ? ` · ${escapeHtml(item.result)}` : ""}
`).join("")}` : ""} +