feat(server): scheduled jobs on the server and a Scheduled tab in the admin panel

Owner review 2, R10: nothing may run out of sight, so every timer the server
ran becomes a system schedule the admin panel shows and manages, and
administrators create their own.

- SchedulerHost runs the shared Scheduler on the job engine (started after
  JobEngineHost, stopped before it); ServerScheduleHost gives it the
  container's time zone (UTC with a warning when TZ is unknown), the archive
  refreshed from archive.json at every run (what ArchivePolling did), the
  clean-up steps and the system schedules: archive-scan every 10 minutes
  (no catch-up, also run once at start like the polling), upload-cleanup
  every 30 minutes, index-backup at 03:00 (SQLite only), housekeeping (job
  history) at 04:00 and audit-cleanup at 04:30.
- ArchivePolling and DatabaseBackupService are gone; UploadMaintenance only
  recovers commits at start, its sweep is the "uploads" clean-up step.
- /api/v1/schedules (ManageArchive, audited): list with actions and time
  zone, create, PUT/PATCH, delete (409 schedule_system), run now (409
  schedule_pending), reset (409 schedule_no_defaults), runs paged by cursor;
  invalid fields are 400 invalid_schedule naming the field.
- CHRONOS_AUDIT_RETENTION_DAYS (AuditRetentionDays, default 365) seeds the
  audit clean-up; set by the environment it is applied at every start and
  locked. Job history leaves Settings: it is the housekeeping schedule's age
  limit, and the setting is what a reset restores.
- Admin panel: Jobs has Queue and Scheduled tabs; schedules with when (in
  the panel's language and the server's zone), next run, last result, a
  switch, Run now, Edit, Delete or Reset, their runs linking to the jobs, and
  a side panel for the action, recurrence and parameters; job rows a
  schedule queued carry a Scheduled pill. Strings in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 808ce94ae29e3bf4522cb4d40dfd76d4f8529c64)
This commit is contained in:
Alby96 committed 2026-10-27 02:25:01 +01:00
1 parent e5508e7e69
commit 75daab7275
66 files changed
+1985 -290

No files matched your search

