import { useMemo, useState } from 'react';
import {
Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, MenuItem, Stack, Table, TableBody,
TableCell, TableContainer, TableHead, TableRow, TextField, ToggleButton, ToggleButtonGroup, Typography,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import HistoryIcon from '@mui/icons-material/History';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import SaveIcon from '@mui/icons-material/Save';
import ScheduleIcon from '@mui/icons-material/Schedule';
import StopIcon from '@mui/icons-material/Stop';
import CloseIcon from '@mui/icons-material/Close';
import { EmptyState } from '@/components/EmptyState';
import { LoadingBanner } from '@/components/LoadingBanner';
import { PageHeader } from '@/components/PageHeader';
import { SectionPaper as Paper } from '@/components/SectionPaper';
import { formatDateTime, formatNumber } from '@/components/meta/format';
import { useFeatureUi } from '@/i18n/useUi';
import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider';
import {
useJobRuns, useJobs, useRunJob, useSaveSchedule, useStartJob, useStopJob, type JobItem, type ScheduleBody,
} from './api';
import strings from './strings';
const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
/** Digits typed -> HH:mm (always 24-hour, whatever the browser language is). */
function maskTime(raw: string): string {
const d = raw.replace(/\D/g, '').slice(0, 4);
return d.length <= 2 ? d : `${d.slice(0, 2)}:${d.slice(2)}`;
}
/** minutes -> the number and unit shown (whole hours are shown as hours). */
function toUnit(minutes: number): { value: string; unit: 'minutes' | 'hours' } {
return minutes >= 60 && minutes % 60 === 0 ? { value: String(minutes / 60), unit: 'hours' } : { value: String(minutes), unit: 'minutes' };
}
function statusColor(status: string | null): 'success' | 'error' | 'info' | 'default' {
return status === 'OK' ? 'success' : status === 'FAILED' ? 'error' : status === 'RUNNING' ? 'info' : 'default';
}
export function JobsPage() {
const { t } = useFeatureUi(strings);
const jobs = useJobs();
return (
<>
{jobs.isLoading ? (
) : jobs.error ? (
{jobs.error instanceof Error ? jobs.error.message : t('jobs.loadError')}
) : (jobs.data ?? []).length === 0 ? (
) : (
{/* remount when the saved schedule changes so the draft follows the server, not every 10-second refresh */}
{(jobs.data ?? []).map((j) => (
))}
)}
>
);
}
function JobCard({ job }: { job: JobItem }) {
const { t, lang } = useFeatureUi(strings);
const confirm = useConfirm();
const toast = useToast();
const save = useSaveSchedule(t('jobs.saved'));
const start = useStartJob(t('jobs.startedOk'));
const stop = useStopJob(t('jobs.stoppedOk'));
const run = useRunJob();
const first = toUnit(job.intervalMinutes);
const [type, setType] = useState<'INTERVAL' | 'DAILY'>(job.scheduleType);
const [amount, setAmount] = useState(first.value);
const [unit, setUnit] = useState<'minutes' | 'hours'>(first.unit);
const [times, setTimes] = useState(job.dailyTimes);
const [newTime, setNewTime] = useState('');
const [showHistory, setShowHistory] = useState(false);
const minutes = Number(amount) * (unit === 'hours' ? 60 : 1);
const intervalOk = Number.isInteger(minutes) && minutes >= 1 && minutes <= 7 * 24 * 60;
const scheduleOk = type === 'INTERVAL' ? intervalOk : times.length > 0;
const body: ScheduleBody = type === 'INTERVAL'
? { scheduleType: 'INTERVAL', intervalMinutes: minutes, dailyTimes: null }
: { scheduleType: 'DAILY', intervalMinutes: null, dailyTimes: times };
const dirty = type !== job.scheduleType
|| (type === 'INTERVAL' ? minutes !== job.intervalMinutes : times.join(',') !== job.dailyTimes.join(','));
const busy = save.isPending || start.isPending || stop.isPending || run.isPending;
const title = lang === 'ar' ? job.titleAr : job.titleEn;
const description = lang === 'ar' ? job.descriptionAr : job.descriptionEn;
const state = job.running ? 'running' : job.enabled ? 'started' : 'stopped';
const addTime = () => {
if (!TIME_RE.test(newTime) || times.includes(newTime)) return;
setTimes([...times, newTime].sort());
setNewTime('');
};
const saveOnly = () => save.mutate({ key: job.key, body });
// starting uses the schedule on screen: an unsaved change is saved first
const startJob = () => {
if (!dirty) { start.mutate(job.key); return; }
save.mutate({ key: job.key, body }, { onSuccess: () => start.mutate(job.key) });
};
const runNow = async () => {
if (!(await confirm({ message: t('jobs.runNowConfirm') }))) return;
run.mutate(job.key, { onSuccess: (r) => (r.success ? toast.success(r.message) : toast.warning(r.message)) });
};
return (
{title}
{job.key}
{description}
{t('jobs.lastRun')}
{job.lastStart ? (
{formatDateTime(job.lastStart, lang)}
{job.lastStatus && }
{job.lastCount !== null && {t('jobs.rows')}: {formatNumber(job.lastCount, lang)}}
{job.lastMessage && {job.lastMessage}}
) : (
{t('jobs.never')}
)}
{t('jobs.nextRun')}
{job.nextRun ? formatDateTime(job.nextRun, lang) : '-'}
{t('jobs.schedule')}
v && setType(v)}>
{t('jobs.type.interval')}
{t('jobs.type.daily')}
{type === 'INTERVAL' ? (
{t('jobs.every')}
setAmount(e.target.value.replace(/\D/g, '').slice(0, 5))}
slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }}
/>
setUnit(e.target.value as 'minutes' | 'hours')}>
) : (
{t('jobs.times')}
{times.map((x) => (
{x}} onDelete={() => setTimes(times.filter((y) => y !== x))} />
))}
setNewTime(maskTime(e.target.value))}
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addTime(); } }}
slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr', maxLength: 5 } }}
/>
} disabled={!TIME_RE.test(newTime) || times.includes(newTime)} onClick={addTime}>
{t('jobs.addTime')}
{times.length === 0 && {t('jobs.noTimes')}}
)}
} disabled={busy || !scheduleOk || !dirty} onClick={saveOnly}>{t('jobs.save')}
{job.enabled ? (
} disabled={busy} onClick={() => stop.mutate(job.key)}>{t('jobs.stop')}
) : (
} disabled={busy || !scheduleOk} onClick={startJob}>
{dirty ? t('jobs.saveStart') : t('jobs.start')}
)}
} disabled={busy || job.running} onClick={() => void runNow()}>{t('jobs.runNow')}
} onClick={() => setShowHistory(true)}>{t('jobs.history')}
{showHistory && setShowHistory(false)} />}
);
}
function HistoryDialog({ jobKey, title, onClose }: { jobKey: string; title: string; onClose: () => void }) {
const { t, lang } = useFeatureUi(strings);
const runs = useJobRuns(jobKey);
const rows = useMemo(() => runs.data ?? [], [runs.data]);
return (
);
}