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

+16 -12
View File
@@ -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",
+3 -3
View File
@@ -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();
+42 -34
View File
@@ -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 || "";
}
+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.
// 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) => `<p class="error">${escapeHtml(describeHouseOfRcError(t, code, data))}</p>`;
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 `<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 = `
<form class="form-grid cols-4" data-hor-filter>
<label>${escapeHtml(t("houseofrc.event_from"))}<input type="date" name="from" value="${escapeHtml(filters.from)}" /></label>
<label>${escapeHtml(t("houseofrc.event_to"))}<input type="date" name="to" value="${escapeHtml(filters.to)}" /></label>
<label>${escapeHtml(t("houseofrc.event_country"))}<input name="country" maxlength="2" value="${escapeHtml(filters.country)}" placeholder="SE" /></label>
<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>
</form>
<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) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
showEvents({ from: String(form.get("from") || day(0)), to: String(form.get("to") || day(60)), country: String(form.get("country") || "").trim().toUpperCase() });
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) => {
event.preventDefault();
@@ -197,9 +204,11 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, make
if (link) showEntries(link);
});
const list = body.querySelector("[data-hor-list]");
const { status: code, body: data } = await postJson("/api/houseofrc/events", { from: `${filters.from}T00:00:00Z`, to: `${filters.to}T23:59:59Z`, country: filters.country });
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 (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");
list.innerHTML = events.length
? `<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 bindBack = () => body.querySelector("[data-hor-back]")?.addEventListener("click", () => showEvents());
if (code !== 200 || !data.ok) {
body.innerHTML = (code === 502 && data.status === 404 ? `<p class="error">${escapeHtml(t("houseofrc.entries_not_found"))}</p>` : error(code, data)) + back;
body.innerHTML = error(code, data) + back;
bindBack();
return;
}
const { event, entries } = data;
let classId = state.classes[0]?.id || "";
const { event, classes, entries } = data;
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 plan = planHouseOfRcEntries(entries, state.drivers, classId);
const statusText = (row) => t(`houseofrc.entry_${row.status}`);
const horClass = classes.find((item) => item.id === horClassId);
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 = `
<p><strong>${escapeHtml(event.name)}</strong> · ${escapeHtml([fmtDate(event.start), event.city].filter(Boolean).join(" · "))}${event.url ? ` · <a href="${escapeHtml(event.url)}" target="_blank" rel="noopener">House of RC ↗</a>` : ""}</p>
${entries.length ? `
<label>${escapeHtml(t("houseofrc.entries_class"))}
<select data-hor-class>${state.classes.map((item) => `<option value="${escapeHtml(item.id)}" ${item.id === classId ? "selected" : ""}>${escapeHtml(item.name)}</option>`).join("")}</select>
<small>${escapeHtml(t("houseofrc.entries_class_hint"))}</small>
<div class="form-grid cols-2">
<label>${escapeHtml(t("houseofrc.entries_hor_class"))}
<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>
</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">
<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>
@@ -242,21 +263,27 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, saveState, make
<td>${escapeHtml(row.entry.club || "–")}</td>
<td>${escapeHtml(row.entry.car || "–")}</td>
<td>${escapeHtml(row.transponder || "–")}</td>
<td><span class="pill ${row.status === "new" ? "pill-warn" : "pill-green"}">${escapeHtml(statusText(row))}</span></td>
<td><span class="pill ${row.status === "new" ? "pill-warn" : "pill-green"}">${escapeHtml(t(`houseofrc.entry_${row.status}`))}</span></td>
</tr>`).join("")}</tbody>
</table></div>
<p class="hint">${escapeHtml(t("houseofrc.entries_hint"))}</p>
<div class="actions mt-16">${back}<button class="btn btn-primary" type="button" data-hor-apply>${escapeHtml(t("houseofrc.entries_apply"))}</button></div>`
: `<p>${escapeHtml(t("houseofrc.entries_empty"))}</p>${back}`}`;
: `<p class="mt-16">${escapeHtml(t("houseofrc.entries_empty"))}</p>${back}`}`;
bindBack();
body.querySelector("[data-hor-class]")?.addEventListener("change", (change) => { classId = change.target.value; render(); });
body.querySelector("[data-hor-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-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 driverIds = applyHouseOfRcEntries(state.drivers, plan, { classId, selected, makeDriver });
const { driverIds, entryIds } = applyHouseOfRcEntries(state.drivers, plan, { classId, selected, makeDriver });
saveState();
close();
onImported({ event, classId, driverIds });
onImported({ event, horClass, classId, driverIds, entryIds });
});
};
render();