Files
Chronos/src/Chronos.Server/Admin/web/schedules.js
T
Alby96andClaude Opus 5.5 e6e69782ed fix(server): a locked audit retention also fixes the audit step and the switch
The audit retention in force ignored the audit clean-up's steps: with the
audit step unticked nothing was deleted, yet Settings › Logs still showed the
age limit. It is now 0 without that step, and setting a limit (Settings › Logs
or CHRONOS_AUDIT_RETENTION_DAYS at start) ticks the step again, so a saved or
fixed retention always takes effect. While the variable fixes a limit above 0,
an edit that drops the step is 409 setting_locked like turning the schedule off.

The admin panel's Scheduled tab disables what the variable fixes (the row's
switch, the form's Enabled and audit step, the age limit) with the locked
tooltip, and points a setting_locked refusal at the field actually refused.

The Copies kept tooltips now say the backups folder keeps as many copies as
the backup schedule that keeps the most; the LastDone and Newest comments
state the real first-copy rule; Keep audit is documented last-writer-wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:39:49 +01:00

624 lines
32 KiB
JavaScript

// 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, its next
// run, its last result (every time in the server's time zone) 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, 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"];
/** The unit letters of an interval's server code (every:10m). */
const UNIT_CODES = { m: "minutes", h: "hours", d: "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): the setting,
* its variable and the steps the limit deletes with (ServerScheduleHost.AgedSteps).
*/
const LOCKED_AGES = { "audit-cleanup": { setting: "AuditRetentionDays", variable: "CHRONOS_AUDIT_RETENTION_DAYS", steps: ["audit"] } };
/** 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 ?? "";
}
}
/**
* The recurrence a server code describes (ScheduleRecurrence.Format: every:10m, daily:03:00, weekly:mon,thu@02:30,
* monthly:1@04:00), in the API's shape for recurrenceText; null for anything else.
*/
export function parseRecurrence(code) {
const match = /^(every|daily|weekly|monthly):(.+)$/.exec(String(code ?? ""));
if (!match) return null;
const [, kind, rest] = match;
const isTime = (s) => /^\d{2}:\d{2}$/.test(s ?? "");
if (kind === "every") {
const every = /^(\d+)([mhd])$/.exec(rest);
return every ? { kind, every: Number(every[1]), unit: UNIT_CODES[every[2]] } : null;
}
if (kind === "daily") return isTime(rest) ? { kind, time: rest } : null;
const [what, time] = rest.split("@");
if (!isTime(time)) return null;
if (kind === "weekly") {
const days = what.split(",");
return days.every((d) => DAYS.includes(d)) ? { kind, days, time } : null;
}
return /^\d+$/.test(what) ? { kind, dayOfMonth: Number(what), time } : null;
}
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 ?? [];
// A schedule deleted meanwhile (here or by another administrator), or the one a job of the Queue tab links to after
// its deletion, is simply not shown: its runs are not asked for.
for (const id of expanded) {
if (!find(id)) forget(id);
}
if (focusSchedule && !find(focusSchedule)) focusSchedule = null;
// 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]));
// One schedule's runs that cannot be read (deleted since the list) close it; the table is drawn all the same.
await Promise.all([...expanded].map((id) => loadRuns(id).catch(() => forget(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);
}
/**
* What an environment variable fixes on the system schedule <paramref name="systemKey"/> whose age limit is
* <paramref name="days"/> (LOCKED_AGES), with the attributes of its fixed controls; null when nothing is fixed. While the
* limit deletes (more than 0 days) its switch and the steps it deletes with are fixed too (ScheduleEndpoints.ChangesLocked).
*/
function ageLock(systemKey, days) {
const age = LOCKED_AGES[systemKey];
if (!age || !locked.some((l) => l.toLowerCase() === age.setting.toLowerCase())) return null;
return { ...age, deletes: days > 0, attrs: `disabled title="${attr(t("Admin.Settings.Locked.Tip", age.variable))}"` };
}
/** Closes a schedule's runs and drops them. */
function forget(id) {
expanded.delete(id);
runs.delete(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);
const lock = ageLock(s.systemKey, s.parameters?.olderThanDays ?? 0);
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))}" ${lock?.deletes ? lock.attrs : `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(zonedShort(s.lastRun, zone))}</span>`;
const tip = `${outcomeTip(s.lastOutcome)} · ${zonedDateTime(s.lastRun, zone)}`;
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(zonedDateTime(j.created, zone))}</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) {
forget(id);
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}`);
forget(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 lock = editing ? ageLock(schedule.systemKey, schedule.parameters?.olderThanDays ?? 0) : null;
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" : ""} ${lock?.deletes ? lock.attrs : `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, schedule);
}
});
(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 lock = ageLock(systemKey, p.olderThanDays ?? 0);
host.innerHTML = (PARAMETERS[action] ?? []).map((name) => {
const key = `Admin.Schedules.Param.${PARAM_KEYS[`${action}.${name}`]}`;
if (name === "steps") {
const tip = (step) => lock?.deletes && lock.steps.includes(step) ? lock.attrs : `title="${attr(stepTip(step))}"`;
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" : ""} ${tip(step)}><span>${escapeHtml(stepLabel(step))}</span></label>`).join("")}</fieldset>`;
}
if (name in NUMBERS) {
const fixed = name === "olderThanDays" && lock ? lock.attrs : `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)}" ${fixed}></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 of <paramref name="schedule"/> (null for a new one): the field it concerns gets the error
* border, the message and the focus; a toast announces it.
*/
function fieldError(form, err, schedule) {
const field = err.code === "setting_locked" ? lockedField(form, schedule) : fieldOf(form, 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 changed or ran (also a run that queued nothing, or an edit by another administrator), or a job it queued
// changed state (the Last result column); the burst of one pass is read once.
if (e.type === "jobState" || e.type === "scheduleChanged") {
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;
}
/**
* The form field a <c>setting_locked</c> refusal concerns, in the server's order (ScheduleEndpoints.ChangesLocked): the
* switch turned off while the limit deletes, the age limit changed, a step the limit deletes with unticked; else the age limit.
*/
function lockedField(form, schedule) {
const el = form.elements;
const days = schedule?.parameters?.olderThanDays ?? 0;
if (days > 0 && !el.enabled.checked) return el.enabled;
if (el.olderThanDays && Number(el.olderThanDays.value) !== days) return el.olderThanDays;
const step = days > 0 ? (LOCKED_AGES[schedule?.systemKey]?.steps ?? []).map((s) => el[`step-${s}`]).find((box) => box && !box.checked) : null;
return step ?? el.olderThanDays ?? 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, as every time of this tab is ("Times in …": schedule times are its wall-clock
* times); in the browser's when the zone is unknown here.
*/
function zoned(iso, zone, options) {
const date = new Date(iso);
try {
return new Intl.DateTimeFormat(culture(), { ...options, timeZone: zone }).format(date);
} catch {
return new Intl.DateTimeFormat(culture(), options).format(date);
}
}
function zonedTime(iso, zone) {
return iso ? zoned(iso, zone, { dateStyle: "short", timeStyle: "short" }) : "—";
}
function zonedDateTime(iso, zone) {
return iso ? zoned(iso, zone, { dateStyle: "short", timeStyle: "medium" }) : "—";
}
/** Like formatTime in the server's time zone: the time when the instant falls on today there, else the date. */
function zonedShort(iso, zone) {
if (!iso) return "—";
const day = (instant) => zoned(instant, zone, { dateStyle: "short" });
return zoned(iso, zone, day(iso) === day(Date.now()) ? { timeStyle: "short" } : { dateStyle: "medium" });
}
/** "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);
}