Repository Public
1"use client";2import { useQueryClient } from "@tanstack/react-query";3import { useMemo, useRef, useState } from "react";4import { apiPatch, apiPost, type Schemas } from "@/api/client";5import { ApiError } from "@/api/errors";6import { invalidatePaths, useApiQuery } from "@/api/query";7import { useNodeOptions } from "@/features/shared/nodes";8import { useI18n } from "@/i18n";9import { fromLocalInput, localTimeZone } from "@/lib/format";10import { IdempotencyIntent } from "@/lib/idempotency";11import { initialValues, schemaToFields, validateForm, type FieldError, type FormValues } from "@/lib/schemaForm";12import { Banner, Button, Combobox, Dialog, ErrorState, SchemaForm, SelectField, Skeleton, Switch, TextAreaField, TextField, useErrorMessage, useToast } from "@/ui";13import { EMPTY_PLACEMENT, fromPlacement, parseDependencies, splitInterval, toPlacement, toSeconds, type IntervalUnit, type PlacementDraft } from "./interval";1415type Template = Schemas["JobTemplate"];1617function PlacementFields({ value, onChange, disabled, template }: { value: PlacementDraft; onChange: (v: PlacementDraft) => void; disabled: boolean; template: Template | undefined }) {18 const { t } = useI18n();19 const nodes = useNodeOptions();20 // a template may be restricted to some nodes: only those are offered21 const options = useMemo(() => (template?.node_ids ? nodes.options.filter((o) => template.node_ids?.includes(o.value)) : nodes.options), [nodes.options, template]);22 return (23 <fieldset className="mcc-fieldset" disabled={disabled}>24 <legend>{t("jobs.placement.title")}</legend>25 <p className="mcc-hint">{t("jobs.placement.hint")}</p>26 <Combobox label={t("jobs.placement.node")} options={options} value={value.nodeId} onChange={(nodeId) => onChange({ ...value, nodeId })} placeholder={t("jobs.placement.anyNode")} {...(nodes.error ? { hint: t("jobs.placement.nodesUnavailable") } : {})} />27 <div className="mcc-form-row">28 <TextField label={t("jobs.placement.site")} value={value.site} onChange={(site) => onChange({ ...value, site })} />29 <TextField label={t("jobs.placement.role")} value={value.role} onChange={(role) => onChange({ ...value, role })} />30 </div>31 <TextField label={t("jobs.placement.tags")} hint={t("jobs.placement.tagsHint")} value={value.tags} onChange={(tags) => onChange({ ...value, tags })} mono />32 </fieldset>33 );34}3536function TemplateSelect({ templates, value, onChange, disabled }: { templates: Template[]; value: string; onChange: (v: string) => void; disabled?: boolean }) {37 const { t, fmt } = useI18n();38 const current = templates.find((x) => x.name === value);39 return (40 <>41 <SelectField label={t("jobs.template")} required value={value} onChange={onChange} disabled={disabled}42 options={[{ value: "", label: t("ui.schema.choose") }, ...templates.map((x) => ({ value: x.name, label: x.available ? x.title : `${x.title} — ${t("jobs.templateUnavailable")}`, disabled: !x.available }))]}43 hint={current?.description} />44 {current ? <p className="mcc-hint">{t("jobs.templateLimits", { timeout: fmt.duration(current.timeout_s), attempts: current.max_attempts })}</p> : null}45 </>46 );47}4849function FormError({ error }: { error: ApiError }) {50 const explain = useErrorMessage();51 const m = explain(error);52 return <Banner tone={error.status === 422 || error.status === 409 ? "warning" : "critical"} role="alert"><strong data-testid="job-form-error" data-code={error.code}>{m.title}</strong>{m.detail ? <> — {m.detail}</> : null}</Banner>;53}54const asApiError = (e: unknown) => (e instanceof ApiError ? e : new ApiError({ status: 0, code: "network", message: "network" }));5556/** Submit a job from a template: parameters form generated from the template schema, placement, attempts. */57export function SubmitJobDialog({ onClose, onCreated, initialTemplate }: { onClose: () => void; onCreated: (job: Schemas["Job"]) => void; initialTemplate?: string }) {58 const { t } = useI18n();59 const toast = useToast();60 const qc = useQueryClient();61 const templates = useApiQuery("/job-templates", undefined, { staleTime: 60_000 });62 const [name, setName] = useState(initialTemplate ?? "");63 const [valuesBy, setValuesBy] = useState<Record<string, FormValues>>({});64 const [placement, setPlacement] = useState<PlacementDraft>(EMPTY_PLACEMENT);65 const [attempts, setAttempts] = useState("1");66 const [deps, setDeps] = useState("");67 const [errors, setErrors] = useState<FieldError[]>([]);68 const [local, setLocal] = useState<{ template?: boolean; attempts?: boolean; deps?: string }>({});69 const [busy, setBusy] = useState(false);70 const [failure, setFailure] = useState<ApiError | null>(null);71 const intent = useRef(new IdempotencyIntent());7273 const template = templates.data?.items.find((x) => x.name === name);74 const fields = useMemo(() => schemaToFields(template?.params_schema), [template]);75 const values = valuesBy[name] ?? initialValues(fields);76 const maxAttempts = Math.min(5, template?.max_attempts ?? 5);7778 const submit = async () => {79 const result = validateForm(fields, values);80 const n = Number(attempts);81 const d = parseDependencies(deps);82 const depsProblem = d.invalid.length > 0 ? t("jobs.submit.depsInvalid", { ids: d.invalid.join(", ") }) : d.ids.length > 16 ? t("jobs.submit.depsTooMany") : undefined;83 const badAttempts = !Number.isInteger(n) || n < 1 || n > maxAttempts;84 setErrors(result.errors);85 setLocal({ template: !template, attempts: badAttempts, ...(depsProblem ? { deps: depsProblem } : {}) });86 if (!template || badAttempts || depsProblem || result.errors.length > 0) return;87 const p = toPlacement(placement);88 const body: Schemas["CreateJobRequest"] = {89 template: template.name,90 max_attempts: n,91 ...(Object.keys(result.params).length > 0 ? { params: result.params } : {}),92 ...(p ? { placement: p } : {}),93 ...(d.ids.length > 0 ? { depends_on: d.ids } : {}),94 };95 setBusy(true);96 setFailure(null);97 try {98 // same key while the same body is retried (network error, step-up); a changed body is a new intent99 const job = await apiPost("/jobs", { body, headers: { "Idempotency-Key": intent.current.keyFor(body) } });100 intent.current.complete();101 await invalidatePaths(qc, "/jobs");102 toast({ tone: "ok", title: t("jobs.submit.done", { template: template.title }) });103 onCreated(job);104 } catch (e) {105 setBusy(false);106 setFailure(asApiError(e));107 }108 };109110 return (111 <Dialog open onClose={onClose} title={t("jobs.submit.title")} description={t("jobs.submit.body")} size="wide" dismissable={!busy}112 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" icon="play" loading={busy} disabled={!!template && !template.available} onClick={() => void submit()} data-testid="job-submit-confirm">{t("jobs.submit.run")}</Button></>}>113 {templates.isLoading ? <Skeleton width="60" label={t("common.loading")} /> : null}114 {templates.isError ? <ErrorState error={templates.error} onRetry={() => void templates.refetch()} compact /> : null}115 {templates.data ? (116 <div className="mcc-form" data-testid="job-submit-form">117 <TemplateSelect templates={templates.data.items} value={name} onChange={(v) => { setName(v); setErrors([]); }} disabled={busy} />118 {local.template ? <span className="mcc-error-text" role="alert">{t("jobs.submit.chooseTemplate")}</span> : null}119 {template ? (120 <>121 <section className="stack-sm" aria-label={t("jobs.params")}>122 <h3>{t("jobs.params")}</h3>123 <SchemaForm schema={template.params_schema} values={values} onChange={(v) => setValuesBy((all) => ({ ...all, [name]: v }))} errors={errors} disabled={busy} emptyText={t("jobs.noParams")} />124 </section>125 <PlacementFields value={placement} onChange={setPlacement} disabled={busy} template={template} />126 <div className="mcc-form-row">127 <TextField label={t("jobs.maxAttempts")} hint={t("jobs.maxAttemptsHint", { max: maxAttempts })} inputMode="numeric" mono value={attempts} onChange={setAttempts} disabled={busy} error={local.attempts ? t("jobs.maxAttemptsHint", { max: maxAttempts }) : undefined} />128 </div>129 <TextAreaField label={t("jobs.dependsOn")} hint={t("jobs.dependsOnHint")} value={deps} onChange={setDeps} disabled={busy} spellCheck={false} error={local.deps} />130 </>131 ) : null}132 {failure ? <FormError error={failure} /> : null}133 </div>134 ) : null}135 </Dialog>136 );137}138139const UNITS: IntervalUnit[] = ["minutes", "hours", "days"];140141/** Stored parameters back into form values (numbers and JSON as text, as the generated form expects). */142function editableParams(fields: ReturnType<typeof schemaToFields>, params: Record<string, unknown>): FormValues {143 const out: FormValues = {};144 for (const f of fields) {145 const v = params[f.name];146 if (v === undefined) continue;147 out[f.name] = f.kind === "json" ? JSON.stringify(v) : f.kind === "integer" || f.kind === "number" ? String(v) : v;148 }149 return out;150}151152/** Create or edit a recurring schedule. The template of an existing schedule cannot change (contract). */153export function ScheduleDialog({ schedule, onClose }: { schedule?: Schemas["JobSchedule"]; onClose: () => void }) {154 const { t } = useI18n();155 const toast = useToast();156 const qc = useQueryClient();157 const templates = useApiQuery("/job-templates", undefined, { staleTime: 60_000 });158 const start = schedule ? splitInterval(schedule.every_seconds) : { value: 1, unit: "hours" as IntervalUnit };159 const [label, setLabel] = useState(schedule?.name ?? "");160 const [name, setName] = useState(schedule?.template ?? "");161 const [every, setEvery] = useState(String(start.value));162 const [unit, setUnit] = useState<IntervalUnit>(start.unit);163 const [first, setFirst] = useState("");164 const [enabled, setEnabled] = useState(schedule?.enabled ?? true);165 const [placement, setPlacement] = useState<PlacementDraft>(fromPlacement(schedule?.placement));166 const [valuesBy, setValuesBy] = useState<Record<string, FormValues>>({});167 const [errors, setErrors] = useState<FieldError[]>([]);168 const [local, setLocal] = useState<{ label?: boolean; template?: boolean; every?: boolean; first?: boolean }>({});169 const [busy, setBusy] = useState(false);170 const [failure, setFailure] = useState<ApiError | null>(null);171172 const template = templates.data?.items.find((x) => x.name === name);173 const fields = useMemo(() => schemaToFields(template?.params_schema), [template]);174 const values = valuesBy[name] ?? { ...initialValues(fields), ...(schedule && schedule.template === name ? editableParams(fields, schedule.params) : {}) };175176 const save = async () => {177 const result = validateForm(fields, values);178 const seconds = toSeconds(every, unit);179 const firstIso = first ? fromLocalInput(first) : null;180 const problems = { label: label.trim() === "", template: !template, every: seconds === null, first: first !== "" && firstIso === null };181 setErrors(result.errors);182 setLocal(problems);183 if (problems.label || !template || seconds === null || problems.first || result.errors.length > 0) return;184 const p = toPlacement(placement);185 setBusy(true);186 setFailure(null);187 try {188 if (schedule) {189 await apiPatch("/job-schedules/{id}", { path: { id: schedule.id }, body: { name: label.trim(), every_seconds: seconds, enabled, params: result.params, placement: p ?? {} } });190 } else {191 await apiPost("/job-schedules", { body: { name: label.trim(), template: template.name, every_seconds: seconds, enabled, ...(Object.keys(result.params).length > 0 ? { params: result.params } : {}), ...(p ? { placement: p } : {}), ...(firstIso ? { first_run_at: firstIso } : {}) } });192 }193 await invalidatePaths(qc, "/job-schedules");194 toast({ tone: "ok", title: schedule ? t("jobs.schedule.updated") : t("jobs.schedule.created") });195 onClose();196 } catch (e) {197 setBusy(false);198 setFailure(asApiError(e));199 }200 };201202 return (203 <Dialog open onClose={onClose} title={schedule ? t("jobs.schedule.editTitle", { name: schedule.name }) : t("jobs.schedule.createTitle")} size="wide" dismissable={!busy}204 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void save()} data-testid="schedule-save">{schedule ? t("common.save") : t("common.create")}</Button></>}>205 {templates.isLoading ? <Skeleton width="60" label={t("common.loading")} /> : null}206 {templates.isError ? <ErrorState error={templates.error} onRetry={() => void templates.refetch()} compact /> : null}207 {templates.data ? (208 <div className="mcc-form" data-testid="schedule-form">209 <TextField label={t("common.name")} required value={label} onChange={setLabel} maxLength={80} disabled={busy} error={local.label ? t("ui.schema.required", { limit: "" }) : undefined} />210 <TemplateSelect templates={templates.data.items} value={name} onChange={(v) => { setName(v); setErrors([]); }} disabled={busy || !!schedule} />211 {local.template ? <span className="mcc-error-text" role="alert">{t("jobs.submit.chooseTemplate")}</span> : null}212 <div className="mcc-form-row">213 <TextField label={t("jobs.schedule.every")} required inputMode="numeric" mono value={every} onChange={setEvery} disabled={busy} error={local.every ? t("jobs.schedule.everyInvalid") : undefined} />214 <SelectField label={t("jobs.schedule.unit")} value={unit} onChange={setUnit} disabled={busy} options={UNITS.map((u) => ({ value: u, label: t(`jobs.schedule.units.${u}`) }))} />215 </div>216 {!schedule ? <TextField label={t("jobs.schedule.firstRun")} hint={t("jobs.schedule.firstRunHint", { zone: localTimeZone() })} type="datetime-local" value={first} onChange={setFirst} disabled={busy} error={local.first ? t("ui.schema.pattern", { limit: "" }) : undefined} /> : null}217 {template ? (218 <section className="stack-sm" aria-label={t("jobs.params")}>219 <h3>{t("jobs.params")}</h3>220 <SchemaForm schema={template.params_schema} values={values} onChange={(v) => setValuesBy((all) => ({ ...all, [name]: v }))} errors={errors} disabled={busy} emptyText={t("jobs.noParams")} />221 </section>222 ) : null}223 <PlacementFields value={placement} onChange={setPlacement} disabled={busy} template={template} />224 <Switch label={t("jobs.schedule.enabled")} checked={enabled} onChange={setEnabled} disabled={busy} />225 {failure ? <FormError error={failure} /> : null}226 </div>227 ) : null}228 </Dialog>229 );230}231