import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass, rememberHouseOfRcClass, diffHouseOfRcEntries, applyHouseOfRcEntryChanges, buildHouseOfRcResults } 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). async function postJson(path, body) { try { const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) }); return { status: response.status, body: await response.json().catch(() => ({})) }; } catch { return { status: 0, body: { error: "unreachable" } }; } } export function describeHouseOfRcError(t, code, body = {}) { if (code === 401 && body.error === "auth_required") return t("auth.login_required"); const key = { not_configured: "houseofrc.err_not_configured", unauthorized: "houseofrc.err_unauthorized", rate_limited: "houseofrc.err_rate_limited", timeout: "houseofrc.err_unreachable", unreachable: "houseofrc.err_unreachable", invalid_key: "houseofrc.err_invalid_key", not_your_event: "houseofrc.err_not_your_event", event_not_found: "houseofrc.err_event_not_found", invalid_event: "houseofrc.err_event_not_found", }[body.error]; if (body.error === "rejected") return t("houseofrc.err_rejected", { message: [body.message, ...Object.values(body.errors || {}).flat()].filter(Boolean).join(" ") || "422" }); return key ? t(key, { seconds: body.retryAfter || 60 }) : t("houseofrc.err_other", { status: body.status || code }); } export async function mountHouseOfRcSettings(container, { t, escapeHtml }) { if (!container) return; const status = await fetch("/api/houseofrc/status").then((res) => res.json()).catch(() => null); if (!status) { container.innerHTML = `
${escapeHtml(t("houseofrc.err_unreachable"))}
`; return; } const remount = () => mountHouseOfRcSettings(container, { t, escapeHtml }); const stateText = !status.configured ? t("houseofrc.state_none") : status.source === "env" ? t("houseofrc.state_env", { hint: status.keyHint }) : t("houseofrc.state_saved", { hint: status.keyHint }); container.innerHTML = `${escapeHtml(stateText)}
${escapeHtml(t("houseofrc.hint"))}
`; const result = container.querySelector("#houseOfRcResult"); const show = (text, isError = false) => { result.textContent = text; result.className = isError ? "error" : "hint"; result.hidden = false; }; container.querySelector("#houseOfRcKeyForm").addEventListener("submit", async (event) => { event.preventDefault(); const apiKey = String(new FormData(event.currentTarget).get("apiKey") || "").trim(); if (!apiKey) return; const { status: code, body } = await postJson("/api/houseofrc/key", { apiKey }); if (code !== 200) return show(describeHouseOfRcError(t, code, body), true); await remount(); container.querySelector("#houseOfRcTest")?.click(); }); container.querySelector("#houseOfRcTest")?.addEventListener("click", async () => { show(t("houseofrc.testing")); const { status: code, body } = await postJson("/api/houseofrc/test"); 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 () => { if (!window.confirm(t("houseofrc.remove_confirm"))) return; const { status: code, body } = await postJson("/api/houseofrc/key", { apiKey: "" }); if (code !== 200) return show(describeHouseOfRcError(t, code, body), true); remount(); }); } // Ask the server (which holds the key) who owns these transponders on House of RC. export async function lookupHouseOfRcTransponders(transponders) { const { status: code, body } = await postJson("/api/houseofrc/transponders", { transponders }); return code === 200 && body.ok ? { ok: true, members: body.members || {}, asked: body.asked || 0 } : { ok: false, code, body }; } // Drivers โ "Fetch from House of RC": one lookup for every transponder, then a list of what // differs. Only fields that are empty on our side are pre-ticked; nothing changes until Apply. export async function openHouseOfRcDriverImport({ state, t, escapeHtml, saveState, renderView }) { document.getElementById("houseOfRcImportOverlay")?.remove(); const overlay = document.createElement("div"); overlay.className = "modal-overlay"; overlay.id = "houseOfRcImportOverlay"; overlay.innerHTML = `${escapeHtml(t("houseofrc.import_loading"))}
${escapeHtml(t("houseofrc.import_no_transponders"))}
`; return; } const result = await lookupHouseOfRcTransponders(transponders); if (!overlay.isConnected) return; if (!result.ok) { body.innerHTML = `${escapeHtml(describeHouseOfRcError(t, result.code, result.body))}
`; return; } const plan = planHouseOfRcDriverUpdates(state.drivers, result.members); const found = Object.keys(result.members).length; const summary = t("houseofrc.import_summary", { found, asked: result.asked }); const changes = plan.filter((row) => row.nameDiffers || row.brandDiffers || !row.linked); if (!changes.length) { body.innerHTML = `${escapeHtml(summary)}
${escapeHtml(t(found ? "houseofrc.import_nothing" : "houseofrc.import_none_found"))}
`; return; } const cell = (row, field, current, incoming) => (row[`${field}Differs`] ? `` : `${escapeHtml(current || incoming || "โ")}`); body.innerHTML = `${escapeHtml(summary)}
${escapeHtml(t("houseofrc.import_hint"))}
| ${escapeHtml(t("table.transponder"))} | ${escapeHtml(t("table.name"))} | ${escapeHtml(t("table.brand"))} | ${escapeHtml(t("houseofrc.import_model"))} |
|---|---|---|---|
| ${escapeHtml(row.transponder)} | ${cell(row, "name", row.currentName, row.member.name)} | ${cell(row, "brand", row.currentBrand, row.member.brand)} | ${escapeHtml(row.member.model || "โ")} |
${escapeHtml(own ? t(own) : describeHouseOfRcError(t, code, data))}
`; }; let filters = { from: day(-60), to: day(180), country: "SE" }; const showEvents = async () => { body.innerHTML = `${escapeHtml(t("houseofrc.event_loading"))}
${escapeHtml(t("houseofrc.event_none"))}
`; list.querySelectorAll("[data-hor-event]").forEach((button) => button.addEventListener("click", () => showEntries(button.dataset.horEvent))); }; const showEntries = async (eventRef) => { body.innerHTML = `${escapeHtml(t("houseofrc.entries_loading"))}
`; const { status: code, body: data } = await postJson("/api/houseofrc/entries", { eventId: eventRef }); if (!overlay.isConnected) return; const back = ``; const bindBack = () => body.querySelector("[data-hor-back]")?.addEventListener("click", () => showEvents()); if (code !== 200 || !data.ok) { body.innerHTML = error(code, data) + back; bindBack(); return; } 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; let matchedHow = ""; const render = () => { const horClass = classes.find((item) => item.id === horClassId); if (ourClassId === null) { const match = matchHouseOfRcClass(state.classes, horClass?.name); ourClassId = match.id || NEW_CLASS; matchedHow = match.how; } 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 = `${escapeHtml(event.name)} ยท ${escapeHtml([fmtDate(event.start), event.city].filter(Boolean).join(" ยท "))}${event.url ? ` ยท House of RC โ` : ""}
| ${escapeHtml(t("table.name"))} | ${escapeHtml(t("drivers.club"))} | ${escapeHtml(t("houseofrc.import_model"))} | ${escapeHtml(t("table.transponder"))} | ||
|---|---|---|---|---|---|
| ${escapeHtml(row.entry.name)}${row.entry.number != null ? ` #${escapeHtml(String(row.entry.number))}` : ""} | ${escapeHtml(row.entry.club || "โ")} | ${row.brandDiffers ? `` : escapeHtml(row.entry.car || row.currentBrand || "โ")} | ${escapeHtml(row.transponder || "โ")} | ${escapeHtml(t(`houseofrc.entry_${row.status}`))} |
${escapeHtml(t("houseofrc.entries_hint"))}
${escapeHtml(t("houseofrc.entries_empty"))}
${back}`}`; bindBack(); 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; matchedHow = ""; 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 brands = new Set([...body.querySelectorAll("[data-hor-brand]:checked")].map((box) => Number(box.dataset.horBrand))); rememberHouseOfRcClass(state.classes, classId, horClass?.name || ""); const { driverIds, entryIds } = applyHouseOfRcEntries(state.drivers, plan, { classId, selected, makeDriver, brands }); saveState(); close(); onImported({ event, horClass, classId, driverIds, entryIds }); }); }; render(); }; showEvents(); } // Manage โ "Fetch entry changes": late entries to add, withdrawn drivers to take out (ticked). // The caller applies the new participant list the same way as ticking participants by hand, // so only heats that haven't run change. export async function openHouseOfRcEntryRefresh({ event, state, t, escapeHtml, makeDriver, onApply }) { const { overlay, body, close } = openHorModal({ id: "houseOfRcRefreshOverlay", title: t("houseofrc.refresh_title"), escapeHtml }); body.innerHTML = `${escapeHtml(t("houseofrc.entries_loading"))}
`; const { status: code, body: data } = await postJson("/api/houseofrc/entries", { eventId: String(event.houseOfRc.eventId) }); if (!overlay.isConnected) return; if (code !== 200 || !data.ok) { body.innerHTML = `${escapeHtml(describeHouseOfRcError(t, code, data))}
`; return; } const diff = diffHouseOfRcEntries(event, data.entries, state.drivers); const where = [event.houseOfRc.name, event.houseOfRc.className].filter(Boolean).join(" โ "); if (!diff.added.length && !diff.withdrawn.length) { body.innerHTML = `${escapeHtml(where)}
โ ${escapeHtml(t("houseofrc.refresh_nothing"))}
`; return; } body.innerHTML = `${escapeHtml(where)}
${diff.added.length ? `| ${escapeHtml(row.entry.name)} | ${escapeHtml(row.entry.club || "โ")} | ${escapeHtml(row.entry.car || "โ")} | ${escapeHtml(row.transponder || "โ")} | ${escapeHtml(t(`houseofrc.entry_${row.status}`))} |
| ${escapeHtml(driver.name)} | ${escapeHtml(driver.transponder || "โ")} |
${escapeHtml(t("houseofrc.refresh_note"))}
${escapeHtml(where)}${event.houseOfRc.resultsSentAt ? ` ยท ${escapeHtml(t("houseofrc.results_last", { time: new Date(event.houseOfRc.resultsSentAt).toLocaleString() }))}` : ""}
${escapeHtml(t(final ? "houseofrc.results_final_hint" : "houseofrc.results_heats_hint"))}
| ${escapeHtml(t("houseofrc.results_col_driver"))} | ${escapeHtml(t("houseofrc.results_col_qual"))} | ${escapeHtml(t("houseofrc.results_col_final"))} | ${escapeHtml(t("houseofrc.results_col_heats"))} | ${escapeHtml(t("houseofrc.results_col_best"))} |
|---|---|---|---|---|
| ${escapeHtml(row.name)} | ${row.qualification === 1 ? "TQ" : escapeHtml(String(row.qualification ?? "โ"))} | ${row.ranking ? escapeHtml(`${row.ranking} (${row.main})`) : "โ"}${row.lapsTime ? ` ${escapeHtml(row.lapsTime)}` : ""} | ${row.heats} | ${escapeHtml(row.bestLap || "โ")} |
โ ๏ธ ${escapeHtml(t("houseofrc.results_missing", { names: missing.join(", ") }))}
` : ""}