NTP_V2/web/src/features/jobs/pages.tsx

266 lines
13 KiB
TypeScript

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 (
<>
<PageHeader title={t('jobs.title')} subtitle={t('jobs.subtitle')} />
{jobs.isLoading ? (
<LoadingBanner />
) : jobs.error ? (
<Alert severity="error">{jobs.error instanceof Error ? jobs.error.message : t('jobs.loadError')}</Alert>
) : (jobs.data ?? []).length === 0 ? (
<EmptyState title={t('jobs.empty')} />
) : (
<Stack spacing={2}>
{/* remount when the saved schedule changes so the draft follows the server, not every 10-second refresh */}
{(jobs.data ?? []).map((j) => (
<JobCard key={`${j.key}|${j.scheduleType}|${j.intervalMinutes}|${j.dailyTimes.join(',')}`} job={j} />
))}
</Stack>
)}
</>
);
}
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<string[]>(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 (
<Paper sx={{ p: 2 }}>
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>
<ScheduleIcon color="primary" />
<Box sx={{ flex: 1, minWidth: 220 }}>
<Typography sx={{ fontWeight: 700 }}>{title}</Typography>
<Typography variant="caption" color="text.secondary" dir="ltr" sx={{ display: 'block', textAlign: 'start' }}>{job.key}</Typography>
</Box>
<Chip
label={t(`jobs.state.${state}` as const)}
color={state === 'running' ? 'info' : state === 'started' ? 'success' : 'default'}
variant={state === 'stopped' ? 'outlined' : 'filled'}
/>
</Stack>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>{description}</Typography>
<Box sx={{ display: 'grid', gap: 2, mt: 2, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
<Box>
<Typography variant="caption" color="text.secondary">{t('jobs.lastRun')}</Typography>
{job.lastStart ? (
<Stack spacing={0.5}>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
<Typography dir="ltr">{formatDateTime(job.lastStart, lang)}</Typography>
{job.lastStatus && <Chip size="small" label={t(`jobs.status.${job.lastStatus}` as 'jobs.status.OK')} color={statusColor(job.lastStatus)} />}
{job.lastCount !== null && <Typography variant="body2">{t('jobs.rows')}: <span dir="ltr">{formatNumber(job.lastCount, lang)}</span></Typography>}
</Stack>
{job.lastMessage && <Typography variant="body2" color="text.secondary">{job.lastMessage}</Typography>}
</Stack>
) : (
<Typography color="text.secondary">{t('jobs.never')}</Typography>
)}
</Box>
<Box>
<Typography variant="caption" color="text.secondary">{t('jobs.nextRun')}</Typography>
<Typography dir="ltr" sx={{ textAlign: 'start' }}>{job.nextRun ? formatDateTime(job.nextRun, lang) : '-'}</Typography>
</Box>
</Box>
<Typography variant="subtitle2" sx={{ mt: 2.5, mb: 1 }}>{t('jobs.schedule')}</Typography>
<Stack spacing={1.5}>
<ToggleButtonGroup exclusive size="small" color="primary" value={type} onChange={(_, v: 'INTERVAL' | 'DAILY' | null) => v && setType(v)}>
<ToggleButton value="INTERVAL">{t('jobs.type.interval')}</ToggleButton>
<ToggleButton value="DAILY">{t('jobs.type.daily')}</ToggleButton>
</ToggleButtonGroup>
{type === 'INTERVAL' ? (
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Typography>{t('jobs.every')}</Typography>
<TextField
size="small" value={amount} sx={{ width: 100 }} error={!intervalOk} helperText={!intervalOk ? t('jobs.badInterval') : undefined}
onChange={(e) => setAmount(e.target.value.replace(/\D/g, '').slice(0, 5))}
slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }}
/>
<TextField select size="small" value={unit} sx={{ width: 120 }} onChange={(e) => setUnit(e.target.value as 'minutes' | 'hours')}>
<MenuItem value="minutes">{t('jobs.unit.minutes')}</MenuItem>
<MenuItem value="hours">{t('jobs.unit.hours')}</MenuItem>
</TextField>
</Stack>
) : (
<Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>{t('jobs.times')}</Typography>
<Stack direction="row" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
{times.map((x) => (
<Chip key={x} label={<span dir="ltr">{x}</span>} onDelete={() => setTimes(times.filter((y) => y !== x))} />
))}
<TextField
size="small" value={newTime} placeholder={t('jobs.timeHint')} sx={{ width: 110 }}
onChange={(e) => setNewTime(maskTime(e.target.value))}
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addTime(); } }}
slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr', maxLength: 5 } }}
/>
<Button size="small" startIcon={<AddIcon />} disabled={!TIME_RE.test(newTime) || times.includes(newTime)} onClick={addTime}>
{t('jobs.addTime')}
</Button>
</Stack>
{times.length === 0 && <Typography variant="caption" color="error">{t('jobs.noTimes')}</Typography>}
</Box>
)}
</Stack>
<Stack direction="row" spacing={1} useFlexGap sx={{ mt: 2.5, flexWrap: 'wrap' }}>
<Button variant="outlined" startIcon={<SaveIcon />} disabled={busy || !scheduleOk || !dirty} onClick={saveOnly}>{t('jobs.save')}</Button>
{job.enabled ? (
<Button variant="outlined" color="error" startIcon={<StopIcon />} disabled={busy} onClick={() => stop.mutate(job.key)}>{t('jobs.stop')}</Button>
) : (
<Button variant="contained" startIcon={<PlayArrowIcon />} disabled={busy || !scheduleOk} onClick={startJob}>
{dirty ? t('jobs.saveStart') : t('jobs.start')}
</Button>
)}
<Button startIcon={<PlayArrowIcon />} disabled={busy || job.running} onClick={() => void runNow()}>{t('jobs.runNow')}</Button>
<Button startIcon={<HistoryIcon />} onClick={() => setShowHistory(true)}>{t('jobs.history')}</Button>
</Stack>
{showHistory && <HistoryDialog jobKey={job.key} title={title} onClose={() => setShowHistory(false)} />}
</Paper>
);
}
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 (
<Dialog open onClose={onClose} fullWidth maxWidth="md">
<DialogTitle sx={{ display: 'flex', alignItems: 'center' }}>
<Box sx={{ flex: 1 }}>{t('jobs.h.title')} - {title}</Box>
<IconButton size="small" aria-label={t('jobs.close')} onClick={onClose}><CloseIcon fontSize="small" /></IconButton>
</DialogTitle>
<DialogContent>
{runs.isLoading ? (
<LoadingBanner variant="update" />
) : rows.length === 0 ? (
<Typography color="text.secondary">{t('jobs.h.none')}</Typography>
) : (
<TableContainer>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>{t('jobs.h.start')}</TableCell>
<TableCell>{t('jobs.h.end')}</TableCell>
<TableCell>{t('jobs.h.status')}</TableCell>
<TableCell align="center">{t('jobs.h.rows')}</TableCell>
<TableCell>{t('jobs.h.by')}</TableCell>
<TableCell>{t('jobs.h.message')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((r) => (
<TableRow key={r.id}>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{formatDateTime(r.startDate, lang)}</TableCell>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{r.endDate ? formatDateTime(r.endDate, lang) : ''}</TableCell>
<TableCell>
{r.status && <Chip size="small" label={t(`jobs.status.${r.status}` as 'jobs.status.OK')} color={statusColor(r.status)} />}
</TableCell>
<TableCell align="center" dir="ltr">{r.rowsAffected === null ? '' : formatNumber(r.rowsAffected, lang)}</TableCell>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{r.triggeredBy === 'SCHEDULE' ? t('jobs.h.schedule') : r.triggeredBy}</TableCell>
<TableCell>{r.message}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</DialogContent>
<DialogActions><Button onClick={onClose}>{t('jobs.close')}</Button></DialogActions>
</Dialog>
);
}