diff --git a/CHANGELOG.md b/CHANGELOG.md index 8208118..cbb5c69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.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 - **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. diff --git a/README.md b/README.md index 420499e..c07692e 100644 --- a/README.md +++ b/README.md @@ -322,7 +322,7 @@ Erik Eriksson;654321;4WD;Associated;; RaceCore is meant for a trusted race network: - **Admin PIN** (Settings â System & backup, off by default) protects every change through the API. The login lasts 30 days and is throttled against guessing. - **Race Controller Master:** one computer at a time runs the race (the decoder, start, pause, resume, stop, false start, resetting a heat and the autopilot, also from the speaker panel). Judging corrections and the other calls work from any computer. The computer running the server (page opened on `localhost`) becomes master on its own and shows a green line "đ You are the Race Controller Master" with **Release master**. Phones and other computers follow the race live (updated every second), show "You are following the race âŠ" and become master only when someone presses the button; that computer then remembers the role. They can also prepare drivers and races. Whoever works as race controller presses **Take over as master**, and the previous master lets go of the decoder within seconds. With the admin PIN on, taking over needs a login. Name the computer under Settings â System, e.g. "Speaker booth". Overlays and OBS are always view-only. -- **House of RC:** under Settings â System â đ House of RC you save the club's API key once (stored on the server only, never shown again) and press **Test connection**. Drivers â **đ Fetch from House of RC** fills in names and brands from the transponders (only what you tick), and a known transponder fills in a new driver. 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_ALLOWED_ORIGINS`** is for a UI deliberately served from another address. - **Don't expose port 8081 to the internet.** Reads are not PIN protected. Publish only the public overlay and mobile profile paths through a reverse proxy or VPN. diff --git a/README.sv.md b/README.sv.md index 0d320a4..6a77ebe 100644 --- a/README.sv.md +++ b/README.sv.md @@ -335,7 +335,7 @@ Erik Eriksson;654321;4WD;Associated;; RaceCore Ă€r tĂ€nkt för ett betrott racenĂ€tverk: - **Admin-PIN** (InstĂ€llningar â System & backup, av som standard) skyddar alla Ă€ndringar via API:t. Inloggningen gĂ€ller i 30 dagar och Ă€r skyddad mot gissning. - **Race Controller Master:** bara en dator Ă„t gĂ„ngen kör racet (decodern, start, paus, fortsĂ€tt, stopp, tjuvstart, nollstĂ€ll heat och autopiloten, Ă€ven frĂ„n speakerpanelen). Domarvyns korrigeringar och övriga utrop fungerar frĂ„n alla datorer. Datorn som kör servern (sidan öppnad pĂ„ `localhost`) blir master av sig sjĂ€lv och visar en grön rad "đ Du Ă€r Race Controller Master" med **SlĂ€pp master**. Mobiler och andra datorer följer racet live (uppdateras varje sekund), visar "Du följer racet âŠ" och blir master bara nĂ€r nĂ„gon trycker pĂ„ knappen; den datorn minns sedan rollen. De kan ocksĂ„ förbereda förare och race. Den som jobbar som race controller trycker **Ta över som master**, och den förra mastern slĂ€pper decodern inom nĂ„gra sekunder. Med admin-PIN krĂ€vs inloggning för att ta över. Ge datorn ett namn under InstĂ€llningar â System, t.ex. "SpeakerbĂ„set". Overlays och OBS Ă€r alltid bara visning. -- **House of RC:** under InstĂ€llningar â System â đ House of RC sparar du klubbens API-nyckel en gĂ„ng (bara pĂ„ servern, visas aldrig igen) och trycker **Testa anslutning**. Förare â **đ HĂ€mta frĂ„n House of RC** fyller i namn och mĂ€rke utifrĂ„n transpondrarna (bara det du bockar i), och en kĂ€nd transponder fyller i en ny förare. 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_ALLOWED_ORIGINS`** anvĂ€nds för ett grĂ€nssnitt som medvetet körs frĂ„n en annan adress. - **Exponera inte port 8081 mot internet.** LĂ€sningar skyddas inte av PIN. Publicera bara sökvĂ€garna för publik overlay och mobilprofil via reverse proxy eller VPN. diff --git a/ROADMAP.md b/ROADMAP.md index 0cda06c..2bf6ee2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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] 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. +- [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: -- [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. +Next: +- [ ] **Results back:** `POST /v1/timing/events/{id}/entries` with `{ entries: [{ id, ranking, qualification, points, tq, laps_time, data }] }`, all or nothing, up to 2000 entries. `data.result` is shown on House of RC (`main`, `main_position`, `bumped_from`, `race`, `best_lap`, `average_lap`, `points`, `heats[]`). The race already keeps each driver's entry id (`event.houseOfRc.entryIds`). +- [ ] **Semi-live (Conny's idea):** post after every heat, with that heat's results in `data`; House of RC would add a view showing only the latest heat. +- [ ] 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? - [ ] A test event to post against. diff --git a/package-lock.json b/package-lock.json index 5ba543f..e0c54a7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.80.0", + "version": "1.81.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.80.0", + "version": "1.81.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index 4928bb9..dea8848 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.80.0", + "version": "1.81.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/server.js b/server.js index 4269373..2a1e34e 100644 --- a/server.js +++ b/server.js @@ -493,7 +493,7 @@ app.post("/api/houseofrc/events", async (req, res) => { 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); + const result = await houseOfRc.getEventEntries(req.body?.eventId); res.status(result.ok ? 200 : result.status === 400 ? 400 : 502).json(result); }); diff --git a/server/houseofrc.js b/server/houseofrc.js index 51d42fa..5fe32a2 100644 --- a/server/houseofrc.js +++ b/server/houseofrc.js @@ -31,6 +31,7 @@ function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fe } function setKey(value) { + account = null; const key = String(value || "").trim(); if (!key) { 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() { const result = await get("/v1/me"); if (!result.ok) return result; 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 @@ -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 || "", }); - // 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. + // Events in a date range: the club's own (hosted or organized) when the key is an + // organization's, otherwise every public event filtered by country. At most 5 pages of 100. 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 = []; 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; 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) }; + return { ok: true, status: 200, organizationId, events: events.filter((event) => event.type !== "series") }; } - // 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. + // One event with its racing classes and entries (/v1/timing/events/{id}/entries, needs the + // hosting or organizing club's key). The answer also holds the drivers' email, phone, + // emergency contact and age: those are dropped here and never reach the browser. + const NOT_RACING = new Set(["entrycancelled", "waitinglist"]); + async function getEventEntries(eventId) { 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 }; + const result = await get(`/v1/timing/events/${id}/entries`); + if (!result.ok) { + if (result.status === 403) return { ...result, error: "not_your_event" }; + if (result.status === 404) return { ...result, error: "event_not_found" }; + return result; + } + const data = result.data?.data || {}; + const users = new Map((data.users || []).map((user) => [user.id, user])); + const classes = (data.classes || []).map((item) => ({ id: item.id, name: String(item.name || "").trim(), order: item.order ?? null })); + const entries = (data.entries || []).filter((entry) => !NOT_RACING.has(entry.status)).map((entry) => { + const user = users.get(entry.user_id) || {}; + const brand = String(entry.brands?.[0]?.name || "").trim(); + const model = String(entry.car?.name || "").trim(); + return { + 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 }; diff --git a/src/app.js b/src/app.js index eb91f43..5ffbe0c 100644 --- a/src/app.js +++ b/src/app.js @@ -2203,21 +2203,23 @@ const TRANSLATIONS = { "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_link_placeholder": "âŠeller klistra in lĂ€nk/ID, t.ex. https://houseofrc.com/events/2080", "houseofrc.event_open": "Ăppna", "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.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_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_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.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", @@ -4409,21 +4411,23 @@ const TRANSLATIONS = { "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_link_placeholder": "âŠor paste a link/ID, e.g. https://houseofrc.com/events/2080", "houseofrc.event_open": "Open", "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.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_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_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.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", diff --git a/src/event_workspace_controller.js b/src/event_workspace_controller.js index 2901ca4..8a9f9bc 100644 --- a/src/event_workspace_controller.js +++ b/src/event_workspace_controller.js @@ -250,14 +250,14 @@ export function renderEventWorkspaceView(context) { document.getElementById("raceWizardHouseOfRc")?.addEventListener("click", () => openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState, makeDriver: (fields) => normalizeDriver({ id: uid("driver"), ...fields }), - onImported: ({ event, classId, driverIds }) => { + onImported: ({ event, horClass, classId, driverIds, entryIds }) => { const draft = getRaceWizardDraft(); 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, classId, 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); renderView(); diff --git a/src/houseofrc_logic.js b/src/houseofrc_logic.js index c3c780a..6c0d5dc 100644 --- a/src/houseofrc_logic.js +++ b/src/houseofrc_logic.js @@ -49,55 +49,63 @@ export function applyHouseOfRcDriverUpdates(drivers = [], members = {}, choices 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) +// Entries of one House of RC class against our register, for one of our classes: +// linked - already a driver in that class (same House of RC member, transponder or name) // 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 = "") { 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 sameTransponder = (entry) => (driver) => Boolean(driver.transponder) && (entry.transponders || []).includes(driver.transponder); 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) => { - 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: "" }; + const entryTransponder = (entry.transponders || [])[0] || ""; + const existing = find(inClass, entry); + if (existing) return { entry, status: "linked", driverId: existing.id, transponder: existing.transponder || entryTransponder }; + const source = find(club, entry); + if (source) return { entry, status: "copy", sourceId: source.id, transponder: entryTransponder || source.transponder }; + return { entry, status: "new", transponder: entryTransponder }; }); } -// 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. export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDriver }) { - const ids = []; + const driverIds = []; + const entryIds = {}; 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; + let driver = row.driverId ? drivers.find((item) => item.id === row.driverId) : null; + if (driver) { + if (memberId) driver.houseOfRcId = memberId; + if (!driver.transponder && row.transponder) driver.transponder = row.transponder; + } 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; - 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); + driverIds.push(driver.id); + if (entry.entryId != null) entryIds[driver.id] = entry.entryId; }); - 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 || ""; } diff --git a/src/houseofrc_view.js b/src/houseofrc_view.js index 5361460..69dde5c 100644 --- a/src/houseofrc_view.js +++ b/src/houseofrc_view.js @@ -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. // 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 () => { show(t("houseofrc.testing")); 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); }); 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 }; } -// 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 }) { +// Race wizard â "Fetch from House of RC": pick one of the club's events, one of its classes and +// which of our classes it is; the entries fill the wizard (name, date, class, participants with +// 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 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) => `
${escapeHtml(describeHouseOfRcError(t, code, data))}
`; + const fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short", year: "numeric" }) : ""); + 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 `${escapeHtml(own ? t(own) : describeHouseOfRcError(t, code, data))}
`; + }; + 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 = `