feat(houseofrc): fetch club events, classes and entries with transponders via the timing API (1.81.0)

This commit is contained in:
larssand committed 2026-11-08 15:53:57 +01:00
1 parent 9c1f5713e6
commit b0f2b92c04
15 files changed
+247 -149

No files matched your search

+6
View File
@@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet. No changes recorded yet.
## 1.81.0
- **House of RC with the club's key:** RaceCore now uses House of RC's timing API. With the key of the club running the event (an organization key), **Test connection** shows the club ("Connected as Jämtlands MK (organization 233)"), and the race wizard's **🏠 Fetch from House of RC** lists the club's own events, past and coming.
- Picking an event shows its **classes from House of RC** with the number of entries; choose one, and which of our classes it is (matched by name, or **➕ New class** with the House of RC name). The entries come **with their transponders**: drivers are matched on their House of RC member, then transponder, then name; new drivers get the entry's transponder. The race keeps the event, the class and each driver's entry, ready for sending results back. Cancelled and waiting-list entries are left out.
- The drivers' email, phone, emergency contact and age, which House of RC sends to the organizer, are dropped on the server and never stored or shown.
## 1.80.0 ## 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. - **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.
+1 -1
View File
@@ -322,7 +322,7 @@ Erik Eriksson;654321;4WD;Associated;;
RaceCore is meant for a trusted race network: 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. - **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. - **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. 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). - **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. 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_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. - **`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. - **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
View File
@@ -335,7 +335,7 @@ Erik Eriksson;654321;4WD;Associated;;
RaceCore är tänkt för ett betrott racenätverk: 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. - **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. - **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. 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). - **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. 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_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. - **`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. - **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.
+5 -5
View File
@@ -1007,12 +1007,12 @@ 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] 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] 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`. - [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. - [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.
Still open with Conny: Next:
- [x] Test the key with `GET /v1/me`. - [ ] **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`).
- [ ] 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. - [ ] **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.
- [ ] The transponder per entry (or the eventclass ID per row in `/results`), so new drivers don't need it typed in. - [ ] 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? - [ ] 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. - [ ] A test event to post against.
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "rc-racecore", "name": "rc-racecore",
"version": "1.80.0", "version": "1.81.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "rc-racecore", "name": "rc-racecore",
"version": "1.80.0", "version": "1.81.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"better-sqlite3": "^12.11.1", "better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "rc-racecore", "name": "rc-racecore",
"version": "1.80.0", "version": "1.81.0",
"private": true, "private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": { "engines": {
+1 -1
View File
@@ -493,7 +493,7 @@ app.post("/api/houseofrc/events", async (req, res) => {
res.status(result.ok ? 200 : 502).json(result); res.status(result.ok ? 200 : 502).json(result);
}); });
app.post("/api/houseofrc/entries", async (req, res) => { app.post("/api/houseofrc/entries", async (req, res) => {
const result = await houseOfRc.getEventEntries(req.body?.eventId, req.body?.eventclassId); const result = await houseOfRc.getEventEntries(req.body?.eventId);
res.status(result.ok ? 200 : result.status === 400 ? 400 : 502).json(result); res.status(result.ok ? 200 : result.status === 400 ? 400 : 502).json(result);
}); });
+50 -25
View File
@@ -31,6 +31,7 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
} }
function setKey(value) { function setKey(value) {
account = null;
const key = String(value || "").trim(); const key = String(value || "").trim();
if (!key) { if (!key) {
fs.rmSync(configPath, { force: true }); fs.rmSync(configPath, { force: true });
@@ -66,11 +67,19 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
} }
} }
// A member's key answers with `user`, a club's (timing) key with `organization`. The
// organization is what lists the club's events and opens their entries.
let account = null;
async function testConnection() { async function testConnection() {
const result = await get("/v1/me"); const result = await get("/v1/me");
if (!result.ok) return result; if (!result.ok) return result;
const body = result.data?.data || {}; const body = result.data?.data || {};
return { ok: true, status: result.status, user: body.user || null, rateLimit: body.rate_limit ?? null }; account = { user: body.user || null, organization: body.organization || null };
return { ok: true, status: result.status, ...account, rateLimit: body.rate_limit ?? null };
}
async function getOrganizationId() {
if (!account) await testConnection();
return account?.organization?.id ?? null;
} }
// Members owning these transponders (/timing/users, max 200 per call). The newest owner of a // Members owning these transponders (/timing/users, max 200 per call). The newest owner of a
@@ -102,43 +111,59 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe
organizerId: event.organizer_id ?? null, seriesId: event.series_id ?? null, url: event.web_url || "", 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). // Events in a date range: the club's own (hosted or organized) when the key is an
// At most 5 pages of 100 to stay well inside the rate limit. // organization's, otherwise every public event filtered by country. At most 5 pages of 100.
async function listEvents({ from, to, country = "" } = {}) { async function listEvents({ from, to, country = "" } = {}) {
const organizationId = await getOrganizationId();
const query = organizationId
? { parent_id: organizationId, from, to }
: { start_from: from, start_to: to, country: String(country || "").toUpperCase() || undefined };
const events = []; const events = [];
for (let page = 1; page <= 5; page += 1) { 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 }); const result = await get("/v1/events", { ...query, sort: "start", per_page: 100, page });
if (!result.ok) return result; if (!result.ok) return result;
const rows = Array.isArray(result.data?.data) ? result.data.data : []; const rows = Array.isArray(result.data?.data) ? result.data.data : [];
events.push(...rows.map(pickEvent)); events.push(...rows.map(pickEvent));
if (!result.data?.links?.next || rows.length < 100) break; if (!result.data?.links?.next || rows.length < 100) break;
} }
const wanted = String(country || "").toUpperCase(); return { ok: true, status: 200, organizationId, events: events.filter((event) => event.type !== "series") };
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 // One event with its racing classes and entries (/v1/timing/events/{id}/entries, needs the
// entries (0 points); cancelled and waiting-list entries are already left out. // hosting or organizing club's key). The answer also holds the drivers' email, phone,
async function getEventEntries(eventId, eventclassId) { // emergency contact and age: those are dropped here and never reach the browser.
// An id, or a pasted link like https://houseofrc.com/events/2253. const NOT_RACING = new Set(["entrycancelled", "waitinglist"]);
async function getEventEntries(eventId) {
const text = String(eventId || "").trim(); const text = String(eventId || "").trim();
const id = Number(text.match(/events\/(\d+)/)?.[1] || text.match(/^\d+$/)?.[0]); 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" }; if (!Number.isInteger(id) || id < 1) return { ok: false, status: 400, error: "invalid_event" };
const event = await get(`/v1/events/${id}`); const result = await get(`/v1/timing/events/${id}/entries`);
if (!event.ok) return event.status === 404 ? { ...event, error: "event_not_found" } : event; if (!result.ok) {
const results = await get("/results", { event_id: id, eventclass_id: eventclassId || undefined }); if (result.status === 403) return { ...result, error: "not_your_event" };
if (!results.ok) return results; if (result.status === 404) return { ...result, error: "event_not_found" };
const entries = (Array.isArray(results.data) ? results.data : []).map((row) => ({ return result;
houseOfRcId: row.user_id ?? null, }
name: String(row.name || [row.firstname, row.lastname].filter(Boolean).join(" ")).trim(), const data = result.data?.data || {};
number: row.number ?? null, const users = new Map((data.users || []).map((user) => [user.id, user]));
club: String(row.club || "").trim(), const classes = (data.classes || []).map((item) => ({ id: item.id, name: String(item.name || "").trim(), order: item.order ?? null }));
country: String(row.country || "").trim(), const entries = (data.entries || []).filter((entry) => !NOT_RACING.has(entry.status)).map((entry) => {
car: [row.brand1 && !String(row.product || "").toLowerCase().startsWith(String(row.brand1).toLowerCase()) ? row.brand1 : "", row.product].filter(Boolean).join(" ").trim(), const user = users.get(entry.user_id) || {};
brand: String(row.brand1 || "").trim(), const brand = String(entry.brands?.[0]?.name || "").trim();
points: row.points ?? null, const model = String(entry.car?.name || "").trim();
})).filter((entry) => entry.name); return {
return { ok: true, status: 200, event: pickEvent(event.data?.data || {}), entries }; entryId: entry.id,
classId: entry.class_id,
houseOfRcId: entry.user_id,
name: String(user.name || [user.firstname, user.lastname].filter(Boolean).join(" ")).trim(),
country: user.represents_country || user.country || "",
number: entry.driver_number ?? null,
transponders: (entry.transponders || []).map((value) => String(value).trim()).filter(Boolean),
club: String(entry.club?.name || "").trim(),
car: brand && !model.toLowerCase().startsWith(brand.toLowerCase()) ? `${brand} ${model}`.trim() : model || brand,
status: entry.status || "",
};
}).filter((entry) => entry.name);
return { ok: true, status: 200, event: pickEvent(data.event || { id }), classes, entries };
} }
return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries }; return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries };
+16 -12
View File
@@ -2203,21 +2203,23 @@ const TRANSLATIONS = {
"houseofrc.event_to": "Till", "houseofrc.event_to": "Till",
"houseofrc.event_country": "Land", "houseofrc.event_country": "Land",
"houseofrc.event_search": "Sök", "houseofrc.event_search": "Sök",
"houseofrc.event_link_placeholder": "…eller klistra in länk/ID, t.ex. https://houseofrc.com/events/2251", "houseofrc.event_link_placeholder": "…eller klistra in länk/ID, t.ex. https://houseofrc.com/events/2080",
"houseofrc.event_open": "Öppna", "houseofrc.event_open": "Öppna",
"houseofrc.event_loading": "Hämtar tävlingar…", "houseofrc.event_loading": "Hämtar tävlingar…",
"houseofrc.event_none": "Inga tävlingar i den perioden.", "houseofrc.event_none": "Inga tävlingar för klubben i den perioden.",
"houseofrc.event_back": "Tävlingar", "houseofrc.event_back": "Tävlingar",
"houseofrc.entries_loading": "Hämtar anmälda förare…", "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_empty": "Inga anmälda förare än.",
"houseofrc.entries_class": "Klass hos oss", "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_hor_class": "Klass på House of RC",
"houseofrc.entries_new_class": "Ny klass: {name}",
"houseofrc.err_not_your_event": "Den här tävlingen tillhör en annan klubb. Anmälningarna kräver nyckeln för klubben som arrangerar den.",
"houseofrc.err_event_not_found": "Hittar ingen sådan tävling på House of RC.",
"houseofrc.connected_org": "✅ Ansluten som {name} (organisation {id}) · {limit} anrop/min",
"houseofrc.entries_all": "Alla", "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_hint": "Befintliga förare återanvänds och behåller sitt namn; nya förare skapas med transpondern från anmälan. Hämta igen för nästa klass.",
"houseofrc.entries_apply": "Fyll i Race-guiden", "houseofrc.entries_apply": "Fyll i Race-guiden",
"houseofrc.entry_linked": "Finns", "houseofrc.entry_linked": "Finns",
"houseofrc.entry_name": "Finns (samma namn)",
"houseofrc.entry_copy": "Finns i annan klass", "houseofrc.entry_copy": "Finns i annan klass",
"houseofrc.entry_new": "Ny förare", "houseofrc.entry_new": "Ny förare",
"houseofrc.title": "House of RC", "houseofrc.title": "House of RC",
@@ -4409,21 +4411,23 @@ const TRANSLATIONS = {
"houseofrc.event_to": "To", "houseofrc.event_to": "To",
"houseofrc.event_country": "Country", "houseofrc.event_country": "Country",
"houseofrc.event_search": "Search", "houseofrc.event_search": "Search",
"houseofrc.event_link_placeholder": "…or paste a link/ID, e.g. https://houseofrc.com/events/2251", "houseofrc.event_link_placeholder": "…or paste a link/ID, e.g. https://houseofrc.com/events/2080",
"houseofrc.event_open": "Open", "houseofrc.event_open": "Open",
"houseofrc.event_loading": "Fetching events…", "houseofrc.event_loading": "Fetching events…",
"houseofrc.event_none": "No events in that period.", "houseofrc.event_none": "No club events in that period.",
"houseofrc.event_back": "Events", "houseofrc.event_back": "Events",
"houseofrc.entries_loading": "Fetching entered drivers…", "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_empty": "No drivers entered yet.",
"houseofrc.entries_class": "Our class", "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_hor_class": "Class on House of RC",
"houseofrc.entries_new_class": "New class: {name}",
"houseofrc.err_not_your_event": "This event belongs to another club. Its entries need the key of the club running it.",
"houseofrc.err_event_not_found": "No such event on House of RC.",
"houseofrc.connected_org": "✅ Connected as {name} (organization {id}) · {limit} requests/min",
"houseofrc.entries_all": "All", "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_hint": "Existing drivers are reused and keep their name; new drivers get the transponder from the entry. Fetch again for the next class.",
"houseofrc.entries_apply": "Fill the race wizard", "houseofrc.entries_apply": "Fill the race wizard",
"houseofrc.entry_linked": "Exists", "houseofrc.entry_linked": "Exists",
"houseofrc.entry_name": "Exists (same name)",
"houseofrc.entry_copy": "Exists in another class", "houseofrc.entry_copy": "Exists in another class",
"houseofrc.entry_new": "New driver", "houseofrc.entry_new": "New driver",
"houseofrc.title": "House of RC", "houseofrc.title": "House of RC",
+3 -3
View File
@@ -250,14 +250,14 @@ export function renderEventWorkspaceView(context) {
document.getElementById("raceWizardHouseOfRc")?.addEventListener("click", () => openHouseOfRcEventImport({ document.getElementById("raceWizardHouseOfRc")?.addEventListener("click", () => openHouseOfRcEventImport({
state, t, escapeHtml, uid, saveState, state, t, escapeHtml, uid, saveState,
makeDriver: (fields) => normalizeDriver({ id: uid("driver"), ...fields }), makeDriver: (fields) => normalizeDriver({ id: uid("driver"), ...fields }),
onImported: ({ event, classId, driverIds }) => { onImported: ({ event, horClass, classId, driverIds, entryIds }) => {
const draft = getRaceWizardDraft(); const draft = getRaceWizardDraft();
Object.assign(draft, { Object.assign(draft, {
name: draft.name.trim() || event.name, name: [event.name, horClass?.name].filter(Boolean).join(" – "),
date: String(event.start || "").slice(0, 10) || draft.date, date: String(event.start || "").slice(0, 10) || draft.date,
classId, classId,
driverIds, driverIds,
houseOfRc: { eventId: event.id, name: event.name, url: event.url }, houseOfRc: { eventId: event.id, name: event.name, url: event.url, classId: horClass?.id ?? null, className: horClass?.name || "", entryIds },
}); });
setRaceWizardStep(2); setRaceWizardStep(2);
renderView(); renderView();
+42 -34
View File
@@ -49,55 +49,63 @@ export function applyHouseOfRcDriverUpdates(drivers = [], members = {}, choices
return changed; return changed;
} }
// Entries of a House of RC event against our register, for one of our classes: // Entries of one House of RC class against our register, for one of our classes:
// linked - already a driver in that class with this House of RC id // linked - already a driver in that class (same House of RC member, transponder or name)
// 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 // copy - the person exists in another class: a new driver in this class, same profile
// new - unknown: a new driver (transponder to fill in) // new - unknown: a new driver with the entry's transponder
export function planHouseOfRcEntries(entries = [], drivers = [], classId = "") { export function planHouseOfRcEntries(entries = [], drivers = [], classId = "") {
const club = drivers.filter((driver) => !driver.guestEventId); const club = drivers.filter((driver) => !driver.guestEventId);
const inClass = club.filter((driver) => driver.classId === classId);
const sameMember = (entry) => (driver) => entry.houseOfRcId != null && String(driver.houseOfRcId || "") === String(entry.houseOfRcId); const sameMember = (entry) => (driver) => entry.houseOfRcId != null && String(driver.houseOfRcId || "") === String(entry.houseOfRcId);
const sameTransponder = (entry) => (driver) => Boolean(driver.transponder) && (entry.transponders || []).includes(driver.transponder);
const sameName = (entry) => (driver) => sameText(driver.name, entry.name); const sameName = (entry) => (driver) => sameText(driver.name, entry.name);
const find = (list, entry) => list.find(sameMember(entry)) || list.find(sameTransponder(entry)) || list.find(sameName(entry));
return entries.map((entry) => { return entries.map((entry) => {
const inClass = club.filter((driver) => driver.classId === classId); const entryTransponder = (entry.transponders || [])[0] || "";
const linked = inClass.find(sameMember(entry)); const existing = find(inClass, entry);
if (linked) return { entry, status: "linked", driverId: linked.id, transponder: linked.transponder }; if (existing) return { entry, status: "linked", driverId: existing.id, transponder: existing.transponder || entryTransponder };
const named = inClass.find(sameName(entry)); const source = find(club, entry);
if (named) return { entry, status: "name", driverId: named.id, transponder: named.transponder }; if (source) return { entry, status: "copy", sourceId: source.id, transponder: entryTransponder || source.transponder };
const source = club.find(sameMember(entry)) || club.find(sameName(entry)); return { entry, status: "new", transponder: entryTransponder };
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. // Creates/links the ticked entries. Returns the driver ids in House of RC order and which
// House of RC entry each driver is ({ driverId: entryId }), for posting results back.
// makeDriver(fields) must return a normalized driver with a fresh id. // makeDriver(fields) must return a normalized driver with a fresh id.
export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDriver }) { export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDriver }) {
const ids = []; const driverIds = [];
const entryIds = {};
plan.forEach((row, index) => { plan.forEach((row, index) => {
if (!selected.has(index)) return; if (!selected.has(index)) return;
const { entry } = row; const { entry } = row;
const memberId = entry.houseOfRcId != null ? String(entry.houseOfRcId) : ""; const memberId = entry.houseOfRcId != null ? String(entry.houseOfRcId) : "";
if (row.driverId) { let driver = row.driverId ? drivers.find((item) => item.id === row.driverId) : null;
const driver = drivers.find((item) => item.id === row.driverId); if (driver) {
if (driver && memberId) driver.houseOfRcId = memberId; if (memberId) driver.houseOfRcId = memberId;
if (driver) ids.push(driver.id); if (!driver.transponder && row.transponder) driver.transponder = row.transponder;
return; } else {
const source = row.sourceId ? drivers.find((item) => item.id === row.sourceId) : null;
driver = makeDriver({
name: source?.name || entry.name,
classId,
transponder: row.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);
} }
const source = row.sourceId ? drivers.find((item) => item.id === row.sourceId) : null; driverIds.push(driver.id);
const driver = makeDriver({ if (entry.entryId != null) entryIds[driver.id] = entry.entryId;
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; return { driverIds, entryIds };
}
// Our class for a House of RC class: same name (ignoring case and spaces), else none.
export function matchHouseOfRcClass(classes = [], name = "") {
return classes.find((item) => sameText(item.name, name))?.id || "";
} }
+52 -25
View File
@@ -1,4 +1,4 @@
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries } from "./houseofrc_logic.js"; import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass } from "./houseofrc_logic.js";
// Settings → System → House of RC: save the club's API key on the server and test it. // 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). // The key is never read back; the server only tells whether one is set (and its last 4 chars).
@@ -67,7 +67,8 @@ export async function mountHouseOfRcSettings(container, { t, escapeHtml }) {
container.querySelector("#houseOfRcTest")?.addEventListener("click", async () => { container.querySelector("#houseOfRcTest")?.addEventListener("click", async () => {
show(t("houseofrc.testing")); show(t("houseofrc.testing"));
const { status: code, body } = await postJson("/api/houseofrc/test"); const { status: code, body } = await postJson("/api/houseofrc/test");
if (code === 200 && body.ok) show(t("houseofrc.connected", { name: body.user?.name || "?", id: body.user?.id ?? "?", limit: body.rateLimit ?? "?" })); if (code === 200 && body.ok && body.organization) show(t("houseofrc.connected_org", { name: body.organization.name, id: body.organization.id, limit: body.rateLimit ?? "?" }));
else if (code === 200 && body.ok) show(t("houseofrc.connected", { name: body.user?.name || "?", id: body.user?.id ?? "?", limit: body.rateLimit ?? "?" }));
else show(describeHouseOfRcError(t, code, body), true); else show(describeHouseOfRcError(t, code, body), true);
}); });
container.querySelector("#houseOfRcRemove")?.addEventListener("click", async () => { container.querySelector("#houseOfRcRemove")?.addEventListener("click", async () => {
@@ -165,20 +166,25 @@ function openHorModal({ id, title, escapeHtml, wide = true }) {
return { overlay, body: overlay.querySelector("[data-hor-body]"), 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 // Race wizard → "Fetch from House of RC": pick one of the club's events, one of its classes and
// entered drivers; fills the wizard (name, date, class, participants) and links the event. // which of our classes it is; the entries fill the wizard (name, date, class, participants with
export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, makeDriver, onImported }) { // transponders) and the race remembers the event and each driver's entry for the results.
export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState, makeDriver, onImported }) {
const { overlay, body, close } = openHorModal({ id: "houseOfRcEventOverlay", title: t("houseofrc.event_title"), escapeHtml }); 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 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 fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short", year: "numeric" }) : "");
const error = (code, data) => `<p class="error">${escapeHtml(describeHouseOfRcError(t, code, data))}</p>`; const error = (code, data) => {
const own = { not_your_event: "houseofrc.err_not_your_event", event_not_found: "houseofrc.err_event_not_found", invalid_event: "houseofrc.err_event_not_found" }[data?.error];
return `<p class="error">${escapeHtml(own ? t(own) : describeHouseOfRcError(t, code, data))}</p>`;
};
let filters = { from: day(-60), to: day(180), country: "SE" };
const showEvents = async (filters = { from: day(0), to: day(60), country: "SE" }) => { const showEvents = async () => {
body.innerHTML = ` body.innerHTML = `
<form class="form-grid cols-4" data-hor-filter> <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_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_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> <label data-hor-country hidden>${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> <div class="actions-inline align-end"><button class="btn" type="submit">${escapeHtml(t("houseofrc.event_search"))}</button></div>
</form> </form>
<form class="hor-link-row mt-16" data-hor-link> <form class="hor-link-row mt-16" data-hor-link>
@@ -189,7 +195,8 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, make
body.querySelector("[data-hor-filter]").addEventListener("submit", (event) => { body.querySelector("[data-hor-filter]").addEventListener("submit", (event) => {
event.preventDefault(); event.preventDefault();
const form = new FormData(event.currentTarget); 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() }); filters = { from: String(form.get("from") || day(-60)), to: String(form.get("to") || day(180)), country: String(form.get("country") || "").trim().toUpperCase() };
showEvents();
}); });
body.querySelector("[data-hor-link]").addEventListener("submit", (event) => { body.querySelector("[data-hor-link]").addEventListener("submit", (event) => {
event.preventDefault(); event.preventDefault();
@@ -197,9 +204,11 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, make
if (link) showEntries(link); if (link) showEntries(link);
}); });
const list = body.querySelector("[data-hor-list]"); 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 }); const { status: code, body: data } = await postJson("/api/houseofrc/events", { from: filters.from, to: filters.to, country: filters.country });
if (!overlay.isConnected || !list.isConnected) return; if (!overlay.isConnected || !list.isConnected) return;
if (code !== 200 || !data.ok) { list.innerHTML = error(code, data); return; } if (code !== 200 || !data.ok) { list.innerHTML = error(code, data); return; }
// A member's key sees all public events: then the country filter is offered.
body.querySelector("[data-hor-country]").hidden = Boolean(data.organizationId);
const events = (data.events || []).filter((event) => event.status !== "cancelled"); const events = (data.events || []).filter((event) => event.status !== "cancelled");
list.innerHTML = events.length list.innerHTML = events.length
? `<div class="hor-event-list">${events.map((event) => ` ? `<div class="hor-event-list">${events.map((event) => `
@@ -218,22 +227,34 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, make
const back = `<button class="btn" type="button" data-hor-back>← ${escapeHtml(t("houseofrc.event_back"))}</button>`; 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()); const bindBack = () => body.querySelector("[data-hor-back]")?.addEventListener("click", () => showEvents());
if (code !== 200 || !data.ok) { 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; body.innerHTML = error(code, data) + back;
bindBack(); bindBack();
return; return;
} }
const { event, entries } = data; const { event, classes, entries } = data;
let classId = state.classes[0]?.id || ""; const NEW_CLASS = "__new__";
let horClassId = classes.find((item) => entries.some((entry) => entry.classId === item.id))?.id ?? classes[0]?.id;
let ourClassId = null;
const render = () => { const render = () => {
const plan = planHouseOfRcEntries(entries, state.drivers, classId); const horClass = classes.find((item) => item.id === horClassId);
const statusText = (row) => t(`houseofrc.entry_${row.status}`); if (ourClassId === null) ourClassId = matchHouseOfRcClass(state.classes, horClass?.name) || NEW_CLASS;
const classEntries = entries.filter((entry) => entry.classId === horClassId);
const plan = ourClassId === NEW_CLASS ? planHouseOfRcEntries(classEntries, state.drivers, "") : planHouseOfRcEntries(classEntries, state.drivers, ourClassId);
const count = (id) => entries.filter((entry) => entry.classId === id).length;
body.innerHTML = ` 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> <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 ? ` <div class="form-grid cols-2">
<label>${escapeHtml(t("houseofrc.entries_class"))} <label>${escapeHtml(t("houseofrc.entries_hor_class"))}
<select data-hor-class>${state.classes.map((item) => `<option value="${escapeHtml(item.id)}" ${item.id === classId ? "selected" : ""}>${escapeHtml(item.name)}</option>`).join("")}</select> <select data-hor-source-class>${classes.map((item) => `<option value="${escapeHtml(String(item.id))}" ${item.id === horClassId ? "selected" : ""}>${escapeHtml(`${item.name} (${count(item.id)})`)}</option>`).join("")}</select>
<small>${escapeHtml(t("houseofrc.entries_class_hint"))}</small>
</label> </label>
<label>${escapeHtml(t("houseofrc.entries_class"))}
<select data-hor-class>
${state.classes.map((item) => `<option value="${escapeHtml(item.id)}" ${item.id === ourClassId ? "selected" : ""}>${escapeHtml(item.name)}</option>`).join("")}
<option value="${NEW_CLASS}" ${ourClassId === NEW_CLASS ? "selected" : ""}>➕ ${escapeHtml(t("houseofrc.entries_new_class", { name: horClass?.name || "" }))}</option>
</select>
</label>
</div>
${classEntries.length ? `
<div class="table-wrap mt-16"><table class="hor-import-table"> <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> <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> <tbody>${plan.map((row, index) => `<tr>
@@ -242,21 +263,27 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, make
<td>${escapeHtml(row.entry.club || "–")}</td> <td>${escapeHtml(row.entry.club || "–")}</td>
<td>${escapeHtml(row.entry.car || "–")}</td> <td>${escapeHtml(row.entry.car || "–")}</td>
<td>${escapeHtml(row.transponder || "–")}</td> <td>${escapeHtml(row.transponder || "–")}</td>
<td><span class="pill ${row.status === "new" ? "pill-warn" : "pill-green"}">${escapeHtml(statusText(row))}</span></td> <td><span class="pill ${row.status === "new" ? "pill-warn" : "pill-green"}">${escapeHtml(t(`houseofrc.entry_${row.status}`))}</span></td>
</tr>`).join("")}</tbody> </tr>`).join("")}</tbody>
</table></div> </table></div>
<p class="hint">${escapeHtml(t("houseofrc.entries_hint"))}</p> <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>` <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}`}`; : `<p class="mt-16">${escapeHtml(t("houseofrc.entries_empty"))}</p>${back}`}`;
bindBack(); bindBack();
body.querySelector("[data-hor-class]")?.addEventListener("change", (change) => { classId = change.target.value; render(); }); body.querySelector("[data-hor-source-class]").addEventListener("change", (change) => { horClassId = Number(change.target.value); ourClassId = null; render(); });
body.querySelector("[data-hor-class]").addEventListener("change", (change) => { ourClassId = 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-all]")?.addEventListener("change", (change) => body.querySelectorAll("[data-hor-entry]").forEach((box) => { box.checked = change.target.checked; }));
body.querySelector("[data-hor-apply]")?.addEventListener("click", () => { body.querySelector("[data-hor-apply]")?.addEventListener("click", () => {
let classId = ourClassId;
if (classId === NEW_CLASS) {
classId = uid("class");
state.classes.push({ id: classId, name: horClass?.name || event.name });
}
const selected = new Set([...body.querySelectorAll("[data-hor-entry]:checked")].map((box) => Number(box.dataset.horEntry))); 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 }); const { driverIds, entryIds } = applyHouseOfRcEntries(state.drivers, plan, { classId, selected, makeDriver });
saveState(); saveState();
close(); close();
onImported({ event, classId, driverIds }); onImported({ event, horClass, classId, driverIds, entryIds });
}); });
}; };
render(); render();
+17 -12
View File
@@ -74,12 +74,15 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w
const realFetch = window.fetch; const realFetch = window.fetch;
window.fetch = async (url, options) => { window.fetch = async (url, options) => {
const json = (data) => new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } }); 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/events")) return json({ ok: true, organizationId: 233, 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: [ 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" },
{ houseOfRcId: 901, name: "HoR Anna", number: 7, club: "Sundsvall RC", car: "XRAY X12" }, classes: [{ id: 555, name: "HoR 2wd" }, { id: 556, name: "HoR 4wd" }],
{ houseOfRcId: 902, name: "HoR Bo", number: null, club: "", car: "" }, entries: [
{ houseOfRcId: 903, name: "HoR Skipped", number: null, club: "", car: "" }, { entryId: 11, classId: 555, houseOfRcId: 901, name: "HoR Anna", number: 7, transponders: ["7710001"], club: "Sundsvall RC", car: "XRAY X12" },
] }); { entryId: 12, classId: 555, houseOfRcId: 902, name: "HoR Bo", number: null, transponders: [], club: "", car: "" },
{ 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: "" },
] });
return realFetch(url, options); return realFetch(url, options);
}; };
})()`); })()`);
@@ -88,7 +91,8 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w
await evaluate(`document.querySelector('[data-hor-event="2251"]').click()`); await evaluate(`document.querySelector('[data-hor-event="2251"]').click()`);
await waitFor(async () => evaluate(`Boolean(document.querySelector("[data-hor-apply]"))`), "the entries"); 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())`); const statuses = await evaluate(`[...document.querySelectorAll("#houseOfRcEventOverlay tbody .pill")].map((pill) => pill.textContent.trim())`);
assert.equal(statuses.length, 3); assert.equal(statuses.length, 3, "only the chosen House of RC class");
assert.equal(await evaluate(`document.querySelector("[data-hor-class]").value`), "__new__", "no class with that name: offered as a new class");
await evaluate(`(() => { await evaluate(`(() => {
const select = document.querySelector("[data-hor-class]"); const select = document.querySelector("[data-hor-class]");
select.value = "test_class"; select.dispatchEvent(new Event("change", { bubbles: true })); select.value = "test_class"; select.dispatchEvent(new Event("change", { bubbles: true }));
@@ -97,7 +101,7 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w
await waitFor(async () => (await savedState()).drivers.some((driver) => driver.name === "HoR Anna"), "new drivers saved"); await waitFor(async () => (await savedState()).drivers.some((driver) => driver.name === "HoR Anna"), "new drivers saved");
const drivers = (await savedState()).drivers; const drivers = (await savedState()).drivers;
const anna = drivers.find((driver) => driver.name === "HoR Anna"); 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.deepEqual([anna.classId, anna.club, anna.brand, anna.houseOfRcId, anna.transponder], ["test_class", "Sundsvall RC", "XRAY X12", "901", "7710001"], "the entry's transponder comes along");
assert.equal(drivers.some((driver) => driver.name === "HoR Skipped"), false, "an unticked entry is not created"); 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 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); const ids = drivers.filter((driver) => ["HoR Anna", "HoR Bo"].includes(driver.name)).map((driver) => driver.id);
@@ -105,15 +109,16 @@ export async function runHouseOfRcEventSmoke({ evaluate, navigate, savedState, w
await evaluate(`document.getElementById("raceWizardNext").click()`); await evaluate(`document.getElementById("raceWizardNext").click()`);
await evaluate(`document.getElementById("raceWizardNext").click()`); await evaluate(`document.getElementById("raceWizardNext").click()`);
await evaluate(`document.getElementById("raceWizardCreate").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"); await waitFor(async () => (await savedState()).events.some((event) => event.houseOfRc?.eventId === 2251), "the race is created");
const event = (await savedState()).events.find((item) => item.name === "HoR Deltävling 2"); const event = (await savedState()).events.find((item) => item.houseOfRc?.eventId === 2251);
assert.deepEqual([event.date, event.classId, event.houseOfRc?.eventId], ["2026-12-05", "test_class", 2251]); assert.deepEqual([event.date, event.classId, event.houseOfRc?.eventId, event.houseOfRc?.classId], ["2026-12-05", "test_class", 2251, 555]);
assert.deepEqual(Object.values(event.houseOfRc.entryIds).sort(), [11, 12], "each driver's House of RC entry, for the results");
assert.deepEqual([...event.raceConfig.driverIds].sort(), [...ids].sort()); 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"); 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 { } finally {
await evaluate(`document.getElementById("houseOfRcEventOverlay")?.remove()`).catch(() => {}); await evaluate(`document.getElementById("houseOfRcEventOverlay")?.remove()`).catch(() => {});
const current = await savedState(); const current = await savedState();
const eventIds = current.events.filter((event) => event.name === "HoR Deltävling 2").map((event) => event.id); const eventIds = current.events.filter((event) => event.houseOfRc?.eventId === 2251).map((event) => event.id);
Object.assign(current, { Object.assign(current, {
drivers: current.drivers.filter((driver) => !String(driver.name).startsWith("HoR ")), drivers: current.drivers.filter((driver) => !String(driver.name).startsWith("HoR ")),
events: current.events.filter((event) => !eventIds.includes(event.id)), events: current.events.filter((event) => !eventIds.includes(event.id)),
+20 -14
View File
@@ -38,27 +38,33 @@ test("House of RC apply: writes only the ticked fields and links drivers whose n
assert.equal(changed, 4, "c and e are linked by name even without ticks"); 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 () => { test("House of RC entries: matched on member, transponder or name; other class and new drivers", async () => {
const { planHouseOfRcEntries, applyHouseOfRcEntries } = await import("../src/houseofrc_logic.js"); const { planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass } = await import("../src/houseofrc_logic.js");
const register = [ const register = [
{ id: "d1", name: "Anna Andersson", classId: "2wd", transponder: "111", houseOfRcId: "5" }, { id: "d1", name: "Anna Andersson", classId: "2wd", transponder: "111", houseOfRcId: "5" },
{ id: "d2", name: "Bo Berg", classId: "2wd", transponder: "222" }, { id: "d2", name: "Robban", classId: "2wd", transponder: "222" },
{ id: "d3", name: "Cid Ceder", classId: "4wd", transponder: "333", houseOfRcId: "7", profileId: "p3", club: "ÖRC" }, { id: "d3", name: "bo berg", classId: "2wd", transponder: "" },
{ id: "d4", name: "Cid Ceder", classId: "4wd", transponder: "333", houseOfRcId: "7", profileId: "p3", club: "ÖRC" },
]; ];
const entries = [ const entries = [
{ houseOfRcId: 5, name: "Anna A.", club: "ÖRC", car: "Xray XB2" }, { entryId: 1, houseOfRcId: 5, name: "Anna A.", transponders: ["111"], club: "ÖRC", car: "Xray XB2" },
{ houseOfRcId: 6, name: "bo berg", club: "", car: "" }, { entryId: 2, houseOfRcId: 6, name: "Robert Nilsson", transponders: ["222"], club: "", car: "" },
{ houseOfRcId: 7, name: "Cid Ceder", club: "ÖRC", car: "Associated B7" }, { entryId: 3, houseOfRcId: 9, name: "Bo Berg", transponders: ["444"], club: "", car: "" },
{ houseOfRcId: 8, name: "Dan Ny", club: "Sundsvall RC", car: "Mugen MSB1" }, { entryId: 4, houseOfRcId: 7, name: "Cid Ceder", transponders: ["555"], club: "ÖRC", car: "Associated B7" },
{ entryId: 5, houseOfRcId: 8, name: "Dan Ny", transponders: ["666", "667"], club: "Sundsvall RC", car: "Mugen MSB1" },
]; ];
const plan = planHouseOfRcEntries(entries, register, "2wd"); const plan = planHouseOfRcEntries(entries, register, "2wd");
assert.deepEqual(plan.map((row) => row.status), ["linked", "name", "copy", "new"]); assert.deepEqual(plan.map((row) => `${row.status}:${row.driverId || row.sourceId || ""}`), ["linked:d1", "linked:d2", "linked:d3", "copy:d4", "new:"], "member, then transponder, then name");
let n = 0; let n = 0;
const ids = applyHouseOfRcEntries(register, plan, { classId: "2wd", selected: new Set([0, 1, 2, 3]), makeDriver: (fields) => ({ id: `new${++n}`, ...fields }) }); const { driverIds, entryIds } = applyHouseOfRcEntries(register, plan, { classId: "2wd", selected: new Set([0, 1, 2, 3, 4]), makeDriver: (fields) => ({ id: `new${++n}`, ...fields }) });
assert.deepEqual(ids, ["d1", "d2", "new1", "new2"], "existing drivers reused, the others created, in entry order"); assert.deepEqual(driverIds, ["d1", "d2", "d3", "new1", "new2"]);
assert.equal(register.find((d) => d.id === "d2").houseOfRcId, "6", "same name gets linked"); assert.deepEqual(entryIds, { d1: 1, d2: 2, d3: 3, new1: 4, new2: 5 }, "each driver remembers their House of RC entry");
assert.deepEqual([register[1].name, register[1].houseOfRcId], ["Robban", "6"], "our name is kept, the member is linked");
assert.equal(register[2].transponder, "444", "an empty transponder is filled from the entry");
const cid = register.find((d) => d.id === "new1"); 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"); assert.deepEqual([cid.classId, cid.transponder, cid.profileId, cid.brand], ["2wd", "555", "p3", "Associated B7"], "other class: same profile, this entry's transponder");
const dan = register.find((d) => d.id === "new2"); const dan = register.find((d) => d.id === "new2");
assert.deepEqual([dan.name, dan.transponder, dan.club, dan.houseOfRcId], ["Dan Ny", "", "Sundsvall RC", "8"]); assert.deepEqual([dan.name, dan.transponder, dan.club, dan.houseOfRcId], ["Dan Ny", "666", "Sundsvall RC", "8"]);
assert.equal(matchHouseOfRcClass([{ id: "c1", name: "Offroad 2WD foam" }], "offroad 2wd Foam"), "c1");
assert.equal(matchHouseOfRcClass([{ id: "c1", name: "Touring" }], "F1"), "");
}); });
+30 -13
View File
@@ -733,18 +733,29 @@ test("House of RC: the key is stored server-side only, never returned, and the t
const mock = createServer((req, res) => { const mock = createServer((req, res) => {
seen.push({ url: req.url, auth: req.headers.authorization }); seen.push({ url: req.url, auth: req.headers.authorization });
const ok = req.headers.authorization === "Bearer hrc_test_secret_key_1234"; const ok = req.headers.authorization === "Bearer hrc_test_secret_key_1234";
const missing = ok && req.url.startsWith("/v1/events/") && req.url !== "/v1/events/2251"; const forbidden = ok && req.url === "/v1/timing/events/3001/entries";
res.writeHead(!ok ? 401 : missing ? 404 : 200, { "Content-Type": "application/json" }); const missing = ok && req.url.startsWith("/v1/timing/events/") && !forbidden && req.url !== "/v1/timing/events/2251/entries";
if (missing) return res.end(JSON.stringify({ message: "Not found." })); res.writeHead(!ok ? 401 : forbidden ? 403 : missing ? 404 : 200, { "Content-Type": "application/json" });
if (missing || forbidden) return res.end(JSON.stringify({ message: forbidden ? "This API key may not access this event." : "Not found." }));
if (ok && req.url.startsWith("/v1/events?")) { if (ok && req.url.startsWith("/v1/events?")) {
return res.end(JSON.stringify({ data: [ 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: 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" }, { id: 3001, name: "Winter Cup", type: "race", status: null, start: "2026-12-06T07:00:00Z", city: "Oslo", country: "NO" },
], links: { next: null }, meta: {} })); ], 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 === "/v1/timing/events/2251/entries") {
if (ok && req.url === "/results?event_id=2251") { return res.end(JSON.stringify({ data: {
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" }])); event: { 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" },
classes: [{ id: 555, name: "Offroad 2wd", order: 1 }, { id: 556, name: "Camping" }],
entries: [
{ id: 98765, class_id: 555, user_id: 68, status: "confirmed", driver_number: 7, transponders: ["2939397"], club: { id: 233, name: "Jämtlands MK" }, car: { id: 1, name: "X12" }, brands: [{ id: 70, name: "XRAY" }, null, null, null, null] },
{ id: 98766, class_id: 555, user_id: 69, status: "entrycancelled", transponders: [], club: null, car: null, brands: [] },
],
users: [
{ id: 68, name: "Anna Andersson", country: "SE", email: "anna@example.com", phone: "070-1234567", emergency_contact: { name: "Bo", info: "070-7654321" }, age: 41 },
{ id: 69, name: "Cancelled Carl", country: "SE", email: "carl@example.com" },
],
} }));
} }
if (ok && req.url.startsWith("/timing/users")) { if (ok && req.url.startsWith("/timing/users")) {
// Newest owner first; an unknown number is simply missing. // Newest owner first; an unknown number is simply missing.
@@ -753,7 +764,7 @@ test("House of RC: the key is stored server-side only, never returned, and the t
{ id: 9, name: "Old Owner", transponder: "1234567" }, { id: 9, name: "Old Owner", transponder: "1234567" },
])); ]));
} }
res.end(JSON.stringify(ok ? { data: { user: { id: 68, name: "Test Club" }, rate_limit: 60 } } : { error: "unauthorized" })); res.end(JSON.stringify(ok ? { data: { organization: { id: 233, name: "Test Club" }, rate_limit: 60 } } : { error: "unauthorized" }));
}); });
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve)); await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
const dataDir = mkdtempSync(join(tmpdir(), "live-rc-test-hor-")); const dataDir = mkdtempSync(join(tmpdir(), "live-rc-test-hor-"));
@@ -779,19 +790,25 @@ test("House of RC: the key is stored server-side only, never returned, and the t
const saved = await (await post("/api/houseofrc/key", { apiKey: " hrc_test_secret_key_1234 " })).json(); const saved = await (await post("/api/houseofrc/key", { apiKey: " hrc_test_secret_key_1234 " })).json();
assert.deepEqual([saved.configured, saved.source, saved.keyHint], [true, "file", "…1234"]); assert.deepEqual([saved.configured, saved.source, saved.keyHint], [true, "file", "…1234"]);
const test = await (await post("/api/houseofrc/test", {})).json(); const test = await (await post("/api/houseofrc/test", {})).json();
assert.deepEqual([test.ok, test.user.name, test.rateLimit], [true, "Test Club", 60]); assert.deepEqual([test.ok, test.organization.name, test.rateLimit], [true, "Test Club", 60], "a club key answers with its organization");
assert.equal(seen.at(-1).url, "/v1/me"); assert.equal(seen.at(-1).url, "/v1/me");
const lookup = await (await post("/api/houseofrc/transponders", { transponders: ["1234567", "7654321", "1234567", "bad value"] })).json(); 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.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"); 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(); const events = await (await post("/api/houseofrc/events", { from: "2026-12-01", to: "2026-12-31" })).json();
assert.deepEqual(events.events.map((event) => event.id), [2251], "filtered to the chosen country"); assert.equal(events.organizationId, 233);
assert.match(seen.at(-1).url, /^\/v1\/events\?start_from=2026-12-01.*sort=start&per_page=100&page=1$/); assert.equal(seen.at(-1).url, "/v1/events?parent_id=233&from=2026-12-01&to=2026-12-31&sort=start&per_page=100&page=1", "a club key lists the club's own events");
const entries = await (await post("/api/houseofrc/entries", { eventId: "https://houseofrc.com/events/2251" })).json(); const response = await post("/api/houseofrc/entries", { eventId: "https://houseofrc.com/events/2251" });
const raw = await response.text();
assert.equal(seen.at(-1).url, "/v1/timing/events/2251/entries");
assert.ok(!/anna@|070-|emergency|"age"/.test(raw), "email, phone, emergency contact and age never reach the browser");
const entries = JSON.parse(raw);
assert.equal(entries.event.name, "Deltävling 2 Sundsvall"); 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.deepEqual(entries.classes.map((item) => item.name), ["Offroad 2wd", "Camping"]);
assert.deepEqual(entries.entries, [{ entryId: 98765, classId: 555, houseOfRcId: 68, name: "Anna Andersson", country: "SE", number: 7, transponders: ["2939397"], club: "Jämtlands MK", car: "XRAY X12", status: "confirmed" }], "cancelled entries left out; car = make + model");
assert.equal((await post("/api/houseofrc/entries", { eventId: "nonsense" })).status, 400); 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"); 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 keyFile = join(dataDir, "houseofrc.json"); const keyFile = join(dataDir, "houseofrc.json");
assert.equal(statSync(keyFile).mode & 0o777, 0o600, "only the server user can read the key file"); assert.equal(statSync(keyFile).mode & 0o777, 0o600, "only the server user can read the key file");