153 lines
13 KiB
JavaScript
153 lines
13 KiB
JavaScript
import assert from "node:assert/strict";
|
||
|
||
// The race day schedule: every class on one date in one running order with times, ▲▼, a
|
||
// start time and gap, pause/resume of the day, the autopilot telling what it waits for, and
|
||
// the drivers' board with the next heats and a heads-up.
|
||
export async function runDayScheduleSmoke({ evaluate, navigate, savedState, waitFor, base, send, dialogs }) {
|
||
const dialogsAtStart = dialogs.length;
|
||
const patchState = async (patch) => {
|
||
const current = await savedState();
|
||
Object.assign(current, patch);
|
||
const response = await fetch(base + "/api/state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(current) });
|
||
assert.equal(response.ok, true);
|
||
};
|
||
const d = new Date();
|
||
const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||
const seeded = await savedState();
|
||
const heat = (id, eventId, name) => ({ id, eventId, name, type: "qualification", mode: "race", status: "ready", durationMin: 5, startMode: "staggered" });
|
||
await patchState({
|
||
sessions: [
|
||
...seeded.sessions.map((session) => (["running", "paused"].includes(session.status) ? { ...session, status: "finished", endedAt: Date.now() } : session)),
|
||
heat("ds_2wd_q1", "ds_2wd", "Q1 H1"), heat("ds_4wd_q1", "ds_4wd", "Q1 H1"), heat("ds_2wd_q2", "ds_2wd", "Q2 H1"),
|
||
],
|
||
events: [...seeded.events, { id: "ds_2wd", name: "DS Cup 2WD", date: today, mode: "race", raceConfig: {} }, { id: "ds_4wd", name: "DS Cup 4WD", date: today, mode: "race", raceConfig: {} }],
|
||
activeSessionId: "ds_2wd_q1",
|
||
raceDays: [],
|
||
});
|
||
const rowIds = () => evaluate(`[...document.querySelectorAll("[data-day-row]")].map((row) => row.dataset.dayRow)`);
|
||
try {
|
||
await navigate("race_day", "daySchedule");
|
||
await waitFor(async () => (await rowIds()).join() === "ds_2wd_q1,ds_4wd_q1,ds_2wd_q2", "both classes in one running order, round by round");
|
||
await evaluate(`document.querySelector('[data-day-move="ds_4wd_q1"][data-step="-1"]').click()`);
|
||
await waitFor(async () => (await rowIds()).join() === "ds_4wd_q1,ds_2wd_q1,ds_2wd_q2", "▲ moves the 4WD heat first");
|
||
await waitFor(async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.sessionOrder?.[0] === "ds_4wd_q1", "the day order is saved");
|
||
console.log("PASS Race Day shows today's schedule for every class in running order and ▲▼ change it");
|
||
|
||
// First start in an hour, 2 min between heats: the second heat is 5 + 2 min later.
|
||
const inAnHour = new Date(Date.now() + 3600000);
|
||
const hhmm = (date) => `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
||
await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.elements.startTime.value = ${JSON.stringify(hhmm(inAnHour))}; form.elements.gapMin.value = "2"; form.requestSubmit(); })()`);
|
||
await waitFor(async () => Boolean(((await savedState()).raceDays || []).find((day) => day.date === today)?.startAt), "start time saved");
|
||
const times = await evaluate(`[...document.querySelectorAll("[data-day-row] td:first-child strong")].map((cell) => cell.textContent)`);
|
||
// Run in the last hour before midnight, "in an hour" is tomorrow: today's start time is then
|
||
// already past and the schedule starts from now - only the gap can be checked.
|
||
if (inAnHour.getDate() === new Date().getDate()) {
|
||
assert.equal(times[0], hhmm(inAnHour));
|
||
assert.equal(times[1], hhmm(new Date(inAnHour.getTime() + 7 * 60000)));
|
||
} else {
|
||
const minutes = (value) => Number(value.slice(0, 2)) * 60 + Number(value.slice(3, 5));
|
||
assert.equal((minutes(times[1]) - minutes(times[0]) + 1440) % 1440, 7, "5 min heat + 2 min gap");
|
||
}
|
||
console.log("PASS the day gets a first start time and gap, and every heat its planned time");
|
||
|
||
// Several fixed breaks: fill the empty row, + Add break for a second, save; ✕ removes one.
|
||
// Early-morning times so they never move the heats the rest of this test plans.
|
||
const savedBreaks = async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.fixedBreaks || [];
|
||
await evaluate(`(() => {
|
||
const form = document.getElementById("dayPlanForm");
|
||
const fill = (row, label, from, to) => { row.querySelector('[name="breakLabel"]').value = label; row.querySelector('[name="breakFrom"]').value = from; row.querySelector('[name="breakTo"]').value = to; };
|
||
fill(form.querySelector("[data-fixed-break]"), "Prisutdelning", "04:00", "04:10");
|
||
form.querySelector("[data-fixed-break-add]").click();
|
||
const rows = form.querySelectorAll("[data-fixed-break]");
|
||
fill(rows[rows.length - 1], "Lunch", "03:00", "03:10");
|
||
form.requestSubmit();
|
||
})()`);
|
||
await waitFor(async () => (await savedBreaks()).length === 2, "two breaks saved");
|
||
assert.deepEqual((await savedBreaks()).map((item) => item.label), ["Lunch", "Prisutdelning"], "saved in time order");
|
||
await waitFor(async () => (await evaluate(`document.querySelectorAll("#dayPlanForm [data-fixed-break]").length`)) === 3, "two breaks and an empty row after saving");
|
||
await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.querySelector("[data-fixed-break] [data-fixed-break-remove]").click(); form.requestSubmit(); })()`);
|
||
await waitFor(async () => (await savedBreaks()).map((item) => item.label).join() === "Prisutdelning", "✕ removed the lunch");
|
||
await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.querySelector("[data-fixed-break] [data-fixed-break-remove]").click(); form.requestSubmit(); })()`);
|
||
await waitFor(async () => (await savedBreaks()).length === 0, "no breaks left");
|
||
console.log("PASS several fixed breaks a day: add, save in time order, remove");
|
||
|
||
await evaluate(`document.getElementById("dayAutopilotOn").click()`);
|
||
await waitFor(async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.autopilot === true, "autopilot on");
|
||
await waitFor(async () => (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)).startsWith("Next: 4WD") || (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)).includes("DS"), "the autopilot says what is next");
|
||
// (Near midnight the first heat is already due, so the autopilot waits for the decoder instead.)
|
||
assert.match(await evaluate(`document.querySelector("[data-autopilot-status]").textContent`), inAnHour.getDate() === new Date().getDate() ? /^Next: .*Q1 H1 at / : /Q1 H1/);
|
||
// Time is up but no decoder: it waits and says why instead of starting.
|
||
await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.elements.startTime.value = ${JSON.stringify(hhmm(new Date(Date.now() - 60000)))}; form.requestSubmit(); })()`);
|
||
await waitFor(async () => (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)).includes("decoder is not connected"), "waits for the decoder");
|
||
assert.equal((await savedState()).sessions.find((session) => session.id === "ds_4wd_q1").status, "ready", "nothing started without a decoder");
|
||
// With the autopilot on, a heat due within 10 minutes is called on its own.
|
||
await waitFor(async () => Boolean((await savedState()).sessions.find((session) => session.id === "ds_4wd_q1").calledAt), "the autopilot calls the next heat");
|
||
assert.equal(await evaluate(`Boolean(document.getElementById("dayCallBanner"))`), false, "no question to the race controller while the autopilot runs");
|
||
await evaluate(`document.getElementById("dayPause").click()`);
|
||
await waitFor(async () => Boolean(((await savedState()).raceDays || []).find((day) => day.date === today)?.pausedAt), "the day is paused");
|
||
await waitFor(async () => (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)) === "The day is paused", "the autopilot says the day is paused");
|
||
await evaluate(`document.getElementById("dayResume").click()`);
|
||
await waitFor(async () => !((await savedState()).raceDays || []).find((day) => day.date === today)?.pausedAt, "the day is resumed");
|
||
await evaluate(`document.getElementById("dayAutopilotOff").click()`);
|
||
await waitFor(async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.autopilot === false, "autopilot off");
|
||
console.log("PASS the autopilot says what comes next, calls the heat, waits for the decoder, and the day can be paused and resumed");
|
||
|
||
// By hand: Race Day asks the race controller to call the next heat (here 20 min before).
|
||
await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.elements.callMin.value = "20"; form.requestSubmit(); })()`);
|
||
// The autopilot may already have called the 2WD Q1 H1; the banner asks for each heat not yet called, in order.
|
||
for (let round = 0; round < 3; round += 1) {
|
||
await waitFor(async () => Boolean(await evaluate(`document.getElementById("dayCallBanner")?.dataset.dayCall`)), "Race Day asks to call the next heat not yet called");
|
||
const asked = await evaluate(`document.getElementById("dayCallBanner").dataset.dayCall`);
|
||
await evaluate(`document.getElementById("dayCallNow").click()`);
|
||
await waitFor(async () => Boolean((await savedState()).sessions.find((session) => session.id === asked).calledAt), "Call now marks it called");
|
||
if (asked === "ds_2wd_q2") break;
|
||
}
|
||
await waitFor(async () => !(await evaluate(`Boolean(document.getElementById("dayCallBanner"))`)), "and the question goes away once every heat is called");
|
||
console.log("PASS heats started by hand: Race Day asks the race controller to call the next heat");
|
||
|
||
const printHtml = await evaluate(`(async () => {
|
||
const { buildDaySchedulePrintHtml } = await import("/src/day_schedule_view.js");
|
||
return buildDaySchedulePrintHtml({ t: (key, vars = {}) => key + JSON.stringify(vars), escapeHtml: (value) => String(value), date: "D", rows: [{ start: Date.now(), session: { name: "Q1 H1" } }], getClassLabel: () => "2WD", getSessionGridEntries: () => [{ name: "Roy" }, { name: "Eddie" }] });
|
||
})()`);
|
||
assert.ok(printHtml.includes("2WD · Q1 H1") && printHtml.includes("<li>Roy</li><li>Eddie</li>"), "the printed running order lists each heat's drivers");
|
||
|
||
// The drivers' board: the next heats with a heads-up (the first is due now) and the rest.
|
||
await send("Page.navigate", { url: base + "/public-overlay/schedule" });
|
||
await waitFor(async () => (await evaluate(`document.querySelectorAll(".board-next").length`)) === 3, "the board shows the next three heats");
|
||
const board = await evaluate(`document.querySelector(".driver-board").innerText`);
|
||
assert.ok(board.includes("Called – get ready"), "a called heat is highlighted for the drivers");
|
||
assert.equal(await evaluate(`document.querySelector(".board-next").classList.contains("is-called")`), true);
|
||
assert.equal(await evaluate(`document.querySelector(".board-next").dataset.boardSession`), "ds_4wd_q1", "in the day's order");
|
||
console.log("PASS the drivers' board shows the next heats with their drivers, called heats highlighted");
|
||
|
||
// A run heat folds away on Race Day; the next one is marked.
|
||
const now = Date.now();
|
||
await patchState({ sessions: (await savedState()).sessions.map((session) => (session.id === "ds_4wd_q1" ? { ...session, status: "finished", startedAt: now - 400000, endedAt: now - 100000 } : session)), activeSessionId: "ds_2wd_q1" });
|
||
await navigate("race_day", "daySchedule");
|
||
await waitFor(async () => !(await rowIds()).includes("ds_4wd_q1"), "the run heat is folded away");
|
||
assert.match(await evaluate(`document.getElementById("dayToggleDone").textContent`), /1 heats run/);
|
||
assert.equal(await evaluate(`document.querySelector("tr.is-next")?.dataset.dayRow`), (await rowIds())[0], "the next heat is marked");
|
||
await evaluate(`document.getElementById("dayToggleDone").click()`);
|
||
await waitFor(async () => (await rowIds()).includes("ds_4wd_q1"), "and shown again on request");
|
||
console.log("PASS today's schedule folds run heats into one line and marks the next heat");
|
||
|
||
// Deleting a race always asks first (the harness answers OK).
|
||
await patchState({ events: [...(await savedState()).events, { id: "ds_delete_me", name: "DS Delete Me", date: today, mode: "race", raceConfig: {} }] });
|
||
await navigate("race_setup", "raceWizardStepForm");
|
||
const asked = dialogs.length;
|
||
await evaluate(`document.getElementById("event-delete-ds_delete_me").click()`);
|
||
await waitFor(async () => !(await savedState()).events.some((event) => event.id === "ds_delete_me"), "the race is deleted after OK");
|
||
assert.equal(dialogs.length, asked + 1, "a question was asked");
|
||
assert.match(dialogs.at(-1).message, /DS Delete Me/);
|
||
console.log("PASS deleting a race asks first");
|
||
} finally {
|
||
const current = await savedState();
|
||
await patchState({
|
||
sessions: current.sessions.filter((session) => !session.id.startsWith("ds_")),
|
||
events: current.events.filter((event) => !event.id.startsWith("ds_")),
|
||
raceDays: [],
|
||
});
|
||
dialogs.splice(dialogsAtStart);
|
||
}
|
||
}
|