feat(houseofrc): re-fetch late entries and withdrawals, remember class mapping, offer brand differences (1.82.0)

This commit is contained in:
larssand committed 2026-11-08 19:04:27 +01:00
1 parent cdeb6b0402
commit f4a62b92d2
13 files changed
+240 -28

No files matched your search

+29 -2
View File
@@ -2212,12 +2212,24 @@ const TRANSLATIONS = {
"houseofrc.entries_empty": "Inga anmälda förare än.",
"houseofrc.entries_class": "Klass hos oss",
"houseofrc.entries_hor_class": "Klass på House of RC",
"houseofrc.refresh_button": "Hämta ändringar från House of RC",
"houseofrc.refresh_hint": "Nya anmälningar och avanmälningar sedan racet skapades ({name})",
"houseofrc.refresh_title": "Ändrade anmälningar",
"houseofrc.refresh_nothing": "Inga ändringar – deltagarna stämmer med House of RC.",
"houseofrc.refresh_added": "Nya anmälningar ({count})",
"houseofrc.refresh_withdrawn": "Avanmälda eller på reservlistan ({count})",
"houseofrc.refresh_note": "Bara heat som inte har körts ändras, precis som när du bockar i deltagare för hand. Förare du lagt till själv berörs inte.",
"houseofrc.refresh_apply": "Uppdatera deltagare",
"houseofrc.class_remembered": "Som förra gången",
"houseofrc.class_exact": "Samma namn",
"houseofrc.class_guess": "Gissad – kontrollera",
"houseofrc.entries_brand_hint": "Bilen i anmälan skiljer sig från märket hos oss. Bocka i för att ta anmälans.",
"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 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_hint": "Befintliga förare återanvänds och behåller namn och märke om du inte bockar i ett annat; nya förare skapas med transpondern och bilen från anmälan. Klassvalet kommer RaceCore ihåg till nästa gång. Hämta igen för nästa klass.",
"houseofrc.entries_apply": "Fyll i Race-guiden",
"houseofrc.entry_linked": "Finns",
"houseofrc.entry_copy": "Finns i annan klass",
@@ -4420,12 +4432,24 @@ const TRANSLATIONS = {
"houseofrc.entries_empty": "No drivers entered yet.",
"houseofrc.entries_class": "Our class",
"houseofrc.entries_hor_class": "Class on House of RC",
"houseofrc.refresh_button": "Fetch changes from House of RC",
"houseofrc.refresh_hint": "New entries and withdrawals since the race was created ({name})",
"houseofrc.refresh_title": "Changed entries",
"houseofrc.refresh_nothing": "No changes – the participants match House of RC.",
"houseofrc.refresh_added": "New entries ({count})",
"houseofrc.refresh_withdrawn": "Withdrawn or on the waiting list ({count})",
"houseofrc.refresh_note": "Only heats that haven't run change, just like ticking participants by hand. Drivers you added yourself are not affected.",
"houseofrc.refresh_apply": "Update participants",
"houseofrc.class_remembered": "As last time",
"houseofrc.class_exact": "Same name",
"houseofrc.class_guess": "Guessed – please check",
"houseofrc.entries_brand_hint": "The car in the entry differs from our brand. Tick to use the entry's.",
"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 and keep their name; new drivers get the transponder from the entry. Fetch again for the next class.",
"houseofrc.entries_hint": "Existing drivers are reused and keep their name and brand unless you tick another; new drivers get the transponder and car from the entry. RaceCore remembers the class choice for next time. Fetch again for the next class.",
"houseofrc.entries_apply": "Fill the race wizard",
"houseofrc.entry_linked": "Exists",
"houseofrc.entry_copy": "Exists in another class",
@@ -6593,6 +6617,8 @@ function normalizeImportedClass(classItem) {
return {
id: String(classItem?.id || uid("class")),
name: String(classItem?.name || "").trim(),
// House of RC class names this class was chosen for, so the next fetch picks it again.
...(Array.isArray(classItem?.houseOfRcNames) && classItem.houseOfRcNames.length ? { houseOfRcNames: classItem.houseOfRcNames.map(String).slice(0, 20) } : {}),
};
}
@@ -7455,6 +7481,7 @@ function renderEventManager(eventId) {
t,
escapeHtml,
normalizeEvent,
normalizeDriver,
ensureRaceParticipantsConfigured,
getSessionsForEvent,
buildEventSchedule,
+16
View File
@@ -1,3 +1,4 @@
import { openHouseOfRcEntryRefresh } from "./houseofrc_view.js";
import { mountSponsorSetup } from "./sponsor_event_view.js";
import { mountTeamRaceSetup } from "./team_race_setup_view.js";
import { orderSessionsForRunning, moveSessionInRunningOrder, applyFormatToPendingSessions, syncParticipantsToSessions } from "./event_race_logic.js";
@@ -22,6 +23,7 @@ export function renderEventManagerView(context) {
t,
escapeHtml,
normalizeEvent,
normalizeDriver,
ensureRaceParticipantsConfigured,
getSessionsForEvent,
getSelectedTeamEditId,
@@ -597,6 +599,20 @@ export function renderEventManagerView(context) {
node.addEventListener("change", persistRaceParticipants);
});
// Race made from House of RC: fetch late entries and withdrawals again.
document.getElementById("houseOfRcRefreshEntries")?.addEventListener("click", () => openHouseOfRcEntryRefresh({
event, state, t, escapeHtml,
makeDriver: (fields) => normalizeDriver({ id: uid("driver"), ...fields }),
onApply: (selectedIds) => {
const beforeIds = getEventDrivers(event).map((driver) => driver.id);
event.raceConfig.driverIds = selectedIds;
event.raceConfig.participantsConfigured = true;
syncParticipantsToSessions(state.sessions.filter((session) => session.eventId === event.id), beforeIds, selectedIds);
saveState();
refreshManager();
},
}));
document.getElementById("selectAllParticipants")?.addEventListener("click", () => {
document.querySelectorAll(".race-participant").forEach((node) => {
node.checked = true;
+1
View File
@@ -188,6 +188,7 @@ export function renderEventManagerMarkup(context) {
<div class="actions">
<button id="selectAllParticipants" class="btn" type="button">${t("events.select_all_participants")}</button>
<button id="clearParticipants" class="btn btn-danger" type="button">${t("events.clear_participants")}</button>
${event.houseOfRc?.eventId ? `<button id="houseOfRcRefreshEntries" class="btn" type="button" title="${escapeHtml(t("houseofrc.refresh_hint", { name: event.houseOfRc.name || "" }))}">🔄 ${t("houseofrc.refresh_button")}</button>` : ""}
</div>
${(() => {
const card = (driver) => {
+58 -7
View File
@@ -63,7 +63,11 @@ export function planHouseOfRcEntries(entries = [], drivers = [], classId = "") {
return entries.map((entry) => {
const entryTransponder = (entry.transponders || [])[0] || "";
const existing = find(inClass, entry);
if (existing) return { entry, status: "linked", driverId: existing.id, transponder: existing.transponder || entryTransponder };
if (existing) {
// The car in the entry may differ from what we have: offered, pre-ticked only when ours is empty.
const brandDiffers = Boolean(entry.car) && !sameText(entry.car, existing.brand);
return { entry, status: "linked", driverId: existing.id, transponder: existing.transponder || entryTransponder, currentBrand: existing.brand || "", brandDiffers, brandDefault: brandDiffers && !existing.brand };
}
const source = find(club, entry);
if (source) return { entry, status: "copy", sourceId: source.id, transponder: entryTransponder || source.transponder };
return { entry, status: "new", transponder: entryTransponder };
@@ -73,7 +77,8 @@ export function planHouseOfRcEntries(entries = [], drivers = [], classId = "") {
// 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 }) {
// brands: the row indexes whose car from House of RC replaces our brand.
export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDriver, brands = new Set() }) {
const driverIds = [];
const entryIds = {};
plan.forEach((row, index) => {
@@ -84,6 +89,7 @@ export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDr
if (driver) {
if (memberId) driver.houseOfRcId = memberId;
if (!driver.transponder && row.transponder) driver.transponder = row.transponder;
if (row.brandDiffers && brands.has(index)) driver.brand = entry.car;
} else {
const source = row.sourceId ? drivers.find((item) => item.id === row.sourceId) : null;
driver = makeDriver({
@@ -105,15 +111,60 @@ export function applyHouseOfRcEntries(drivers, plan, { classId, selected, makeDr
return { driverIds, entryIds };
}
// Our class for a House of RC class: the same name (ignoring case and spaces), else the one
// class whose name holds the other as whole words ("4wd" ~ "4WD Buggy"), else none.
// Our class for a House of RC class, and how sure it is:
// remembered - chosen for this House of RC class name before
// exact - the same name (ignoring case and spaces)
// guess - the one class whose name holds the other as whole words ("4wd" ~ "4WD Buggy")
export function matchHouseOfRcClass(classes = [], name = "") {
const remembered = classes.find((item) => (item.houseOfRcNames || []).some((known) => sameText(known, name)));
if (remembered) return { id: remembered.id, how: "remembered" };
const exact = classes.find((item) => sameText(item.name, name));
if (exact) return exact.id;
if (exact) return { id: exact.id, how: "exact" };
const words = (text) => String(text || "").toLocaleLowerCase().split(/[^\p{L}\p{N}.]+/u).filter(Boolean);
const wanted = words(name);
if (!wanted.length) return "";
if (!wanted.length) return { id: "", how: "" };
const holds = (outer, inner) => inner.length <= outer.length && outer.some((_word, index) => inner.every((word, offset) => outer[index + offset] === word));
const candidates = classes.filter((item) => { const own = words(item.name); return holds(own, wanted) || holds(wanted, own); });
return candidates.length === 1 ? candidates[0].id : "";
return candidates.length === 1 ? { id: candidates[0].id, how: "guess" } : { id: "", how: "" };
}
// Remember the choice: this House of RC class name now points at our class only.
export function rememberHouseOfRcClass(classes = [], classId = "", name = "") {
if (!name) return;
classes.forEach((item) => {
const known = (item.houseOfRcNames || []).filter((value) => !sameText(value, name));
if (item.id === classId) known.push(name);
if (known.length) item.houseOfRcNames = known;
else delete item.houseOfRcNames;
});
}
// Re-fetch for a race made from House of RC: which entries of its class are new, and which of
// our participants' entries are gone (withdrawn or moved to the waiting list - the server
// leaves those out). Participants added by hand (no entry id) are never touched.
export function diffHouseOfRcEntries(event, entries = [], drivers = []) {
const link = event?.houseOfRc || {};
const entryIds = link.entryIds || {};
const participants = new Set(event?.raceConfig?.driverIds || []);
const classEntries = entries.filter((entry) => link.classId == null || entry.classId === link.classId);
const known = new Set(Object.entries(entryIds).filter(([driverId]) => participants.has(driverId)).map(([, entryId]) => entryId));
const plan = planHouseOfRcEntries(classEntries, drivers, event?.classId || "");
const added = plan.filter((row) => !known.has(row.entry.entryId) && !(row.driverId && participants.has(row.driverId) && entryIds[row.driverId] == null));
const current = new Set(classEntries.map((entry) => entry.entryId));
const withdrawn = Object.entries(entryIds)
.filter(([driverId, entryId]) => participants.has(driverId) && !current.has(entryId))
.map(([driverId]) => drivers.find((driver) => driver.id === driverId))
.filter(Boolean);
return { added, withdrawn };
}
// Apply a re-fetch: add the ticked new entries, take out the ticked withdrawn drivers.
// Returns the new participant list (entry order kept, new ones last).
export function applyHouseOfRcEntryChanges(event, drivers, diff, { addIndexes, removeIds, makeDriver, brands = new Set() }) {
const link = event.houseOfRc;
const { driverIds: addedIds, entryIds } = applyHouseOfRcEntries(drivers, diff.added, { classId: event.classId, selected: addIndexes, makeDriver, brands });
link.entryIds = { ...(link.entryIds || {}), ...entryIds };
removeIds.forEach((driverId) => { delete link.entryIds[driverId]; });
const before = event.raceConfig.driverIds || [];
return [...before.filter((id) => !removeIds.has(id)), ...addedIds.filter((id) => !before.includes(id))];
}
+60 -5
View File
@@ -1,4 +1,4 @@
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass } from "./houseofrc_logic.js";
import { planHouseOfRcDriverUpdates, applyHouseOfRcDriverUpdates, planHouseOfRcEntries, applyHouseOfRcEntries, matchHouseOfRcClass, rememberHouseOfRcClass, diffHouseOfRcEntries, applyHouseOfRcEntryChanges } 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).
@@ -235,9 +235,14 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState,
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) ourClassId = matchHouseOfRcClass(state.classes, horClass?.name) || NEW_CLASS;
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;
@@ -252,6 +257,7 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState,
${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 ? `
@@ -261,7 +267,9 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState,
<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>${escapeHtml(row.entry.car || "–")}</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>
@@ -271,7 +279,7 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState,
: `<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; 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;
@@ -280,7 +288,9 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState,
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, entryIds } = applyHouseOfRcEntries(state.drivers, plan, { classId, selected, makeDriver });
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 });
@@ -291,3 +301,48 @@ export function openHouseOfRcEventImport({ state, t, escapeHtml, uid, saveState,
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);
});
}