+534
View File
@@ -0,0 +1,534 @@
// Scheduled jobs (owner review 2, R10): the Scheduled tab of the Jobs page (#/jobs?tab=schedules). Every schedule of the
// server, its system schedules first (the timers it runs, shown so nothing runs out of sight), with when it runs in the
// server's time zone, its next run, its last result and a switch; Run now, Edit, Delete (user schedules) and Reset
// (system schedules). A schedule's name opens its last runs, each linking to its job on the Queue tab. A side panel
// creates and edits schedules: the action (those the server cannot run are disabled, their reason in the tooltip), the
// recurrence, the action's parameters, priority, catch-up and the switch.
import { t, plural, has, applyStrings, culture } from "./i18n.js";
import { escapeHtml, attr, formatNumber, formatTime, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, focusPlace, restoreFocus, fitColumns,
markInvalid, clearInvalid, invalidText } from "./ui.js";
import { kindLabel, pascal, stateCell } from "./jobs.js";
const KINDS = ["every", "daily", "weekly", "monthly"];
const UNITS = ["minutes", "hours", "days"];
/** Day names of the API, Monday first; 1 January 2001 was a Monday. */
const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
const PRIORITIES = ["background", "normal", "user"];
/** The parameters each action reads (ScheduleActions.Normalize), in the order the form shows them. */
const PARAMETERS = {
scan: ["force", "deep"], verify: ["olderThanDays", "percent"], thumbnails: ["force"], proxies: ["force"], analysis: ["deep"],
maintenance: ["dryRun"], backup: ["keep"], cleanup: ["steps", "olderThanDays"], duplicates: [], orphans: [],
};
/** What a new schedule of an action starts with (ScheduleActions.Defaults); absent values are false or off. */
const DEFAULTS = { verify: { olderThanDays: 30, percent: 100 }, backup: { keep: 3 }, cleanup: { steps: ["job-history"], olderThanDays: 90 } };
/** A parameter's label and tooltip by action, under Admin.Schedules.Param. */
const PARAM_KEYS = {
"scan.force": "FullScan", "scan.deep": "DeepAfterScan", "thumbnails.force": "MakeAgain", "proxies.force": "MakeAgain", "analysis.deep": "Deep",
"verify.olderThanDays": "UncheckedDays", "verify.percent": "Percent", "maintenance.dryRun": "DryRun", "backup.keep": "Keep",
"cleanup.steps": "Steps", "cleanup.olderThanDays": "OlderDays",
};
const NUMBERS = { olderThanDays: 'min="0" max="3650"', percent: 'min="1" max="100"', keep: 'min="1" max="100"' };
/** Settings an environment variable fixes for a system schedule's age limit (ServerScheduleHost.LockedAgeOf). */
const LOCKED_AGES = { "audit-cleanup": ["AuditRetentionDays", "CHRONOS_AUDIT_RETENTION_DAYS"] };
/** A schedule's name: a system schedule's in the panel's language (by its key), a user's as typed. */
export function scheduleName(schedule) {
const key = schedule.systemKey ? `Admin.Schedules.System.${pascal(schedule.systemKey)}` : null;
return key && has(key) ? t(key) : schedule.name;
}
export function actionLabel(action) {
const key = `Admin.Schedules.Action.${pascal(action)}`;
return has(key) ? t(key) : action;
}
/** "Queued", "Skipped: busy", "Failed"… for an outcome code (failed:<reason> included). */
export function outcomeLabel(outcome) {
if (String(outcome).startsWith("failed:")) return t("Admin.Schedules.Outcome.Failed");
const key = `Admin.Schedules.Outcome.${pascal(outcome ?? "")}`;
return has(key) ? t(key) : String(outcome ?? "");
}
/** What an outcome means, as one sentence (a failure with its reason). */
export function outcomeTip(outcome) {
const text = String(outcome ?? "");
if (text.startsWith("failed:")) return t("Admin.Schedules.Outcome.Failed.Tip", text.slice("failed:".length));
const key = `Admin.Schedules.Outcome.${pascal(text)}.Tip`;
return has(key) ? t(key) : text;
}
/** "Every 10 minutes", "Daily at 03:00", "Mon, Thu at 02:30", "Day 1 of each month at 04:00" in the panel's language. */
export function recurrenceText(r) {
switch (r?.kind) {
case "every": return UNITS.includes(r.unit) ? plural(`Admin.Schedules.Every.${cap(r.unit)}`, r.every) : `${r.every} ${r.unit}`;
case "daily": return t("Admin.Schedules.DailyAt", timeText(r.time));
case "weekly": return t("Admin.Schedules.WeeklyAt", dayList(r.days ?? []), timeText(r.time));
case "monthly": return t("Admin.Schedules.MonthlyAt", formatNumber(r.dayOfMonth), timeText(r.time));
default: return r?.kind ?? "";
}
}
export async function renderSchedules(root, { api, setMeta, actions, onEvent }, focusSchedule) {
let schedules = [];
let available = [];
let steps = [];
let zone = "UTC";
let locked = [];
let lastJobs = new Map();
const runs = new Map();
const expanded = new Set(focusSchedule ? [focusSchedule] : []);
let opener = null;
let timer = null;
actions.innerHTML = `<button class="btn primary" id="new" data-i18n="Admin.Schedules.New" data-i18n-title="Admin.Schedules.New.Tip"></button>`;
applyStrings(actions);
actions.querySelector("#new").addEventListener("click", () => openForm(null));
root.innerHTML = `
<div class="split">
<section class="panel flush">
<div class="table schedules" data-levels="2" role="table" aria-label="${attr(t("Admin.Jobs.Tab.Schedules"))}">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Schedules.Name"></span><span role="columnheader" class="col-action" data-i18n="Admin.Schedules.Action"></span>
<span role="columnheader" data-i18n="Admin.Schedules.When"></span><span role="columnheader" data-i18n="Admin.Schedules.NextRun"></span>
<span role="columnheader" class="col-last" data-i18n="Admin.Schedules.LastResult"></span><span role="columnheader" data-i18n="Admin.Schedules.Enabled"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
</section>
<aside class="panel side" id="side" hidden></aside>
</div>`;
applyStrings(root);
const table = root.querySelector(".table");
const side = root.querySelector("#side");
side.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
e.preventDefault();
closeSide();
}
});
async function load() {
if (!root.isConnected) return;
try {
const [list, settings] = await Promise.all([api.get("/api/v1/schedules"), api.get("/api/v1/server/settings").catch(() => null)]);
schedules = list.items;
available = list.actions;
steps = list.steps ?? [];
zone = list.timeZone;
locked = settings?.locked ?? [];
// The state of each schedule's last job, for the Last result column (a job the history no longer has shows the outcome).
const ids = [...new Set(schedules.filter((s) => s.lastJobId && s.lastOutcome === "queued").map((s) => s.lastJobId))];
const jobs = await Promise.all(ids.map((id) => api.get(`/api/v1/jobs/${id}`).catch(() => null)));
lastJobs = new Map(jobs.filter(Boolean).map((j) => [j.id, j]));
await Promise.all([...expanded].map((id) => loadRuns(id)));
} catch (err) {
toast(errorText(err), true);
return;
}
if (!root.isConnected) return;
setMeta(`${plural("Admin.Schedules.Count", schedules.length)} · ${t("Admin.Schedules.TimeZone", zone)}`);
draw();
if (focusSchedule) {
root.querySelector(`[data-key="${CSS.escape(focusSchedule)}"]`)?.scrollIntoView({ block: "center" });
root.querySelector(`[data-toggle="${CSS.escape(focusSchedule)}"]`)?.focus();
focusSchedule = null;
}
}
/** The first page of a schedule's runs, or the next one with more. */
async function loadRuns(id, more = false) {
const known = runs.get(id);
const cursor = more && known?.cursor ? `&cursor=${encodeURIComponent(known.cursor)}` : "";
const page = await api.get(`/api/v1/schedules/${id}/runs?limit=10${cursor}`);
runs.set(id, { items: more && known ? known.items.concat(page.items) : page.items, cursor: page.nextCursor });
}
function draw() {
const host = root.querySelector("#rows");
redraw(host, () => {
host.innerHTML = schedules.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Schedules.Empty",
`<button class="btn small" id="empty-new" data-i18n="Admin.Schedules.New" data-i18n-title="Admin.Schedules.New.Tip"></button>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => toggle(b.dataset.toggle)));
host.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.dataset.act, find(b.closest("[data-key]").dataset.key))));
host.querySelectorAll("[data-enable]").forEach((box) => box.addEventListener("change", () => setEnabled(find(box.dataset.enable), box)));
host.querySelectorAll("[data-more-runs]").forEach((b) => b.addEventListener("click", () => moreRuns(b.dataset.moreRuns)));
host.querySelectorAll("[data-run-first]").forEach((b) => b.addEventListener("click", () => act("run", find(b.dataset.runFirst))));
host.querySelector("#empty-new")?.addEventListener("click", () => openForm(null));
fitColumns(table);
}
function find(id) {
return schedules.find((s) => s.id === id);
}
function rowHtml(s) {
const name = scheduleName(s);
const button = (act, key, extra = "") => `<button class="btn small${extra}" data-act="${act}" data-i18n="Admin.Schedules.${key}" data-i18n-title="Admin.Schedules.${key}.Tip"></button>`;
const buttons = button("run", "Run") + button("edit", "Edit") + (s.systemKey ? button("reset", "Reset") : button("delete", "Delete", " destructive"));
const when = recurrenceText(s.recurrence);
return `
<div class="row${s.enabled ? "" : " dim"}" role="row" data-key="${attr(s.id)}">
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(s.id)}" aria-expanded="${expanded.has(s.id)}" aria-controls="runs-${attr(s.id)}"
dir="auto" data-i18n-title="Admin.Schedules.Runs.Tip">${escapeHtml(name)}</button>${s.systemKey
? `<span class="pill" data-i18n="Admin.Schedules.System" data-i18n-title="Admin.Schedules.System.Tip"></span>` : ""}</span>
<span class="col-action ellipsis" role="cell" title="${attr(actionTip(s.action))}">${escapeHtml(actionLabel(s.action))}</span>
<span class="ellipsis" role="cell" title="${attr(t("Admin.Schedules.When.Tip", zone))}">${escapeHtml(when)}</span>
<span class="num nowrap" role="cell" title="${attr(t("Admin.Schedules.NextRun.Tip", zone))}">${escapeHtml(s.enabled ? zonedTime(s.nextRun, zone) : t("Admin.Schedules.Off"))}</span>
<span class="col-last ellipsis" role="cell">${lastResult(s)}</span>
<span role="cell"><input type="checkbox" role="switch" data-enable="${attr(s.id)}" ${s.enabled ? "checked" : ""}
aria-label="${attr(t("Admin.Schedules.EnabledFor", name))}" title="${attr(t("Admin.Schedules.Enabled.Tip"))}"></span>
<span class="row-actions" role="cell">${buttons}</span>
</div>
${expanded.has(s.id) ? `<div class="row log-row" role="row"><div class="wide" role="cell" id="runs-${attr(s.id)}">${runsHtml(s)}</div></div>` : ""}`;
}
/** The last result: the last job's state when the run queued one, else what the run did; when, in the tooltip's words. */
function lastResult(s) {
if (!s.lastRun) return `<span class="muted" data-i18n="Admin.Schedules.Never"></span>`;
const when = `<span class="muted"> · ${escapeHtml(formatTime(s.lastRun))}</span>`;
const tip = `${outcomeTip(s.lastOutcome)} · ${formatDateTime(s.lastRun)}`;
const job = s.lastOutcome === "queued" ? lastJobs.get(s.lastJobId) : null;
if (job) return `<span title="${attr(tip)}">${stateCell(job.state)}${when}</span>`;
const failed = String(s.lastOutcome).startsWith("failed:");
return `<span class="${failed ? "state failed" : ""}" title="${attr(tip)}">${escapeHtml(outcomeLabel(s.lastOutcome))}${when}</span>`;
}
function runsHtml(s) {
const page = runs.get(s.id);
if (!page) return "";
if (page.items.length === 0) {
return emptyState("Admin.Schedules.NoRuns", `<button class="btn small" data-run-first="${attr(s.id)}" data-i18n="Admin.Schedules.Run" data-i18n-title="Admin.Schedules.Run.Tip"></button>`);
}
return `<div class="runs" role="list" aria-label="${attr(t("Admin.Schedules.RunsOf", scheduleName(s)))}">${page.items.map((j) => `
<div class="run" role="listitem"><span class="ellipsis">${escapeHtml(kindLabel(j.kind))}</span><span>${stateCell(j.state)}</span>
<span class="muted nowrap num">${escapeHtml(formatDateTime(j.created))}</span>
<a class="btn small" href="#/jobs?job=${attr(j.id)}" data-i18n="Admin.Schedules.OpenJob" data-i18n-title="Admin.Schedules.OpenJob.Tip"></a></div>`).join("")}
${page.cursor ? `<button class="btn small more" data-more-runs="${attr(s.id)}" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button>` : ""}</div>`;
}
async function toggle(id) {
if (expanded.delete(id)) {
draw();
return;
}
expanded.add(id);
try {
await loadRuns(id);
} catch (err) {
toast(errorText(err), true);
}
draw();
}
async function moreRuns(id) {
try {
await loadRuns(id, true);
} catch (err) {
toast(errorText(err), true);
return;
}
draw();
}
async function act(action, schedule) {
if (!schedule) return;
try {
if (action === "edit") return openForm(schedule);
if (action === "run") {
const run = await api.post(`/api/v1/schedules/${schedule.id}/run`);
toast(outcomeTip(run.outcome), String(run.outcome).startsWith("failed:"));
runs.delete(schedule.id);
} else if (action === "delete") {
const confirmed = await confirmDialog({
title: t("Admin.Schedules.DeleteTitle", scheduleName(schedule)),
confirm: t("Admin.Schedules.Delete"),
confirmTip: t("Admin.Schedules.Delete.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
await api.del(`/api/v1/schedules/${schedule.id}`);
expanded.delete(schedule.id);
} else if (action === "reset") {
const confirmed = await confirmDialog({
title: t("Admin.Schedules.ResetTitle", scheduleName(schedule)),
confirm: t("Admin.Schedules.Reset"),
confirmTip: t("Admin.Schedules.Reset.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
await api.post(`/api/v1/schedules/${schedule.id}/reset`);
}
await load();
} catch (err) {
toast(errorText(err), true);
}
}
async function setEnabled(schedule, box) {
try {
await api.put(`/api/v1/schedules/${schedule.id}`, { enabled: box.checked });
await load();
} catch (err) {
box.checked = !box.checked;
toast(errorText(err), true);
}
}
/** Shows the side panel, remembering which control opened it so closing returns the keyboard there. */
function openSide(html) {
if (side.hidden) {
const scope = actions.contains(document.activeElement) ? actions : root;
opener = { scope, place: focusPlace(scope) };
}
side.hidden = false;
side.innerHTML = html;
applyStrings(side);
fitColumns(table);
side.querySelector("#close").addEventListener("click", closeSide);
}
function closeSide() {
side.hidden = true;
side.innerHTML = "";
fitColumns(table);
if (opener) restoreFocus(opener.scope, opener.place);
opener = null;
}
function openForm(schedule) {
const editing = schedule !== null;
const system = editing && Boolean(schedule.systemKey);
const first = available.find((a) => a.available)?.name ?? "scan";
const draft = { recurrence: { every: 1, unit: "hours", time: "03:00", days: ["mon"], dayOfMonth: 1, ...(schedule?.recurrence ?? { kind: "daily" }) } };
const fixed = `disabled title="${attr(t("Admin.Schedules.Fixed.Tip"))}"`;
const actionOptions = (editing && !available.some((a) => a.name === schedule.action) ? [{ name: schedule.action, available: false }] : available).map((a) =>
`<option value="${attr(a.name)}" ${a.name === (schedule?.action ?? first) ? "selected" : ""} ${a.available || a.name === schedule?.action ? "" : "disabled"}
title="${attr(a.available ? actionTip(a.name) : reasonTip(a.reason))}">${escapeHtml(actionLabel(a.name))}</option>`).join("");
openSide(`
<form class="form" novalidate>
<h2 data-i18n="${editing ? "Admin.Schedules.EditTitle" : "Admin.Schedules.New"}"></h2>
<label><span data-i18n="Admin.Schedules.Name"></span>
<input class="input" name="name" required maxlength="100" autocomplete="off" dir="auto" value="${attr(editing ? scheduleName(schedule) : "")}" ${system ? fixed : `data-i18n-title="Admin.Schedules.Name.Tip"`}></label>
<label><span data-i18n="Admin.Schedules.Action"></span>
<select class="input" name="action" ${system ? fixed : `data-i18n-title="Admin.Schedules.Action.Tip"`}>${actionOptions}</select></label>
<label><span data-i18n="Admin.Schedules.Repeat"></span>
<select class="input" name="kind" data-i18n-title="Admin.Schedules.Repeat.Tip">${KINDS.map((k) =>
`<option value="${k}" ${k === draft.recurrence.kind ? "selected" : ""}>${escapeHtml(t(`Admin.Schedules.Kind.${cap(k)}`))}</option>`).join("")}</select></label>
<div class="form-group" id="recurrence"></div>
<div class="form-group" id="parameters"></div>
<label><span data-i18n="Admin.Schedules.Priority"></span>
<select class="input" name="priority" data-i18n-title="Admin.Schedules.Priority.Tip">${PRIORITIES.map((p) =>
`<option value="${p}" ${p === (schedule?.priority ?? "background") ? "selected" : ""}>${escapeHtml(t(`Admin.Jobs.Priority.${cap(p)}`))}</option>`).join("")}</select></label>
<label class="check"><input type="checkbox" name="catchUp" ${schedule?.catchUp ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.CatchUp.Tip"><span data-i18n="Admin.Schedules.CatchUp"></span></label>
<label class="check"><input type="checkbox" name="enabled" ${schedule?.enabled ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.Enabled.Tip"><span data-i18n="Admin.Schedules.Enabled"></span></label>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Schedules.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Schedules.Create.Tip"}"></button>
</div>
</form>`);
const form = side.querySelector("form");
const values = (action) => action === schedule?.action ? schedule.parameters : (DEFAULTS[action] ?? {});
drawRecurrence(form, draft.recurrence);
drawParameters(form, schedule?.action ?? first, values(schedule?.action ?? first), schedule?.systemKey);
form.elements.kind.addEventListener("change", () => {
// The fields drawn are still those of the kind chosen before.
draft.recurrence = { ...draft.recurrence, ...shownFields(form, draft.recurrence.kind), kind: form.elements.kind.value };
drawRecurrence(form, draft.recurrence);
});
form.elements.action.addEventListener("change", () => drawParameters(form, form.elements.action.value, values(form.elements.action.value), schedule?.systemKey));
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const action = form.elements.action.value;
const body = {
recurrence: recurrenceOf(form),
parameters: parametersOf(form, action),
priority: form.elements.priority.value,
catchUp: form.elements.catchUp.checked,
enabled: form.elements.enabled.checked,
};
if (!system) Object.assign(body, { name: form.elements.name.value.trim(), action });
try {
if (editing) await api.put(`/api/v1/schedules/${schedule.id}`, body);
else await api.post("/api/v1/schedules", body);
closeSide();
toast(t("Admin.Common.Saved"));
await load();
} catch (err) {
fieldError(form, err);
}
});
(form.querySelector("input:not([disabled]), select:not([disabled])"))?.focus();
}
/** The fields of the recurrence's kind, filled from <paramref name="r"/> (values of the other kinds are kept for a switch back). */
function drawRecurrence(form, r) {
const host = form.querySelector("#recurrence");
const time = `<label><span data-i18n="Admin.Schedules.Time"></span>
<input class="input narrow num" type="time" name="time" required value="${attr(r.time ?? "03:00")}" title="${attr(t("Admin.Schedules.Time.Tip", zone))}"></label>`;
switch (r.kind) {
case "every":
host.innerHTML = `<label><span data-i18n="Admin.Schedules.Interval"></span><span class="inline">
<input class="input narrow num" type="number" name="every" min="1" value="${attr(r.every ?? 1)}" data-i18n-title="Admin.Schedules.Interval.Tip">
<select class="input narrow" name="unit" data-i18n-title="Admin.Schedules.Unit.Tip">${UNITS.map((u) =>
`<option value="${u}" ${u === r.unit ? "selected" : ""}>${escapeHtml(t(`Admin.Schedules.Unit.${cap(u)}`))}</option>`).join("")}</select></span></label>`;
break;
case "weekly":
host.innerHTML = `<fieldset><legend data-i18n="Admin.Schedules.Days"></legend><div class="days">${DAYS.map((d) => `<label class="check">
<input type="checkbox" name="day-${d}" ${(r.days ?? []).includes(d) ? "checked" : ""} title="${attr(t("Admin.Schedules.Day.Tip", dayName(d, "long")))}"><span>${escapeHtml(dayName(d))}</span></label>`).join("")}</div></fieldset>${time}`;
break;
case "monthly":
host.innerHTML = `<label><span data-i18n="Admin.Schedules.DayOfMonth"></span>
<input class="input narrow num" type="number" name="dayOfMonth" min="1" max="28" value="${attr(r.dayOfMonth ?? 1)}" data-i18n-title="Admin.Schedules.DayOfMonth.Tip"></label>${time}`;
break;
default:
host.innerHTML = time;
}
applyStrings(host);
}
/** The parameters <paramref name="action"/> reads, filled from <paramref name="p"/>. */
function drawParameters(form, action, p, systemKey) {
const host = form.querySelector("#parameters");
const lockedAge = LOCKED_AGES[systemKey];
const ageLocked = lockedAge && locked.some((l) => l.toLowerCase() === lockedAge[0].toLowerCase());
host.innerHTML = (PARAMETERS[action] ?? []).map((name) => {
const key = `Admin.Schedules.Param.${PARAM_KEYS[`${action}.${name}`]}`;
if (name === "steps") {
return `<fieldset><legend data-i18n="${key}"></legend>${steps.map((step) => `<label class="check">
<input type="checkbox" name="step-${attr(step)}" value="${attr(step)}" ${(p.steps ?? []).includes(step) ? "checked" : ""} title="${attr(stepTip(step))}"><span>${escapeHtml(stepLabel(step))}</span></label>`).join("")}</fieldset>`;
}
if (name in NUMBERS) {
const lock = name === "olderThanDays" && ageLocked ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", lockedAge[1]))}"` : `data-i18n-title="${key}.Tip"`;
return `<label><span data-i18n="${key}"></span><input class="input narrow num" type="number" name="${name}" ${NUMBERS[name]} value="${attr(p[name] ?? 0)}" ${lock}></label>`;
}
return `<label class="check"><input type="checkbox" name="${name}" ${p[name] ? "checked" : ""} data-i18n-title="${key}.Tip"><span data-i18n="${key}"></span></label>`;
}).join("");
applyStrings(host);
}
/** An API failure on the side form: the field it concerns gets the error border, the message and the focus; a toast announces it. */
function fieldError(form, err) {
const field = fieldOf(form, err.code === "setting_locked" ? "parameters.olderThanDays" : err.code === "invalid_schedule" ? err.details : null);
const message = field && err.code === "invalid_schedule" ? invalidText(field) : errorText(err);
if (field) {
markInvalid(field, message);
field.focus();
}
toast(message, true);
}
setMeta("");
onEvent((e) => {
// A schedule's run queues jobs; their states change the Last result column.
if (e.type === "jobState") {
clearTimeout(timer);
timer = setTimeout(load, 800);
}
});
await load();
}
/** The recurrence the form describes (RecurrenceDto). */
function recurrenceOf(form) {
const kind = form.elements.kind.value;
return { kind, ...shownFields(form, kind) };
}
/** The values of the recurrence fields the form shows for <paramref name="kind"/>. */
function shownFields(form, kind) {
const el = form.elements;
switch (kind) {
case "every": return { every: Number(el.every.value), unit: el.unit.value };
case "weekly": return { time: el.time.value, days: DAYS.filter((d) => el[`day-${d}`].checked) };
case "monthly": return { time: el.time.value, dayOfMonth: Number(el.dayOfMonth.value) };
default: return { time: el.time.value };
}
}
/** The parameters of <paramref name="action"/> the form holds (disabled fields included: an age limit an environment variable fixes). */
function parametersOf(form, action) {
const parameters = {};
for (const name of PARAMETERS[action] ?? []) {
if (name === "steps") parameters.steps = [...form.querySelectorAll('input[name^="step-"]')].filter((b) => b.checked).map((b) => b.value);
else if (name in NUMBERS) parameters[name] = Number(form.elements[name].value);
else parameters[name] = form.elements[name].checked;
}
return parameters;
}
/** The form field an invalid API field (<c>recurrence</c>, <c>parameters.percent</c>…) belongs to. */
function fieldOf(form, apiField) {
if (!apiField) return null;
const el = form.elements;
if (apiField === "recurrence") {
const kind = el.kind.value;
if (kind === "every") return el.every;
if (kind === "weekly" && !DAYS.some((d) => el[`day-${d}`].checked)) return el["day-mon"];
if (kind === "monthly" && !(Number(el.dayOfMonth.value) >= 1 && Number(el.dayOfMonth.value) <= 28)) return el.dayOfMonth;
return el.time;
}
if (apiField === "parameters.steps") return form.querySelector('input[name^="step-"]');
const name = apiField.startsWith("parameters.") ? apiField.slice("parameters.".length) : apiField;
return el[name] ?? null;
}
function actionTip(action) {
const key = `Admin.Schedules.Action.${pascal(action)}.Tip`;
return has(key) ? t(key) : action;
}
/** Why the server cannot run an action (ScheduleUnavailable codes; unknown codes read "not available here"). */
function reasonTip(reason) {
const key = `Admin.Schedules.Reason.${pascal(reason ?? "")}.Tip`;
return has(key) ? t(key) : t("Admin.Schedules.Reason.Unknown.Tip");
}
function stepLabel(step) {
const key = `Admin.Schedules.Step.${pascal(step)}`;
return has(key) ? t(key) : step;
}
function stepTip(step) {
const key = `Admin.Schedules.Step.${pascal(step)}.Tip`;
return has(key) ? t(key) : step;
}
/** An instant in the server's time zone (schedule times are its wall-clock times); in the browser's when the zone is unknown here. */
function zonedTime(iso, zone) {
if (!iso) return "—";
const options = { dateStyle: "short", timeStyle: "short" };
try {
return new Intl.DateTimeFormat(culture(), { ...options, timeZone: zone }).format(new Date(iso));
} catch {
return new Intl.DateTimeFormat(culture(), options).format(new Date(iso));
}
}
/** "03:00" as the panel's language writes a time of day. */
function timeText(hhmm) {
const [h, m] = String(hhmm ?? "").split(":").map(Number);
if (!Number.isFinite(h) || !Number.isFinite(m)) return String(hhmm ?? "");
return new Intl.DateTimeFormat(culture(), { timeStyle: "short", timeZone: "UTC" }).format(Date.UTC(2001, 0, 1, h, m));
}
function dayName(day, style = "short") {
return new Intl.DateTimeFormat(culture(), { weekday: style, timeZone: "UTC" }).format(Date.UTC(2001, 0, 1 + DAYS.indexOf(day)));
}
function dayList(days) {
const names = DAYS.filter((d) => days.includes(d)).map((d) => dayName(d));
try {
return new Intl.ListFormat(culture(), { style: "short", type: "conjunction" }).format(names);
} catch {
return names.join(", ");
}
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}