46 lines
2.2 KiB
TypeScript
46 lines
2.2 KiB
TypeScript
import { useQuery } from '@tanstack/react-query';
|
|
import { api } from '@/api/client';
|
|
import { useWrite } from '@/api/hooks';
|
|
|
|
const base = '/grains/jobs';
|
|
const jobsKey = ['jobs'];
|
|
|
|
export interface JobItem {
|
|
key: string;
|
|
titleAr: string; titleEn: string; descriptionAr: string; descriptionEn: string;
|
|
enabled: boolean;
|
|
scheduleType: 'INTERVAL' | 'DAILY';
|
|
intervalMinutes: number;
|
|
dailyTimes: string[];
|
|
running: boolean;
|
|
lastStart: string | null; lastEnd: string | null; lastStatus: string | null; lastMessage: string | null; lastCount: number | null;
|
|
nextRun: string | null;
|
|
}
|
|
export interface JobRun {
|
|
id: number; startDate: string; endDate: string | null; status: string | null; rowsAffected: number | null; message: string | null; triggeredBy: string | null;
|
|
}
|
|
export interface ScheduleBody { scheduleType: 'INTERVAL' | 'DAILY'; intervalMinutes: number | null; dailyTimes: string[] | null }
|
|
export interface JobActionResult { success: boolean; message: string }
|
|
|
|
/** Refreshed every 10 seconds so a running job and its result show without reloading the page. */
|
|
export function useJobs() {
|
|
return useQuery({ queryKey: jobsKey, queryFn: () => api.get<JobItem[]>(base), refetchInterval: 10_000 });
|
|
}
|
|
|
|
export function useJobRuns(key: string | null) {
|
|
return useQuery({ queryKey: [...jobsKey, 'runs', key], queryFn: () => api.get<JobRun[]>(`${base}/${key}/runs`), enabled: !!key });
|
|
}
|
|
|
|
export const useSaveSchedule = (message: string) =>
|
|
useWrite((v: { key: string; body: ScheduleBody }) => api.put<JobItem>(`${base}/${v.key}`, v.body), { invalidate: [jobsKey], successMessage: message });
|
|
|
|
export const useStartJob = (message: string) =>
|
|
useWrite((key: string) => api.post<JobItem>(`${base}/${key}/start`), { invalidate: [jobsKey], successMessage: message });
|
|
|
|
export const useStopJob = (message: string) =>
|
|
useWrite((key: string) => api.post<JobItem>(`${base}/${key}/stop`), { invalidate: [jobsKey], successMessage: message });
|
|
|
|
/** The answer carries its own message ("started" / "already running"), shown by the page. */
|
|
export const useRunJob = () =>
|
|
useWrite((key: string) => api.post<JobActionResult>(`${base}/${key}/run`), { invalidate: [jobsKey], toastSuccess: false });
|