feat(houseofrc): create a race from a House of RC event and its entries (1.80.0)
This commit is contained in:
1 parent
42df6a786f
commit
9c1f5713e6
18 files changed
+444
-21
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.80.0
|
||||
|
||||
- **Race from a House of RC event:** in the race wizard, **🏠 Fetch from House of RC** lists the coming events (country and dates to choose, or paste an event link/ID). Pick one, choose which of our classes the drivers race, untick anyone not racing, and press **Fill the race wizard**: name, date, class and participants are filled in and you go on with the format as usual. Drivers already in the register are reused with their transponder (matched on their House of RC member, else on the name; from another class the same person is added to this class); new drivers are created with club and car, without a transponder. The race remembers the House of RC event, for sending results back later. House of RC doesn't send the class yet, so fetch once per class.
|
||||
- **Fetch from House of RC (drivers):** a car without a separate make now fills the brand with the model name (e.g. "Xray XB4 2025"), and a name that only differs in upper/lower case (e.g. "anders larsson") is offered and pre-ticked.
|
||||
|
||||
## 1.79.1
|
||||
|
||||
- **Fetch from House of RC:** when no transponder matches, the dialog now explains why (House of RC only knows transponders the drivers added to their profile there, with the full number) instead of just "0 of 12".
|
||||
|
||||
@@ -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. Importing entries and posting results back are 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. In the race wizard, **🏠 Fetch from House of RC** picks a House of RC event and fills in the name, date, class and entered drivers (existing drivers keep their transponders). Posting results back is being built together with House of RC (see ROADMAP.md).
|
||||
- **`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. Att hämta anmälningar och 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. I Race-guiden väljer du med **🏠 Hämta från House of RC** en tävling och får namn, datum, klass och anmälda förare ifyllda (befintliga förare behåller sina transpondrar). Att skicka tillbaka resultat byggs tillsammans med House of RC (se ROADMAP.md).
|
||||
- **`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.
|
||||
|
||||
+9
-2
@@ -1003,9 +1003,16 @@ Agreed with Conny (House of RC), 2026-11-07:
|
||||
- **Result format:** send back the same structure as the entries came in, with the results added: driver ID, class and result. Extra heat data can be sent along too; House of RC stores it, as it already does from MyRCM and LiveRC.
|
||||
- If entries change on the House of RC side (late entry, withdrawal), RaceCore fetches them again. Results go only one way: RaceCore → House of RC.
|
||||
|
||||
Status 2026-11-08 (1.78.0-1.80.0):
|
||||
- [x] Key stored server-side (`data/houseofrc.json`, mode 600), Settings → System → House of RC with **Test connection** (`/v1/me` works).
|
||||
- [x] Drivers → **Fetch from House of RC**: names and makes by transponder (`/timing/users`); drivers are linked by `houseOfRcId`.
|
||||
- [x] Race wizard → **Fetch from House of RC**: events via `/v1/events` (filtered by country here), entries via `/results?event_id=` (before the race it lists the entered drivers with 0 points). The race stores `houseOfRc.eventId`.
|
||||
- Note: on 2026-11-08 `/results` answered 404 for every event (also ones that listed entries the day before) and `/openapi.yaml` gave "Server Error"; ask Conny.
|
||||
|
||||
Still open with Conny:
|
||||
- [ ] Test the key with `GET /v1/me`.
|
||||
- [ ] Which endpoint gives an event's entries per class (with House of RC driver ID, class/eventclass ID, driver number and transponder)?
|
||||
- [x] Test the key with `GET /v1/me`.
|
||||
- [ ] An event's classes (eventclass ID + name), e.g. `/v1/events/{id}/classes`, so one fetch can create a race per class instead of choosing our class by hand.
|
||||
- [ ] The transponder per entry (or the eventclass ID per row in `/results`), so new drivers don't need it typed in.
|
||||
- [ ] 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?
|
||||
- [ ] A test event to post against.
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "rc-racecore",
|
||||
"version": "1.79.1",
|
||||
"version": "1.80.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "rc-racecore",
|
||||
"version": "1.79.1",
|
||||
"version": "1.80.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^12.11.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "rc-racecore",
|
||||
"version": "1.79.1",
|
||||
"version": "1.80.0",
|
||||
"private": true,
|
||||
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
|
||||
"engines": {
|
||||
|
||||
@@ -488,6 +488,14 @@ app.post("/api/houseofrc/transponders", async (req, res) => {
|
||||
const result = await houseOfRc.lookupTransponders(req.body?.transponders);
|
||||
res.status(result.ok ? 200 : 502).json(result);
|
||||
});
|
||||
app.post("/api/houseofrc/events", async (req, res) => {
|
||||
const result = await houseOfRc.listEvents({ from: req.body?.from, to: req.body?.to, country: req.body?.country });
|
||||
res.status(result.ok ? 200 : 502).json(result);
|
||||
});
|
||||
app.post("/api/houseofrc/entries", async (req, res) => {
|
||||
const result = await houseOfRc.getEventEntries(req.body?.eventId, req.body?.eventclassId);
|
||||
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") {
|
||||
|
||||
+47
-1
@@ -88,6 +88,7 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
|
||||
id: user.id ?? null,
|
||||
name: String(user.name || "").trim(),
|
||||
model: String(user.model?.name || "").trim(),
|
||||
// Often only the model name carries the make ("Xray XB4 2025"), with no brand object.
|
||||
brand: String(user.model?.brand?.name || "").trim(),
|
||||
};
|
||||
});
|
||||
@@ -95,7 +96,52 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
|
||||
return { ok: true, status: 200, asked: numbers.length, members };
|
||||
}
|
||||
|
||||
return { status, setKey, get, testConnection, lookupTransponders };
|
||||
const pickEvent = (event) => ({
|
||||
id: event.id, name: String(event.name || ""), type: event.type || "", status: event.status || null,
|
||||
start: event.start || null, end: event.end || null, city: event.city || "", country: event.country || "",
|
||||
organizerId: event.organizer_id ?? null, seriesId: event.series_id ?? null, url: event.web_url || "",
|
||||
});
|
||||
|
||||
// Upcoming events in a date range (the API has no country or text filter, so filter here).
|
||||
// At most 5 pages of 100 to stay well inside the rate limit.
|
||||
async function listEvents({ from, to, country = "" } = {}) {
|
||||
const events = [];
|
||||
for (let page = 1; page <= 5; page += 1) {
|
||||
const result = await get("/v1/events", { start_from: from, start_to: to, sort: "start", per_page: 100, page });
|
||||
if (!result.ok) return result;
|
||||
const rows = Array.isArray(result.data?.data) ? result.data.data : [];
|
||||
events.push(...rows.map(pickEvent));
|
||||
if (!result.data?.links?.next || rows.length < 100) break;
|
||||
}
|
||||
const wanted = String(country || "").toUpperCase();
|
||||
return { ok: true, status: 200, events: events.filter((event) => !wanted || String(event.country).toUpperCase() === wanted) };
|
||||
}
|
||||
|
||||
// One event and its entered drivers. /results on an event that hasn't been run yet lists the
|
||||
// entries (0 points); cancelled and waiting-list entries are already left out.
|
||||
async function getEventEntries(eventId, eventclassId) {
|
||||
// An id, or a pasted link like https://houseofrc.com/events/2253.
|
||||
const text = String(eventId || "").trim();
|
||||
const id = Number(text.match(/events\/(\d+)/)?.[1] || text.match(/^\d+$/)?.[0]);
|
||||
if (!Number.isInteger(id) || id < 1) return { ok: false, status: 400, error: "invalid_event" };
|
||||
const event = await get(`/v1/events/${id}`);
|
||||
if (!event.ok) return event.status === 404 ? { ...event, error: "event_not_found" } : event;
|
||||
const results = await get("/results", { event_id: id, eventclass_id: eventclassId || undefined });
|
||||
if (!results.ok) return results;
|
||||
const entries = (Array.isArray(results.data) ? results.data : []).map((row) => ({
|
||||
houseOfRcId: row.user_id ?? null,
|
||||
name: String(row.name || [row.firstname, row.lastname].filter(Boolean).join(" ")).trim(),
|
||||
number: row.number ?? null,
|
||||
club: String(row.club || "").trim(),
|
||||
country: String(row.country || "").trim(),
|
||||
car: [row.brand1 && !String(row.product || "").toLowerCase().startsWith(String(row.brand1).toLowerCase()) ? row.brand1 : "", row.product].filter(Boolean).join(" ").trim(),
|
||||
brand: String(row.brand1 || "").trim(),
|
||||
points: row.points ?? null,
|
||||
})).filter((entry) => entry.name);
|
||||
return { ok: true, status: 200, event: pickEvent(event.data?.data || {}), entries };
|
||||
}
|
||||
|
||||
return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries };
|
||||
}
|
||||
|
||||
module.exports = { createHouseOfRc, DEFAULT_BASE_URL };
|
||||
+49
@@ -2196,6 +2196,30 @@ const TRANSLATIONS = {
|
||||
"houseofrc.import_model": "Bil",
|
||||
"houseofrc.import_apply": "Uppdatera valda",
|
||||
"houseofrc.filled_from": "Ifyllt från House of RC ({model})",
|
||||
"houseofrc.event_button": "Hämta från House of RC",
|
||||
"houseofrc.event_button_hint": "Välj en tävling på House of RC och fyll i guiden med dess anmälda förare",
|
||||
"houseofrc.event_title": "Tävling från House of RC",
|
||||
"houseofrc.event_from": "Från",
|
||||
"houseofrc.event_to": "Till",
|
||||
"houseofrc.event_country": "Land",
|
||||
"houseofrc.event_search": "Sök",
|
||||
"houseofrc.event_link_placeholder": "…eller klistra in länk/ID, t.ex. https://houseofrc.com/events/2251",
|
||||
"houseofrc.event_open": "Öppna",
|
||||
"houseofrc.event_loading": "Hämtar tävlingar…",
|
||||
"houseofrc.event_none": "Inga tävlingar i den perioden.",
|
||||
"houseofrc.event_back": "Tävlingar",
|
||||
"houseofrc.entries_loading": "Hämtar anmälda förare…",
|
||||
"houseofrc.entries_not_found": "House of RC har inga anmälningar för den här tävlingen (404). Tar klubben anmälan någon annanstans, t.ex. MyRCM?",
|
||||
"houseofrc.entries_empty": "Inga anmälda förare än.",
|
||||
"houseofrc.entries_class": "Klass hos oss",
|
||||
"houseofrc.entries_class_hint": "House of RC skickar inte klassen än: välj vilken klass de här förarna kör. Hämta igen för nästa klass.",
|
||||
"houseofrc.entries_all": "Alla",
|
||||
"houseofrc.entries_hint": "Befintliga förare återanvänds (med transponder). Nya förare skapas utan transponder – fyll i den under Förare eller i Deltagare.",
|
||||
"houseofrc.entries_apply": "Fyll i Race-guiden",
|
||||
"houseofrc.entry_linked": "Finns",
|
||||
"houseofrc.entry_name": "Finns (samma namn)",
|
||||
"houseofrc.entry_copy": "Finns i annan klass",
|
||||
"houseofrc.entry_new": "Ny förare",
|
||||
"houseofrc.title": "House of RC",
|
||||
"houseofrc.hint": "Klubbens API-nyckel från House of RC. Den sparas bara på servern (data/houseofrc.json) och visas aldrig igen, inte ens här.",
|
||||
"houseofrc.key": "API-nyckel",
|
||||
@@ -4378,6 +4402,30 @@ const TRANSLATIONS = {
|
||||
"houseofrc.import_model": "Car",
|
||||
"houseofrc.import_apply": "Update selected",
|
||||
"houseofrc.filled_from": "Filled in from House of RC ({model})",
|
||||
"houseofrc.event_button": "Fetch from House of RC",
|
||||
"houseofrc.event_button_hint": "Pick an event on House of RC and fill the wizard with its entered drivers",
|
||||
"houseofrc.event_title": "Event from House of RC",
|
||||
"houseofrc.event_from": "From",
|
||||
"houseofrc.event_to": "To",
|
||||
"houseofrc.event_country": "Country",
|
||||
"houseofrc.event_search": "Search",
|
||||
"houseofrc.event_link_placeholder": "…or paste a link/ID, e.g. https://houseofrc.com/events/2251",
|
||||
"houseofrc.event_open": "Open",
|
||||
"houseofrc.event_loading": "Fetching events…",
|
||||
"houseofrc.event_none": "No events in that period.",
|
||||
"houseofrc.event_back": "Events",
|
||||
"houseofrc.entries_loading": "Fetching entered drivers…",
|
||||
"houseofrc.entries_not_found": "House of RC has no entries for this event (404). Does the club take entries elsewhere, e.g. MyRCM?",
|
||||
"houseofrc.entries_empty": "No drivers entered yet.",
|
||||
"houseofrc.entries_class": "Our class",
|
||||
"houseofrc.entries_class_hint": "House of RC doesn't send the class yet: choose which class these drivers race. Fetch again for the next class.",
|
||||
"houseofrc.entries_all": "All",
|
||||
"houseofrc.entries_hint": "Existing drivers are reused (with their transponder). New drivers are created without a transponder – fill it in under Drivers or Participants.",
|
||||
"houseofrc.entries_apply": "Fill the race wizard",
|
||||
"houseofrc.entry_linked": "Exists",
|
||||
"houseofrc.entry_name": "Exists (same name)",
|
||||
"houseofrc.entry_copy": "Exists in another class",
|
||||
"houseofrc.entry_new": "New driver",
|
||||
"houseofrc.title": "House of RC",
|
||||
"houseofrc.hint": "The club's House of RC API key. It is stored on the server only (data/houseofrc.json) and never shown again, not even here.",
|
||||
"houseofrc.key": "API key",
|
||||
@@ -7369,6 +7417,7 @@ function renderEventWorkspace(mode) {
|
||||
renderEventManager,
|
||||
uid,
|
||||
normalizeEvent,
|
||||
normalizeDriver,
|
||||
applyRaceFormatPreset,
|
||||
buildOpenPracticeBundle,
|
||||
buildRaceSessionsFromWizard,
|
||||
|
||||
+1
-1
@@ -123,7 +123,7 @@ export function renderEventWorkspaceMarkup(mode, deps) {
|
||||
}
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header"><h3>${t(isRaceMode ? "events.create_competition_race" : "events.create")}</h3></div>
|
||||
<div class="panel-header"><h3>${t(isRaceMode ? "events.create_competition_race" : "events.create")}</h3>${isRaceMode ? `<button class="btn" id="raceWizardHouseOfRc" type="button" title="${escapeHtml(t("houseofrc.event_button_hint"))}">🏠 ${t("houseofrc.event_button")}</button>` : ""}</div>
|
||||
<div class="panel-body">
|
||||
<p>${t(isRaceMode ? "events.race_only_intro" : "events.track_only_intro")}</p>
|
||||
${isRaceMode ? `<p class="hint">${t("events.wizard_hint")}</p>` : ""}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { openHouseOfRcEventImport } from "./houseofrc_view.js";
|
||||
import { renderEventWorkspaceMarkup } from "./event_views.js";
|
||||
|
||||
// The folded "Done" races remember whether they were opened (per browser only).
|
||||
@@ -41,6 +42,7 @@ export function renderEventWorkspaceView(context) {
|
||||
renderEventManager,
|
||||
uid,
|
||||
normalizeEvent,
|
||||
normalizeDriver,
|
||||
applyRaceFormatPreset,
|
||||
buildOpenPracticeBundle,
|
||||
buildRaceSessionsFromWizard,
|
||||
@@ -245,6 +247,23 @@ export function renderEventWorkspaceView(context) {
|
||||
renderView();
|
||||
});
|
||||
|
||||
document.getElementById("raceWizardHouseOfRc")?.addEventListener("click", () => openHouseOfRcEventImport({
|
||||
state, t, escapeHtml, uid, saveState,
|
||||
makeDriver: (fields) => normalizeDriver({ id: uid("driver"), ...fields }),
|
||||
onImported: ({ event, classId, driverIds }) => {
|
||||
const draft = getRaceWizardDraft();
|
||||
Object.assign(draft, {
|
||||
name: draft.name.trim() || event.name,
|
||||
date: String(event.start || "").slice(0, 10) || draft.date,
|
||||
classId,
|
||||
driverIds,
|
||||
houseOfRc: { eventId: event.id, name: event.name, url: event.url },
|
||||
});
|
||||
setRaceWizardStep(2);
|
||||
renderView();
|
||||
},
|
||||
}));
|
||||
|
||||
document.getElementById("raceWizardCreate")?.addEventListener("click", () => {
|
||||
const draft = getRaceWizardDraft();
|
||||
const selectedDrivers = draft.driverIds.length ? draft.driverIds : getDriversForClass(draft.classId).map((driver) => driver.id);
|
||||
@@ -254,6 +273,8 @@ export function renderEventWorkspaceView(context) {
|
||||
date: draft.date,
|
||||
classId: draft.classId,
|
||||
mode,
|
||||
// Filled by "Fetch from House of RC": where the results go back to later.
|
||||
...(draft.houseOfRc ? { houseOfRc: draft.houseOfRc } : {}),
|
||||
});
|
||||
applyRaceFormatPreset(event, draft.presetId);
|
||||
event.raceConfig.driverIds = selectedDrivers;
|
||||
|
||||
+65
-5
@@ -3,22 +3,29 @@
|
||||
// only when ours is empty (a name that is just the transponder number counts as empty).
|
||||
const sameText = (a, b) => String(a || "").trim().toLocaleLowerCase().replace(/\s+/g, " ") === String(b || "").trim().toLocaleLowerCase().replace(/\s+/g, " ");
|
||||
|
||||
// The make: House of RC often has it only inside the model name ("Xray XB4 2025").
|
||||
const memberBrand = (member) => member.brand || member.model || "";
|
||||
const isPlaceholderName = (driver) => !driver.name || sameText(driver.name, driver.transponder);
|
||||
|
||||
export function planHouseOfRcDriverUpdates(drivers = [], members = {}) {
|
||||
return drivers
|
||||
.filter((driver) => !driver.guestEventId && driver.transponder && members[driver.transponder])
|
||||
.map((driver) => {
|
||||
const member = members[driver.transponder];
|
||||
const nameDiffers = Boolean(member.name) && !sameText(member.name, driver.name);
|
||||
const brandDiffers = Boolean(member.brand) && !sameText(member.brand, driver.brand);
|
||||
const brand = memberBrand(member);
|
||||
// Any difference counts, also only upper/lower case ("anders larsson").
|
||||
const nameDiffers = Boolean(member.name) && member.name.trim() !== String(driver.name || "").trim();
|
||||
const brandDiffers = Boolean(brand) && !sameText(brand, driver.brand);
|
||||
return {
|
||||
driverId: driver.id,
|
||||
transponder: driver.transponder,
|
||||
currentName: driver.name || "",
|
||||
currentBrand: driver.brand || "",
|
||||
member,
|
||||
member: { ...member, brand },
|
||||
nameDiffers,
|
||||
brandDiffers,
|
||||
nameDefault: nameDiffers && (!driver.name || sameText(driver.name, driver.transponder)),
|
||||
// Pre-ticked: empty, just the transponder number, or the same name in other letters.
|
||||
nameDefault: nameDiffers && (isPlaceholderName(driver) || sameText(driver.name, member.name)),
|
||||
brandDefault: brandDiffers && !driver.brand,
|
||||
linked: String(driver.houseOfRcId || "") === String(member.id ?? ""),
|
||||
};
|
||||
@@ -35,9 +42,62 @@ export function applyHouseOfRcDriverUpdates(drivers = [], members = {}, choices
|
||||
const choice = choices[driver.id] || {};
|
||||
const before = JSON.stringify(driver);
|
||||
if (choice.name && member.name) driver.name = member.name;
|
||||
if (choice.brand && member.brand) driver.brand = member.brand;
|
||||
if (choice.brand && memberBrand(member)) driver.brand = memberBrand(member);
|
||||
if (member.id != null && sameText(driver.name, member.name)) driver.houseOfRcId = String(member.id);
|
||||
if (JSON.stringify(driver) !== before) changed += 1;
|
||||
});
|
||||
return changed;
|
||||
}
|
||||
|
||||
// Entries of a House of RC event against our register, for one of our classes:
|
||||
// linked - already a driver in that class with this House of RC id
|
||||
// name - a driver in that class with the same name (gets linked)
|
||||
// copy - the person exists in another class: a new driver in this class, same profile
|
||||
// new - unknown: a new driver (transponder to fill in)
|
||||
export function planHouseOfRcEntries(entries = [], drivers = [], classId = "") {
|
||||
const club = drivers.filter((driver) => !driver.guestEventId);
|
||||
const sameMember = (entry) => (driver) => entry.houseOfRcId != null && String(driver.houseOfRcId || "") === String(entry.houseOfRcId);
|
||||
const sameName = (entry) => (driver) => sameText(driver.name, entry.name);
|
||||
return entries.map((entry) => {
|
||||
const inClass = club.filter((driver) => driver.classId === classId);
|
||||
const linked = inClass.find(sameMember(entry));
|
||||
if (linked) return { entry, status: "linked", driverId: linked.id, transponder: linked.transponder };
|
||||
const named = inClass.find(sameName(entry));
|
||||
if (named) return { entry, status: "name", driverId: named.id, transponder: named.transponder };
|
||||
const source = club.find(sameMember(entry)) || club.find(sameName(entry));
|
||||
if (source) return { entry, status: "copy", sourceId: source.id, transponder: source.transponder };
|
||||
return { entry, status: "new", transponder: "" };
|
||||
});
|
||||
}
|
||||
|
||||
// Creates/links the ticked entries and returns their driver ids in House of RC order.
|
||||
// makeDriver(fields) must return a normalized driver with a fresh id.
|
||||
export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDriver }) {
|
||||
const ids = [];
|
||||
plan.forEach((row, index) => {
|
||||
if (!selected.has(index)) return;
|
||||
const { entry } = row;
|
||||
const memberId = entry.houseOfRcId != null ? String(entry.houseOfRcId) : "";
|
||||
if (row.driverId) {
|
||||
const driver = drivers.find((item) => item.id === row.driverId);
|
||||
if (driver && memberId) driver.houseOfRcId = memberId;
|
||||
if (driver) ids.push(driver.id);
|
||||
return;
|
||||
}
|
||||
const source = row.sourceId ? drivers.find((item) => item.id === row.sourceId) : null;
|
||||
const driver = makeDriver({
|
||||
name: source?.name || entry.name,
|
||||
classId,
|
||||
transponder: source?.transponder || "",
|
||||
brand: entry.car || source?.brand || "",
|
||||
club: entry.club || source?.club || "",
|
||||
country: source?.country || "",
|
||||
speechName: source?.speechName || "",
|
||||
profileId: source?.profileId || "",
|
||||
houseOfRcId: memberId,
|
||||
});
|
||||
drivers.push(driver);
|
||||
ids.push(driver.id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
+115
-1
@@ -1,4 +1,4 @@
|
||||
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates } from "./houseofrc_logic.js";
|
||||
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries } 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).
|
||||
@@ -150,3 +150,117 @@ export async function openHouseOfRcDriverImport({ state, t, escapeHtml, saveStat
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openHorModal({ id, title, escapeHtml, wide = true }) {
|
||||
document.getElementById(id)?.remove();
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "modal-overlay";
|
||||
overlay.id = id;
|
||||
overlay.innerHTML = `<div class="modal-card ${wide ? "hor-import" : ""}"><div class="panel-header"><h3>🏠 ${escapeHtml(title)}</h3><button class="btn" type="button" data-hor-close>✕</button></div><div class="panel-body" data-hor-body></div></div>`;
|
||||
document.body.append(overlay);
|
||||
const onKey = (event) => { if (event.key === "Escape") close(); };
|
||||
const close = () => { overlay.remove(); document.removeEventListener("keydown", onKey); };
|
||||
document.addEventListener("keydown", onKey);
|
||||
overlay.addEventListener("click", (event) => { if (event.target === overlay || event.target.closest("[data-hor-close]")) close(); });
|
||||
return { overlay, body: overlay.querySelector("[data-hor-body]"), close };
|
||||
}
|
||||
|
||||
// Race wizard → "Fetch from House of RC": pick an event, then one of our classes and the
|
||||
// entered drivers; fills the wizard (name, date, class, participants) and links the event.
|
||||
export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, makeDriver, onImported }) {
|
||||
const { overlay, body, close } = openHorModal({ id: "houseOfRcEventOverlay", title: t("houseofrc.event_title"), escapeHtml });
|
||||
const day = (offset) => new Date(Date.now() + offset * 864e5).toISOString().slice(0, 10);
|
||||
const fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short" }) : "");
|
||||
const error = (code, data) => `<p class="error">${escapeHtml(describeHouseOfRcError(t, code, data))}</p>`;
|
||||
|
||||
const showEvents = async (filters = { from: day(0), to: day(60), country: "SE" }) => {
|
||||
body.innerHTML = `
|
||||
<form class="form-grid cols-4" data-hor-filter>
|
||||
<label>${escapeHtml(t("houseofrc.event_from"))}<input type="date" name="from" value="${escapeHtml(filters.from)}" /></label>
|
||||
<label>${escapeHtml(t("houseofrc.event_to"))}<input type="date" name="to" value="${escapeHtml(filters.to)}" /></label>
|
||||
<label>${escapeHtml(t("houseofrc.event_country"))}<input name="country" maxlength="2" value="${escapeHtml(filters.country)}" placeholder="SE" /></label>
|
||||
<div class="actions-inline align-end"><button class="btn" type="submit">${escapeHtml(t("houseofrc.event_search"))}</button></div>
|
||||
</form>
|
||||
<form class="hor-link-row mt-16" data-hor-link>
|
||||
<input name="link" placeholder="${escapeHtml(t("houseofrc.event_link_placeholder"))}" />
|
||||
<button class="btn btn-primary" type="submit">${escapeHtml(t("houseofrc.event_open"))}</button>
|
||||
</form>
|
||||
<div class="mt-16" data-hor-list><p class="hint">${escapeHtml(t("houseofrc.event_loading"))}</p></div>`;
|
||||
body.querySelector("[data-hor-filter]").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
showEvents({ from: String(form.get("from") || day(0)), to: String(form.get("to") || day(60)), country: String(form.get("country") || "").trim().toUpperCase() });
|
||||
});
|
||||
body.querySelector("[data-hor-link]").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const link = String(new FormData(event.currentTarget).get("link") || "").trim();
|
||||
if (link) showEntries(link);
|
||||
});
|
||||
const list = body.querySelector("[data-hor-list]");
|
||||
const { status: code, body: data } = await postJson("/api/houseofrc/events", { from: `${filters.from}T00:00:00Z`, to: `${filters.to}T23:59:59Z`, country: filters.country });
|
||||
if (!overlay.isConnected || !list.isConnected) return;
|
||||
if (code !== 200 || !data.ok) { list.innerHTML = error(code, data); return; }
|
||||
const events = (data.events || []).filter((event) => event.status !== "cancelled");
|
||||
list.innerHTML = events.length
|
||||
? `<div class="hor-event-list">${events.map((event) => `
|
||||
<button type="button" class="hor-event" data-hor-event="${escapeHtml(String(event.id))}">
|
||||
<strong>${escapeHtml(event.name)}</strong>
|
||||
<small>${escapeHtml([fmtDate(event.start), event.city].filter(Boolean).join(" · "))}</small>
|
||||
</button>`).join("")}</div>`
|
||||
: `<p class="hint">${escapeHtml(t("houseofrc.event_none"))}</p>`;
|
||||
list.querySelectorAll("[data-hor-event]").forEach((button) => button.addEventListener("click", () => showEntries(button.dataset.horEvent)));
|
||||
};
|
||||
|
||||
const showEntries = async (eventRef) => {
|
||||
body.innerHTML = `<p class="hint">${escapeHtml(t("houseofrc.entries_loading"))}</p>`;
|
||||
const { status: code, body: data } = await postJson("/api/houseofrc/entries", { eventId: eventRef });
|
||||
if (!overlay.isConnected) return;
|
||||
const back = `<button class="btn" type="button" data-hor-back>← ${escapeHtml(t("houseofrc.event_back"))}</button>`;
|
||||
const bindBack = () => body.querySelector("[data-hor-back]")?.addEventListener("click", () => showEvents());
|
||||
if (code !== 200 || !data.ok) {
|
||||
body.innerHTML = (code === 502 && data.status === 404 ? `<p class="error">${escapeHtml(t("houseofrc.entries_not_found"))}</p>` : error(code, data)) + back;
|
||||
bindBack();
|
||||
return;
|
||||
}
|
||||
const { event, entries } = data;
|
||||
let classId = state.classes[0]?.id || "";
|
||||
const render = () => {
|
||||
const plan = planHouseOfRcEntries(entries, state.drivers, classId);
|
||||
const statusText = (row) => t(`houseofrc.entry_${row.status}`);
|
||||
body.innerHTML = `
|
||||
<p><strong>${escapeHtml(event.name)}</strong> · ${escapeHtml([fmtDate(event.start), event.city].filter(Boolean).join(" · "))}${event.url ? ` · <a href="${escapeHtml(event.url)}" target="_blank" rel="noopener">House of RC ↗</a>` : ""}</p>
|
||||
${entries.length ? `
|
||||
<label>${escapeHtml(t("houseofrc.entries_class"))}
|
||||
<select data-hor-class>${state.classes.map((item) => `<option value="${escapeHtml(item.id)}" ${item.id === classId ? "selected" : ""}>${escapeHtml(item.name)}</option>`).join("")}</select>
|
||||
<small>${escapeHtml(t("houseofrc.entries_class_hint"))}</small>
|
||||
</label>
|
||||
<div class="table-wrap mt-16"><table class="hor-import-table">
|
||||
<thead><tr><th><input type="checkbox" data-hor-all checked aria-label="${escapeHtml(t("houseofrc.entries_all"))}" /></th><th>${escapeHtml(t("table.name"))}</th><th>${escapeHtml(t("drivers.club"))}</th><th>${escapeHtml(t("houseofrc.import_model"))}</th><th>${escapeHtml(t("table.transponder"))}</th><th></th></tr></thead>
|
||||
<tbody>${plan.map((row, index) => `<tr>
|
||||
<td><input type="checkbox" data-hor-entry="${index}" checked /></td>
|
||||
<td>${escapeHtml(row.entry.name)}${row.entry.number != null ? ` <small>#${escapeHtml(String(row.entry.number))}</small>` : ""}</td>
|
||||
<td>${escapeHtml(row.entry.club || "–")}</td>
|
||||
<td>${escapeHtml(row.entry.car || "–")}</td>
|
||||
<td>${escapeHtml(row.transponder || "–")}</td>
|
||||
<td><span class="pill ${row.status === "new" ? "pill-warn" : "pill-green"}">${escapeHtml(statusText(row))}</span></td>
|
||||
</tr>`).join("")}</tbody>
|
||||
</table></div>
|
||||
<p class="hint">${escapeHtml(t("houseofrc.entries_hint"))}</p>
|
||||
<div class="actions mt-16">${back}<button class="btn btn-primary" type="button" data-hor-apply>${escapeHtml(t("houseofrc.entries_apply"))}</button></div>`
|
||||
: `<p>${escapeHtml(t("houseofrc.entries_empty"))}</p>${back}`}`;
|
||||
bindBack();
|
||||
body.querySelector("[data-hor-class]")?.addEventListener("change", (change) => { classId = change.target.value; render(); });
|
||||
body.querySelector("[data-hor-all]")?.addEventListener("change", (change) => body.querySelectorAll("[data-hor-entry]").forEach((box) => { box.checked = change.target.checked; }));
|
||||
body.querySelector("[data-hor-apply]")?.addEventListener("click", () => {
|
||||
const selected = new Set([...body.querySelectorAll("[data-hor-entry]:checked")].map((box) => Number(box.dataset.horEntry)));
|
||||
const driverIds = applyHouseOfRcEntries(state.drivers, plan, { classId, selected, makeDriver });
|
||||
saveState();
|
||||
close();
|
||||
onImported({ event, classId, driverIds });
|
||||
});
|
||||
};
|
||||
render();
|
||||
};
|
||||
|
||||
showEvents();
|
||||
}
|
||||
@@ -4947,3 +4947,9 @@ tr:has(> td > .medal-3) { background: linear-gradient(90deg, rgba(205, 127, 60,
|
||||
.hor-import-table td { vertical-align: middle; }
|
||||
.hor-choice { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||
.hor-choice s { opacity: 0.6; }
|
||||
.hor-link-row { display: flex; gap: 8px; }
|
||||
.hor-link-row input { flex: 1; min-width: 0; }
|
||||
.hor-event-list { display: grid; gap: 6px; max-height: 50vh; overflow: auto; }
|
||||
.hor-event { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; text-align: left; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; background: transparent; color: inherit; cursor: pointer; }
|
||||
.hor-event:hover, .hor-event:focus-visible { border-color: var(--accent); }
|
||||
.hor-event small { opacity: 0.75; }
|
||||
@@ -64,3 +64,61 @@ export async function runHouseOfRcSmoke({ evaluate, navigate, savedState, waitFo
|
||||
await patchState({ drivers: current.drivers.filter((driver) => !driver.id.startsWith("hor_")) });
|
||||
}
|
||||
}
|
||||
|
||||
// Race wizard → "Fetch from House of RC": pick an event, choose our class, the entered drivers
|
||||
// fill the wizard; the created event remembers the House of RC event for the results later.
|
||||
export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, waitFor, base }) {
|
||||
try {
|
||||
await navigate("race_setup", "raceWizardStepForm");
|
||||
await evaluate(`(() => {
|
||||
const realFetch = window.fetch;
|
||||
window.fetch = async (url, options) => {
|
||||
const json = (data) => new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } });
|
||||
if (String(url).includes("/api/houseofrc/events")) return json({ ok: true, events: [{ id: 2251, name: "HoR Deltävling 2", start: "2026-12-05T07:00:00Z", city: "Sundsvall", country: "SE", url: "https://houseofrc.com/events/2251" }] });
|
||||
if (String(url).includes("/api/houseofrc/entries")) return json({ ok: true, event: { id: 2251, name: "HoR Deltävling 2", start: "2026-12-05T07:00:00Z", city: "Sundsvall", url: "https://houseofrc.com/events/2251" }, entries: [
|
||||
{ houseOfRcId: 901, name: "HoR Anna", number: 7, club: "Sundsvall RC", car: "XRAY X12" },
|
||||
{ houseOfRcId: 902, name: "HoR Bo", number: null, club: "", car: "" },
|
||||
{ houseOfRcId: 903, name: "HoR Skipped", number: null, club: "", car: "" },
|
||||
] });
|
||||
return realFetch(url, options);
|
||||
};
|
||||
})()`);
|
||||
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()`);
|
||||
await waitFor(async () => evaluate(`Boolean(document.querySelector("[data-hor-apply]"))`), "the entries");
|
||||
const statuses = await evaluate(`[...document.querySelectorAll("#houseOfRcEventOverlay tbody .pill")].map((pill) => pill.textContent.trim())`);
|
||||
assert.equal(statuses.length, 3);
|
||||
await evaluate(`(() => {
|
||||
const select = document.querySelector("[data-hor-class]");
|
||||
select.value = "test_class"; select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
})()`);
|
||||
await evaluate(`(() => { document.querySelector('[data-hor-entry="2"]').checked = false; document.querySelector("[data-hor-apply]").click(); })()`);
|
||||
await waitFor(async () => (await savedState()).drivers.some((driver) => driver.name === "HoR Anna"), "new drivers saved");
|
||||
const drivers = (await savedState()).drivers;
|
||||
const anna = drivers.find((driver) => driver.name === "HoR Anna");
|
||||
assert.deepEqual([anna.classId, anna.club, anna.brand, anna.houseOfRcId], ["test_class", "Sundsvall RC", "XRAY X12", "901"]);
|
||||
assert.equal(drivers.some((driver) => driver.name === "HoR Skipped"), false, "an unticked entry is not created");
|
||||
const ticked = await evaluate(`[...document.querySelectorAll(".wizard-participant:checked")].map((box) => box.value)`);
|
||||
const ids = drivers.filter((driver) => ["HoR Anna", "HoR Bo"].includes(driver.name)).map((driver) => driver.id);
|
||||
assert.deepEqual([...ticked].sort(), [...ids].sort(), "the wizard is on Participants with exactly the entered drivers");
|
||||
await evaluate(`document.getElementById("raceWizardNext").click()`);
|
||||
await evaluate(`document.getElementById("raceWizardNext").click()`);
|
||||
await evaluate(`document.getElementById("raceWizardCreate").click()`);
|
||||
await waitFor(async () => (await savedState()).events.some((event) => event.name === "HoR Deltävling 2"), "the race is created");
|
||||
const event = (await savedState()).events.find((item) => item.name === "HoR Deltävling 2");
|
||||
assert.deepEqual([event.date, event.classId, event.houseOfRc?.eventId], ["2026-12-05", "test_class", 2251]);
|
||||
assert.deepEqual([...event.raceConfig.driverIds].sort(), [...ids].sort());
|
||||
console.log("PASS House of RC event import: pick an event and class, entered drivers fill the race wizard, the race keeps the House of RC event id");
|
||||
} finally {
|
||||
await evaluate(`document.getElementById("houseOfRcEventOverlay")?.remove()`).catch(() => {});
|
||||
const current = await savedState();
|
||||
const eventIds = current.events.filter((event) => event.name === "HoR Deltävling 2").map((event) => event.id);
|
||||
Object.assign(current, {
|
||||
drivers: current.drivers.filter((driver) => !String(driver.name).startsWith("HoR ")),
|
||||
events: current.events.filter((event) => !eventIds.includes(event.id)),
|
||||
sessions: current.sessions.filter((session) => !eventIds.includes(session.eventId)),
|
||||
});
|
||||
await fetch(base + "/api/state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(current) });
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import { runProfileClassSmoke } from "./browser_profile_class.js";
|
||||
import { runDecoderClockSmoke } from "./browser_decoder_clock.js";
|
||||
import { runCorrectionsScopeSmoke } from "./browser_corrections_scope.js";
|
||||
import { runDriversPageSmoke } from "./browser_drivers_page.js";
|
||||
import { runHouseOfRcSmoke } from "./browser_houseofrc.js";
|
||||
import { runHouseOfRcSmoke, runHouseOfRcEventSmoke } from "./browser_houseofrc.js";
|
||||
import { runSeriesSmoke } from "./browser_series.js";
|
||||
import { runTrainingSourceSmoke } from "./browser_training_source.js";
|
||||
import { runDecoderUrlSmoke } from "./browser_decoder_url.js";
|
||||
@@ -183,6 +183,7 @@ try {
|
||||
await runCorrectionsScopeSmoke({ evaluate, navigate, savedState, waitFor, base });
|
||||
await runDriversPageSmoke({ evaluate, navigate, savedState, waitFor, base });
|
||||
await runHouseOfRcSmoke({ evaluate, navigate, savedState, waitFor, base });
|
||||
await runHouseOfRcEventSmoke({ evaluate, navigate, savedState, waitFor, base });
|
||||
await runSeriesSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs });
|
||||
await runTrainingSourceSmoke({ evaluate, navigate, savedState, waitFor, base });
|
||||
await runDecoderUrlSmoke({ evaluate, navigate, savedState, waitFor, base });
|
||||
|
||||
@@ -6,22 +6,25 @@ const members = {
|
||||
"1001": { id: 68, name: "Anna Andersson", brand: "Associated", model: "B7" },
|
||||
"1002": { id: 70, name: "Bo Berg", brand: "Xray", model: "XB4" },
|
||||
"1003": { id: 71, name: "Cecilia Carlsson", brand: "", model: "" },
|
||||
"1004": { id: 68, name: "Anders Larsson", brand: "", model: "Xray XB4 2025" },
|
||||
};
|
||||
const drivers = () => [
|
||||
{ id: "a", name: "1001", transponder: "1001", brand: "" },
|
||||
{ id: "b", name: "Bosse", transponder: "1002", brand: "Team Berg" },
|
||||
{ id: "c", name: "cecilia carlsson", transponder: "1003", brand: "" },
|
||||
{ id: "d", name: "Dan", transponder: "9999", brand: "" },
|
||||
{ id: "e", name: "anders larsson", transponder: "1004", brand: "" },
|
||||
{ id: "g", name: "", transponder: "1001", brand: "", guestEventId: "e1" },
|
||||
];
|
||||
|
||||
test("House of RC plan: only matched drivers, pre-ticked only where our field is empty or just the transponder number", () => {
|
||||
const plan = planHouseOfRcDriverUpdates(drivers(), members);
|
||||
assert.deepEqual(plan.map((row) => row.driverId), ["a", "b", "c"], "unknown transponders and sponsor guests are left out");
|
||||
const [a, b, c] = plan;
|
||||
assert.deepEqual(plan.map((row) => row.driverId), ["a", "b", "c", "e"], "unknown transponders and sponsor guests are left out");
|
||||
const [a, b, c, e] = plan;
|
||||
assert.deepEqual([a.nameDiffers, a.nameDefault, a.brandDiffers, a.brandDefault], [true, true, true, true]);
|
||||
assert.deepEqual([b.nameDiffers, b.nameDefault, b.brandDiffers, b.brandDefault], [true, false, true, false], "an existing name or brand is never pre-ticked");
|
||||
assert.deepEqual([c.nameDiffers, c.brandDiffers], [false, false], "same name ignoring case and spaces; no brand from HoR");
|
||||
assert.deepEqual([c.nameDiffers, c.nameDefault, c.brandDiffers], [true, true, false], "only case/spacing differs: offered and pre-ticked; no brand from HoR");
|
||||
assert.deepEqual([e.nameDefault, e.brandDefault, e.member.brand], [true, true, "Xray XB4 2025"], "no brand object: the model name is the make");
|
||||
});
|
||||
|
||||
test("House of RC apply: writes only the ticked fields and links drivers whose name matches", () => {
|
||||
@@ -32,5 +35,30 @@ test("House of RC apply: writes only the ticked fields and links drivers whose n
|
||||
assert.deepEqual([byId.b.name, byId.b.brand, byId.b.houseOfRcId], ["Bosse", "Xray", undefined], "name kept, so not linked (could be a borrowed transponder)");
|
||||
assert.deepEqual([byId.c.name, byId.c.houseOfRcId], ["cecilia carlsson", "71"], "same person: linked without renaming");
|
||||
assert.equal(byId.g.name, "", "sponsor guests untouched");
|
||||
assert.equal(changed, 3);
|
||||
assert.equal(changed, 4, "c and e are linked by name even without ticks");
|
||||
});
|
||||
|
||||
test("House of RC entries: linked, same name, other class and new drivers", async () => {
|
||||
const { planHouseOfRcEntries, applyHouseOfRcEntries } = await import("../src/houseofrc_logic.js");
|
||||
const register = [
|
||||
{ id: "d1", name: "Anna Andersson", classId: "2wd", transponder: "111", houseOfRcId: "5" },
|
||||
{ id: "d2", name: "Bo Berg", classId: "2wd", transponder: "222" },
|
||||
{ id: "d3", name: "Cid Ceder", classId: "4wd", transponder: "333", houseOfRcId: "7", profileId: "p3", club: "ÖRC" },
|
||||
];
|
||||
const entries = [
|
||||
{ houseOfRcId: 5, name: "Anna A.", club: "ÖRC", car: "Xray XB2" },
|
||||
{ houseOfRcId: 6, name: "bo berg", club: "", car: "" },
|
||||
{ houseOfRcId: 7, name: "Cid Ceder", club: "ÖRC", car: "Associated B7" },
|
||||
{ houseOfRcId: 8, name: "Dan Ny", club: "Sundsvall RC", car: "Mugen MSB1" },
|
||||
];
|
||||
const plan = planHouseOfRcEntries(entries, register, "2wd");
|
||||
assert.deepEqual(plan.map((row) => row.status), ["linked", "name", "copy", "new"]);
|
||||
let n = 0;
|
||||
const ids = applyHouseOfRcEntries(register, plan, { classId: "2wd", selected: new Set([0, 1, 2, 3]), makeDriver: (fields) => ({ id: `new${++n}`, ...fields }) });
|
||||
assert.deepEqual(ids, ["d1", "d2", "new1", "new2"], "existing drivers reused, the others created, in entry order");
|
||||
assert.equal(register.find((d) => d.id === "d2").houseOfRcId, "6", "same name gets linked");
|
||||
const cid = register.find((d) => d.id === "new1");
|
||||
assert.deepEqual([cid.classId, cid.transponder, cid.profileId, cid.brand], ["2wd", "333", "p3", "Associated B7"], "other class: same person, profile and transponder, car from the entry");
|
||||
const dan = register.find((d) => d.id === "new2");
|
||||
assert.deepEqual([dan.name, dan.transponder, dan.club, dan.houseOfRcId], ["Dan Ny", "", "Sundsvall RC", "8"]);
|
||||
});
|
||||
@@ -733,7 +733,19 @@ 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";
|
||||
res.writeHead(ok ? 200 : 401, { "Content-Type": "application/json" });
|
||||
const missing = ok && req.url.startsWith("/v1/events/") && req.url !== "/v1/events/2251";
|
||||
res.writeHead(!ok ? 401 : missing ? 404 : 200, { "Content-Type": "application/json" });
|
||||
if (missing) return res.end(JSON.stringify({ message: "Not found." }));
|
||||
if (ok && req.url.startsWith("/v1/events?")) {
|
||||
return res.end(JSON.stringify({ data: [
|
||||
{ id: 2251, name: "Deltävling 2 Sundsvall", type: "race", status: "live", start: "2026-12-05T07:00:00Z", city: "Sundsvall", country: "SE", web_url: "https://houseofrc.com/events/2251" },
|
||||
{ id: 3001, name: "Winter Cup", type: "race", status: null, start: "2026-12-06T07:00:00Z", city: "Oslo", country: "NO" },
|
||||
], links: { next: null }, meta: {} }));
|
||||
}
|
||||
if (ok && req.url === "/v1/events/2251") return res.end(JSON.stringify({ data: { id: 2251, name: "Deltävling 2 Sundsvall", type: "race", start: "2026-12-05T07:00:00Z", city: "Sundsvall", country: "SE", web_url: "https://houseofrc.com/events/2251" } }));
|
||||
if (ok && req.url === "/results?event_id=2251") {
|
||||
return res.end(JSON.stringify([{ user_id: 68, name: "Anna Andersson", firstname: "Anna", lastname: "Andersson", number: 7, points: 0, club: "Östersunds RC", country: "Sweden", product: "X12", brand1: "XRAY" }]));
|
||||
}
|
||||
if (ok && req.url.startsWith("/timing/users")) {
|
||||
// Newest owner first; an unknown number is simply missing.
|
||||
return res.end(JSON.stringify([
|
||||
@@ -772,6 +784,14 @@ test("House of RC: the key is stored server-side only, never returned, and the t
|
||||
const lookup = await (await post("/api/houseofrc/transponders", { transponders: ["1234567", "7654321", "1234567", "bad value"] })).json();
|
||||
assert.equal(seen.at(-1).url, "/timing/users?transponders=1234567%2C7654321", "deduplicated, invalid numbers dropped");
|
||||
assert.deepEqual(lookup.members, { 1234567: { id: 5, name: "Bo Berg", model: "B7", brand: "Associated" } }, "the newest owner wins");
|
||||
const events = await (await post("/api/houseofrc/events", { from: "2026-12-01T00:00:00Z", to: "2026-12-31T23:59:59Z", country: "se" })).json();
|
||||
assert.deepEqual(events.events.map((event) => event.id), [2251], "filtered to the chosen country");
|
||||
assert.match(seen.at(-1).url, /^\/v1\/events\?start_from=2026-12-01.*sort=start&per_page=100&page=1$/);
|
||||
const entries = await (await post("/api/houseofrc/entries", { eventId: "https://houseofrc.com/events/2251" })).json();
|
||||
assert.equal(entries.event.name, "Deltävling 2 Sundsvall");
|
||||
assert.deepEqual(entries.entries, [{ houseOfRcId: 68, name: "Anna Andersson", number: 7, club: "Östersunds RC", country: "Sweden", car: "XRAY X12", brand: "XRAY", points: 0 }], "a pasted link works; car = make + model");
|
||||
assert.equal((await post("/api/houseofrc/entries", { eventId: "nonsense" })).status, 400);
|
||||
assert.equal((await (await post("/api/houseofrc/entries", { eventId: "999" })).json()).error, "event_not_found");
|
||||
|
||||
const keyFile = join(dataDir, "houseofrc.json");
|
||||
assert.equal(statSync(keyFile).mode & 0o777, 0o600, "only the server user can read the key file");
|
||||
|
||||
Reference in new issue
Block a user