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"))}

${status.source === "file" ? `` : ""}
`; 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 = ``; document.body.append(overlay); const close = () => { overlay.remove(); document.removeEventListener("keydown", onKey); }; const onKey = (event) => { if (event.key === "Escape") close(); }; document.addEventListener("keydown", onKey); overlay.addEventListener("click", (event) => { if (event.target === overlay || event.target.closest("[data-hor-close]")) close(); }); const body = overlay.querySelector("[data-hor-body]"); const transponders = state.drivers.filter((driver) => !driver.guestEventId && driver.transponder).map((driver) => driver.transponder); if (!transponders.length) { body.innerHTML = `

${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"))}

${changes.map((row) => ``).join("")}
${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 || "โ€“")}
`; body.querySelector("[data-hor-apply]").addEventListener("click", () => { const choices = {}; body.querySelectorAll("[data-hor-field]").forEach((box) => { choices[box.dataset.horDriver] = { ...choices[box.dataset.horDriver], [box.dataset.horField]: box.checked }; }); const changed = applyHouseOfRcDriverUpdates(state.drivers, result.members, choices); close(); if (changed) { saveState(); renderView(); } }); } function openHorModal({ id, title, escapeHtml, wide = true }) { document.getElementById(id)?.remove(); const overlay = document.createElement("div"); overlay.className = "modal-overlay"; overlay.id = id; overlay.innerHTML = ``; document.body.append(overlay); const onKey = (event) => { if (event.key === "Escape") close(); }; const close = () => { overlay.remove(); document.removeEventListener("keydown", onKey); }; document.addEventListener("keydown", onKey); overlay.addEventListener("click", (event) => { if (event.target === overlay || event.target.closest("[data-hor-close]")) close(); }); return { overlay, body: overlay.querySelector("[data-hor-body]"), close }; } // Race wizard โ†’ "Fetch from House of RC": pick 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", 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 () => { body.innerHTML = `

${escapeHtml(t("houseofrc.event_loading"))}

`; body.querySelector("[data-hor-filter]").addEventListener("submit", (event) => { event.preventDefault(); const form = new FormData(event.currentTarget); 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(); const link = String(new FormData(event.currentTarget).get("link") || "").trim(); if (link) showEntries(link); }); const list = body.querySelector("[data-hor-list]"); const { status: code, body: data } = await postJson("/api/houseofrc/events", { from: filters.from, 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 ? `
${events.map((event) => ` `).join("")}
` : `

${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 โ†—` : ""}

${classEntries.length ? `
${plan.map((row, index) => ``).join("")}
${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"))}

${back}
` : `

${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(t("houseofrc.refresh_added", { count: diff.added.length }))}

${diff.added.map((row, index) => ``).join("")}
${escapeHtml(row.entry.name)}${escapeHtml(row.entry.club || "โ€“")}${escapeHtml(row.entry.car || "โ€“")}${escapeHtml(row.transponder || "โ€“")} ${escapeHtml(t(`houseofrc.entry_${row.status}`))}
` : ""} ${diff.withdrawn.length ? `

โž– ${escapeHtml(t("houseofrc.refresh_withdrawn", { count: diff.withdrawn.length }))}

${diff.withdrawn.map((driver) => ``).join("")}
${escapeHtml(driver.name)}${escapeHtml(driver.transponder || "โ€“")}
` : ""}

${escapeHtml(t("houseofrc.refresh_note"))}

`; body.querySelector("[data-hor-apply]").addEventListener("click", () => { const addIndexes = new Set([...body.querySelectorAll("[data-hor-add]:checked")].map((box) => Number(box.dataset.horAdd))); const removeIds = new Set([...body.querySelectorAll("[data-hor-remove]:checked")].map((box) => box.dataset.horRemove)); const selectedIds = applyHouseOfRcEntryChanges(event, state.drivers, diff, { addIndexes, removeIds, makeDriver }); close(); onApply(selectedIds); }); } // Manage โ†’ "Send results to House of RC": a preview of what goes to each entry, then one // all-or-nothing write. "Heats" leaves out the final placings, so nobody is notified yet // and it can be sent after every heat; "Final results" adds them. export function openHouseOfRcResultsPost({ event, overview, state, t, escapeHtml, saveState }) { const { body, close } = openHorModal({ id: "houseOfRcResultsOverlay", title: t("houseofrc.results_title"), escapeHtml }); const hasFinals = Boolean(overview?.phases?.find((phase) => phase.type === "final")?.standings?.length); let final = hasFinals && Boolean(overview?.finished); const render = () => { const { entries, rows, missing } = buildHouseOfRcResults(event, overview, { final, drivers: state.drivers }); const where = [event.houseOfRc.name, event.houseOfRc.className].filter(Boolean).join(" โ€“ "); body.innerHTML = `

${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"))}

${rows.map((row) => ``).join("")}
${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 || "โ€“")}
${missing.length ? `

โš ๏ธ ${escapeHtml(t("houseofrc.results_missing", { names: missing.join(", ") }))}

` : ""}

`; body.querySelectorAll("[name=horResultsMode]").forEach((radio) => radio.addEventListener("change", () => { final = radio.value === "final"; render(); })); body.querySelector("[data-hor-send]").addEventListener("click", async (click) => { const button = click.currentTarget; const statusLine = body.querySelector("[data-hor-result-status]"); button.disabled = true; statusLine.textContent = t("houseofrc.results_sending"); const { status: code, body: data } = await postJson("/api/houseofrc/results", { eventId: event.houseOfRc.eventId, entries }); if (code !== 200 || !data.ok) { statusLine.className = "error"; statusLine.textContent = describeHouseOfRcError(t, code, data); button.disabled = false; return; } event.houseOfRc.resultsSentAt = new Date().toISOString(); event.houseOfRc.resultsSentFinal = final; saveState(); statusLine.className = ""; statusLine.textContent = `โœ… ${t("houseofrc.results_sent", { count: data.updated })}`; }); }; render(); return { close }; }