408 lines
27 KiB
JavaScript
408 lines
27 KiB
JavaScript
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 = `<p class="error">${escapeHtml(t("houseofrc.err_unreachable"))}</p>`;
|
||
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 = `
|
||
<p><strong id="houseOfRcState">${escapeHtml(stateText)}</strong></p>
|
||
<p class="hint">${escapeHtml(t("houseofrc.hint"))}</p>
|
||
<form id="houseOfRcKeyForm" class="form-grid cols-2">
|
||
<label>${escapeHtml(t("houseofrc.key"))}
|
||
<input type="password" name="apiKey" id="houseOfRcKey" autocomplete="off" spellcheck="false" placeholder="hrc_…" ${status.source === "env" ? "disabled" : ""} />
|
||
</label>
|
||
<div class="actions">
|
||
<button class="btn btn-primary" type="submit" ${status.source === "env" ? "disabled" : ""}>${escapeHtml(t("houseofrc.save"))}</button>
|
||
<button class="btn" type="button" id="houseOfRcTest" ${status.configured ? "" : "disabled"}>${escapeHtml(t("houseofrc.test"))}</button>
|
||
${status.source === "file" ? `<button class="btn btn-danger" type="button" id="houseOfRcRemove">${escapeHtml(t("houseofrc.remove"))}</button>` : ""}
|
||
</div>
|
||
</form>
|
||
<p class="hint" id="houseOfRcResult" role="status" hidden></p>`;
|
||
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 = `<div class="modal-card hor-import"><div class="panel-header"><h3>🏠 ${escapeHtml(t("houseofrc.import_title"))}</h3><button class="btn" type="button" data-hor-close>${escapeHtml(t("common.cancel"))}</button></div><div class="panel-body" data-hor-body><p class="hint">${escapeHtml(t("houseofrc.import_loading"))}</p></div></div>`;
|
||
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 = `<p>${escapeHtml(t("houseofrc.import_no_transponders"))}</p>`;
|
||
return;
|
||
}
|
||
const result = await lookupHouseOfRcTransponders(transponders);
|
||
if (!overlay.isConnected) return;
|
||
if (!result.ok) {
|
||
body.innerHTML = `<p class="error">${escapeHtml(describeHouseOfRcError(t, result.code, result.body))}</p>`;
|
||
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 = `<p>${escapeHtml(summary)}</p><p>${escapeHtml(t(found ? "houseofrc.import_nothing" : "houseofrc.import_none_found"))}</p>`;
|
||
return;
|
||
}
|
||
const cell = (row, field, current, incoming) => (row[`${field}Differs`]
|
||
? `<label class="hor-choice"><input type="checkbox" data-hor-field="${field}" data-hor-driver="${escapeHtml(row.driverId)}" ${row[`${field}Default`] ? "checked" : ""} /> <span><s>${escapeHtml(current || "–")}</s> → <strong>${escapeHtml(incoming)}</strong></span></label>`
|
||
: `<span class="hint">${escapeHtml(current || incoming || "–")}</span>`);
|
||
body.innerHTML = `
|
||
<p>${escapeHtml(summary)}</p>
|
||
<p class="hint">${escapeHtml(t("houseofrc.import_hint"))}</p>
|
||
<div class="table-wrap"><table class="hor-import-table">
|
||
<thead><tr><th>${escapeHtml(t("table.transponder"))}</th><th>${escapeHtml(t("table.name"))}</th><th>${escapeHtml(t("table.brand"))}</th><th>${escapeHtml(t("houseofrc.import_model"))}</th></tr></thead>
|
||
<tbody>${changes.map((row) => `<tr>
|
||
<td>${escapeHtml(row.transponder)}</td>
|
||
<td>${cell(row, "name", row.currentName, row.member.name)}</td>
|
||
<td>${cell(row, "brand", row.currentBrand, row.member.brand)}</td>
|
||
<td>${escapeHtml(row.member.model || "–")}</td>
|
||
</tr>`).join("")}</tbody>
|
||
</table></div>
|
||
<div class="actions mt-16">
|
||
<button class="btn btn-primary" type="button" data-hor-apply>${escapeHtml(t("houseofrc.import_apply"))}</button>
|
||
<button class="btn" type="button" data-hor-close>${escapeHtml(t("common.cancel"))}</button>
|
||
</div>`;
|
||
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 = `<div class="modal-card ${wide ? "hor-import" : ""}"><div class="panel-header"><h3>🏠 ${escapeHtml(title)}</h3><button class="btn" type="button" data-hor-close>✕</button></div><div class="panel-body" data-hor-body></div></div>`;
|
||
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 `<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 () => {
|
||
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 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>
|
||
<input name="link" placeholder="${escapeHtml(t("houseofrc.event_link_placeholder"))}" />
|
||
<button class="btn btn-primary" type="submit">${escapeHtml(t("houseofrc.event_open"))}</button>
|
||
</form>
|
||
<div class="mt-16" data-hor-list><p class="hint">${escapeHtml(t("houseofrc.event_loading"))}</p></div>`;
|
||
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
|
||
? `<div class="hor-event-list">${events.map((event) => `
|
||
<button type="button" class="hor-event" data-hor-event="${escapeHtml(String(event.id))}">
|
||
<strong>${escapeHtml(event.name)}</strong>
|
||
<small>${escapeHtml([fmtDate(event.start), event.city].filter(Boolean).join(" · "))}</small>
|
||
</button>`).join("")}</div>`
|
||
: `<p class="hint">${escapeHtml(t("houseofrc.event_none"))}</p>`;
|
||
list.querySelectorAll("[data-hor-event]").forEach((button) => button.addEventListener("click", () => showEntries(button.dataset.horEvent)));
|
||
};
|
||
|
||
const showEntries = async (eventRef) => {
|
||
body.innerHTML = `<p class="hint">${escapeHtml(t("houseofrc.entries_loading"))}</p>`;
|
||
const { status: code, body: data } = await postJson("/api/houseofrc/entries", { eventId: eventRef });
|
||
if (!overlay.isConnected) return;
|
||
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 = 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 = `
|
||
<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>
|
||
<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>
|
||
${matchedHow ? `<small><span class="pill ${matchedHow === "guess" ? "pill-warn" : "pill-green"}" data-hor-class-how="${matchedHow}">${escapeHtml(t(`houseofrc.class_${matchedHow}`))}</span></small>` : ""}
|
||
</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>
|
||
<td><input type="checkbox" data-hor-entry="${index}" checked /></td>
|
||
<td>${escapeHtml(row.entry.name)}${row.entry.number != null ? ` <small>#${escapeHtml(String(row.entry.number))}</small>` : ""}</td>
|
||
<td>${escapeHtml(row.entry.club || "–")}</td>
|
||
<td>${row.brandDiffers
|
||
? `<label class="hor-choice" title="${escapeHtml(t("houseofrc.entries_brand_hint"))}"><input type="checkbox" data-hor-brand="${index}" ${row.brandDefault ? "checked" : ""} /> <span><s>${escapeHtml(row.currentBrand || "–")}</s> → <strong>${escapeHtml(row.entry.car)}</strong></span></label>`
|
||
: escapeHtml(row.entry.car || row.currentBrand || "–")}</td>
|
||
<td>${escapeHtml(row.transponder || "–")}</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 class="mt-16">${escapeHtml(t("houseofrc.entries_empty"))}</p>${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 = `<p class="hint">${escapeHtml(t("houseofrc.entries_loading"))}</p>`;
|
||
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 = `<p class="error">${escapeHtml(describeHouseOfRcError(t, code, data))}</p>`;
|
||
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 = `<p><strong>${escapeHtml(where)}</strong></p><p>✅ ${escapeHtml(t("houseofrc.refresh_nothing"))}</p>`;
|
||
return;
|
||
}
|
||
body.innerHTML = `
|
||
<p><strong>${escapeHtml(where)}</strong></p>
|
||
${diff.added.length ? `<h4>➕ ${escapeHtml(t("houseofrc.refresh_added", { count: diff.added.length }))}</h4>
|
||
<div class="table-wrap"><table class="hor-import-table"><tbody>${diff.added.map((row, index) => `<tr>
|
||
<td><input type="checkbox" data-hor-add="${index}" checked /></td>
|
||
<td>${escapeHtml(row.entry.name)}</td><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(t(`houseofrc.entry_${row.status}`))}</span></td>
|
||
</tr>`).join("")}</tbody></table></div>` : ""}
|
||
${diff.withdrawn.length ? `<h4 class="mt-16">➖ ${escapeHtml(t("houseofrc.refresh_withdrawn", { count: diff.withdrawn.length }))}</h4>
|
||
<div class="table-wrap"><table class="hor-import-table"><tbody>${diff.withdrawn.map((driver) => `<tr>
|
||
<td><input type="checkbox" data-hor-remove="${escapeHtml(driver.id)}" checked /></td>
|
||
<td>${escapeHtml(driver.name)}</td><td>${escapeHtml(driver.transponder || "–")}</td>
|
||
</tr>`).join("")}</tbody></table></div>` : ""}
|
||
<p class="hint">${escapeHtml(t("houseofrc.refresh_note"))}</p>
|
||
<div class="actions mt-16">
|
||
<button class="btn btn-primary" type="button" data-hor-apply>${escapeHtml(t("houseofrc.refresh_apply"))}</button>
|
||
<button class="btn" type="button" data-hor-close>${escapeHtml(t("common.cancel"))}</button>
|
||
</div>`;
|
||
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 = `
|
||
<p><strong>${escapeHtml(where)}</strong>${event.houseOfRc.resultsSentAt ? ` <span class="hint">· ${escapeHtml(t("houseofrc.results_last", { time: new Date(event.houseOfRc.resultsSentAt).toLocaleString() }))}</span>` : ""}</p>
|
||
<div class="hor-choice">
|
||
<label><input type="radio" name="horResultsMode" value="heats" ${final ? "" : "checked"} /> ${escapeHtml(t("houseofrc.results_mode_heats"))}</label>
|
||
<label><input type="radio" name="horResultsMode" value="final" ${final ? "checked" : ""} ${hasFinals ? "" : "disabled"} /> ${escapeHtml(t("houseofrc.results_mode_final"))}</label>
|
||
</div>
|
||
<p class="hint">${escapeHtml(t(final ? "houseofrc.results_final_hint" : "houseofrc.results_heats_hint"))}</p>
|
||
<div class="table-wrap"><table class="hor-import-table">
|
||
<thead><tr><th>${escapeHtml(t("houseofrc.results_col_driver"))}</th><th>${escapeHtml(t("houseofrc.results_col_qual"))}</th><th>${escapeHtml(t("houseofrc.results_col_final"))}</th><th>${escapeHtml(t("houseofrc.results_col_heats"))}</th><th>${escapeHtml(t("houseofrc.results_col_best"))}</th></tr></thead>
|
||
<tbody>${rows.map((row) => `<tr data-hor-result-row>
|
||
<td>${escapeHtml(row.name)}</td>
|
||
<td>${row.qualification === 1 ? "TQ" : escapeHtml(String(row.qualification ?? "–"))}</td>
|
||
<td>${row.ranking ? escapeHtml(`${row.ranking} (${row.main})`) : "–"}${row.lapsTime ? ` <span class="hint">${escapeHtml(row.lapsTime)}</span>` : ""}</td>
|
||
<td>${row.heats}</td><td>${escapeHtml(row.bestLap || "–")}</td>
|
||
</tr>`).join("")}</tbody></table></div>
|
||
${missing.length ? `<p class="hint">⚠️ ${escapeHtml(t("houseofrc.results_missing", { names: missing.join(", ") }))}</p>` : ""}
|
||
<p data-hor-result-status></p>
|
||
<div class="actions mt-16">
|
||
<button class="btn btn-primary" type="button" data-hor-send ${entries.length ? "" : "disabled"}>📤 ${escapeHtml(t("houseofrc.results_send", { count: entries.length }))}</button>
|
||
<button class="btn" type="button" data-hor-close>${escapeHtml(t("houseofrc.results_close"))}</button>
|
||
</div>`;
|
||
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 };
|
||
}
|