implement cron page (#7)

This commit is contained in:
UUBulb
2024-11-20 00:19:40 +08:00
committed by GitHub
parent 2bf2639080
commit e37f30d335
20 changed files with 555 additions and 28 deletions

18
src/api/cron.ts Normal file
View File

@@ -0,0 +1,18 @@
import { ModelCronForm } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const createCron = async (data: ModelCronForm): Promise<number> => {
return fetcher<number>(FetcherMethod.POST, '/api/v1/cron', data);
}
export const updateCron = async (id: number, data: ModelCronForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/cron/${id}`, data);
}
export const deleteCron = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/cron', id);
}
export const runCron = async (id: number): Promise<void> => {
return fetcher<void>(FetcherMethod.GET, `/api/v1/cron/${id}/manual`, null);
}

View File

@@ -2,17 +2,17 @@ import { ModelDDNSForm } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const createDDNSProfile = async (data: ModelDDNSForm): Promise<number> => {
return fetcher<number>(FetcherMethod.POST, '/api/v1/ddns', data)
return fetcher<number>(FetcherMethod.POST, '/api/v1/ddns', data);
}
export const updateDDNSProfile = async (id: number, data: ModelDDNSForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/ddns/${id}`, data)
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/ddns/${id}`, data);
}
export const deleteDDNSProfiles = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/ddns', id)
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/ddns', id);
}
export const getDDNSProviders = async (): Promise<string[]> => {
return fetcher<string[]>(FetcherMethod.GET, '/api/v1/ddns/providers', null)
return fetcher<string[]>(FetcherMethod.GET, '/api/v1/ddns/providers', null);
}

View File

@@ -2,13 +2,13 @@ import { ModelNATForm } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const createNAT = async (data: ModelNATForm): Promise<number> => {
return fetcher<number>(FetcherMethod.POST, '/api/v1/nat', data)
return fetcher<number>(FetcherMethod.POST, '/api/v1/nat', data);
}
export const updateNAT = async (id: number, data: ModelNATForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/nat/${id}`, data)
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/nat/${id}`, data);
}
export const deleteNAT = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/nat', id)
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/nat', id);
}

View File

@@ -10,5 +10,5 @@ export const updateNotificationGroup = async (id: number, data: ModelNotificatio
}
export const deleteNotificationGroups = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/notification-group`, id)
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/notification-group`, id);
}

View File

@@ -10,9 +10,9 @@ export const updateServerGroup = async (id: number, data: ModelServerGroupForm):
}
export const deleteServerGroups = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/server-group`, id)
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/server-group`, id);
}
export const getServerGroups = async (): Promise<ModelServerGroupResponseItem[]> => {
return fetcher<ModelServerGroupResponseItem[]>(FetcherMethod.GET, '/api/v1/server-group', null)
return fetcher<ModelServerGroupResponseItem[]>(FetcherMethod.GET, '/api/v1/server-group', null);
}

View File

@@ -2,13 +2,13 @@ import { ModelServer, ModelServerForm } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const updateServer = async (id: number, data: ModelServerForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/server/${id}`, data)
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/server/${id}`, data);
}
export const deleteServer = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/server', id)
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/server', id);
}
export const getServers = async (): Promise<ModelServer[]> => {
return fetcher<ModelServer[]>(FetcherMethod.GET, '/api/v1/server', null)
return fetcher<ModelServer[]>(FetcherMethod.GET, '/api/v1/server', null);
}

View File

@@ -2,13 +2,13 @@ import { ModelServiceForm } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const createService = async (data: ModelServiceForm): Promise<number> => {
return fetcher<number>(FetcherMethod.POST, '/api/v1/service', data)
return fetcher<number>(FetcherMethod.POST, '/api/v1/service', data);
}
export const updateService = async (id: number, data: ModelServiceForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/service/${id}`, data)
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/service/${id}`, data);
}
export const deleteService = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/service', id)
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/service', id);
}

View File

@@ -2,9 +2,9 @@ import { ModelUser } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const getProfile = async (): Promise<ModelUser> => {
return fetcher<ModelUser>(FetcherMethod.GET, '/api/v1/profile', null)
return fetcher<ModelUser>(FetcherMethod.GET, '/api/v1/profile', null);
}
export const login = async (username: string, password: string): Promise<any> => {
return fetcher<any>(FetcherMethod.POST, '/api/v1/login', { username, password })
return fetcher<any>(FetcherMethod.POST, '/api/v1/login', { username, password });
}

249
src/components/cron.tsx Normal file
View File

@@ -0,0 +1,249 @@
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { ModelCron } from "@/types"
import { useState } from "react"
import { KeyedMutator } from "swr"
import { IconButton } from "@/components/xui/icon-button"
import { createCron, updateCron } from "@/api/cron"
import { asOptionalField } from "@/lib/utils"
import { cronTypes, cronCoverageTypes } from "@/types"
import { Textarea } from "./ui/textarea"
import { conv } from "@/lib/utils"
interface CronCardProps {
data?: ModelCron;
mutate: KeyedMutator<ModelCron[]>;
}
const cronFormSchema = z.object({
task_type: z.coerce.number(),
name: z.string().min(1),
scheduler: z.string(),
command: asOptionalField(z.string()),
servers: z.array(z.string()).transform((v => {
return v.filter(Boolean).map(Number);
})),
cover: z.coerce.number().int(),
push_successful: asOptionalField(z.boolean()),
notification_group_id: z.coerce.number().int(),
});
export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
const form = useForm<z.infer<typeof cronFormSchema>>({
resolver: zodResolver(cronFormSchema),
defaultValues: data ? data : {
name: "",
task_type: 0,
scheduler: "",
servers: [],
cover: 0,
notification_group_id: 0,
},
resetOptions: {
keepDefaultValues: false,
}
})
const [open, setOpen] = useState(false);
const onSubmit = async (values: z.infer<typeof cronFormSchema>) => {
data?.id ? await updateCron(data.id, values) : await createCron(values);
setOpen(false);
await mutate();
form.reset();
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{data
?
<IconButton variant="outline" icon="edit" />
:
<IconButton icon="plus" />
}
</DialogTrigger>
<DialogContent className="sm:max-w-xl">
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
<div className="items-center mx-1">
<DialogHeader>
<DialogTitle>New Task</DialogTitle>
<DialogDescription />
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-2 my-2">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input
placeholder="My Task"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="task_type"
render={({ field }) => (
<FormItem>
<FormLabel>Task Type</FormLabel>
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select task type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(cronTypes).map(([k, v]) => (
<SelectItem key={k} value={k}>{v}</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="scheduler"
render={({ field }) => (
<FormItem>
<FormLabel>Cron expression</FormLabel>
<FormControl>
<Input
placeholder="0 0 0 3 * * (At 3 AM)"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="command"
render={({ field }) => (
<FormItem>
<FormLabel>Command</FormLabel>
<FormControl>
<Textarea
className="resize-y"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="cover"
render={({ field }) => (
<FormItem>
<FormLabel>Coverage</FormLabel>
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
<FormControl>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(cronCoverageTypes).map(([k, v]) => (
<SelectItem key={k} value={k}>{v}</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="servers"
render={({ field }) => (
<FormItem>
<FormLabel>Specific Servers (Separate with comma)</FormLabel>
<FormControl>
<Input
placeholder="1,2,3"
{...field}
value={conv.arrToStr(field.value ?? [])}
onChange={e => {
const arr = conv.strToArr(e.target.value);
field.onChange(arr);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="notification_group_id"
render={({ field }) => (
<FormItem>
<FormLabel>Notifier Group ID</FormLabel>
<FormControl>
<Input
type="number"
placeholder="0"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter className="justify-end">
<DialogClose asChild>
<Button type="button" className="my-2" variant="secondary">
Close
</Button>
</DialogClose>
<Button type="submit" className="my-2">Submit</Button>
</DialogFooter>
</form>
</Form>
</div>
</ScrollArea>
</DialogContent>
</Dialog>
)
}

View File

@@ -42,6 +42,11 @@ export default function Header() {
<Link to="/dashboard/service">Service</Link>
</NzNavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem>
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/cron"} className={navigationMenuTriggerStyle()}>
<Link to="/dashboard/cron">Task</Link>
</NzNavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem>
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/ddns"} className={navigationMenuTriggerStyle()}>
<Link to="/dashboard/ddns">Dynamic DNS</Link>
@@ -54,7 +59,7 @@ export default function Header() {
</NavigationMenuItem>
<NavigationMenuItem>
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/server-group" || location.pathname === "/dashboard/notification-group"} className={navigationMenuTriggerStyle()}>
<Link to="/dashboard/server-group">Groups</Link>
<Link to="/dashboard/server-group">Group</Link>
</NzNavigationMenuLink>
</NavigationMenuItem>
</>

View File

@@ -76,7 +76,7 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
<div className="items-center mx-1">
<DialogHeader>
<DialogTitle>New Server Group</DialogTitle>
<DialogTitle>New Notifier Group</DialogTitle>
<DialogDescription />
</DialogHeader>
<Form {...form}>
@@ -102,7 +102,7 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
name="notifications"
render={({ field }) => (
<FormItem>
<FormLabel>Notification Methods</FormLabel>
<FormLabel>Notifiers</FormLabel>
<FormControl>
<Input
placeholder="1,2,3"

View File

@@ -214,7 +214,7 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select service type" />
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
@@ -253,7 +253,7 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
name="notification_group_id"
render={({ field }) => (
<FormItem>
<FormLabel>Notification Group ID</FormLabel>
<FormLabel>Notifier Group ID</FormLabel>
<FormControl>
<Input
type="number"

View File

@@ -1,9 +1,9 @@
import { Plus, Edit2, Trash2, Terminal, CircleArrowUp, Clipboard, Check, FolderClosed } from "lucide-react"
import { Plus, Edit2, Trash2, Terminal, CircleArrowUp, Clipboard, Check, FolderClosed, Play } from "lucide-react"
import { Button, ButtonProps } from "@/components/ui/button"
import { forwardRef } from "react";
export interface IconButtonProps extends ButtonProps {
icon: "clipboard" | "check" | "edit" | "trash" | "plus" | "terminal" | "update" | "folder-closed";
icon: "clipboard" | "check" | "edit" | "trash" | "plus" | "terminal" | "update" | "folder-closed" | "play";
}
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>((props, ref) => {
@@ -35,6 +35,9 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>((props,
case "folder-closed": {
return <FolderClosed />;
}
case "play": {
return <Play />;
}
}
})()}
</Button>

View File

@@ -20,6 +20,7 @@ import NATPage from './routes/nat';
import ServerGroupPage from './routes/server-group';
import NotificationGroupPage from './routes/notification-group';
import { ServerProvider } from './hooks/useServer';
import CronPage from './routes/cron';
const router = createBrowserRouter([
{
@@ -39,6 +40,10 @@ const router = createBrowserRouter([
path: "/dashboard/service",
element: <ServicePage />,
},
{
path: "/dashboard/cron",
element: <CronPage />,
},
{
path: "/dashboard/ddns",
element: <DDNSPage />,

237
src/routes/cron.tsx Normal file
View File

@@ -0,0 +1,237 @@
import { swrFetcher } from "@/api/api"
import { Checkbox } from "@/components/ui/checkbox"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { ModelCron } from "@/types"
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
import useSWR from "swr"
import { useEffect } from "react"
import { ActionButtonGroup } from "@/components/action-button-group"
import { HeaderButtonGroup } from "@/components/header-button-group"
import { Skeleton } from "@/components/ui/skeleton"
import { toast } from "sonner"
import { deleteCron, runCron } from "@/api/cron"
import { CronCard } from "@/components/cron"
import { cronTypes } from "@/types"
import { IconButton } from "@/components/xui/icon-button"
export default function CronPage() {
const { data, mutate, error, isLoading } = useSWR<ModelCron[]>('/api/v1/cron', swrFetcher);
useEffect(() => {
if (error)
toast("Error", {
description: `Error fetching resource: ${error.message}.`,
})
}, [error])
const columns: ColumnDef<ModelCron>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
},
{
header: "ID",
accessorKey: "id",
accessorFn: row => row.id,
},
{
header: "Name",
accessorKey: "name",
cell: ({ row }) => {
const s = row.original;
return (
<div className="max-w-32 whitespace-normal break-words">
{s.name}
</div>
)
}
},
{
header: "Task Type",
accessorKey: "taskType",
accessorFn: row => cronTypes[row.task_type] || '',
},
{
header: "Cron Expression",
accessorKey: "scheduler",
accessorFn: row => row.scheduler,
},
{
header: "Command",
accessorKey: "command",
cell: ({ row }) => {
const s = row.original;
return (
<div className="max-w-48 whitespace-normal break-words">
{s.command}
</div>
)
}
},
{
header: "Notifier Group",
accessorKey: "ngroup",
accessorFn: row => row.notification_group_id,
},
{
header: "Send Success Notification",
accessorKey: "pushSuccessful",
accessorFn: row => row.push_successful ?? false,
},
{
header: "Coverage",
accessorKey: "cover",
accessorFn: row => {
switch (row.cover) {
case 0: {
return "Ignore All"
}
case 1: {
return "Cover All"
}
case 2: {
return "On alert"
}
}
},
},
{
header: "Specific Servers",
accessorKey: "servers",
accessorFn: row => row.servers,
},
{
header: "Last Execution",
accessorKey: "lastExecution",
accessorFn: row => row.last_executed_at
},
{
header: "Last Result",
accessorKey: "lastResult",
accessorFn: row => row.last_result ?? false,
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => {
const s = row.original
return (
<ActionButtonGroup className="flex gap-2" delete={{ fn: deleteCron, id: s.id, mutate: mutate }}>
<>
<IconButton variant="outline" icon="play" onClick={
async () => {
try {
await runCron(s.id);
} catch (e) {
console.log(e);
toast("Error executing task", {
description: "Please see the console for details.",
})
await mutate()
}
toast("Success", {
description: "The task triggered successfully.",
})
await mutate()
}} />
<CronCard mutate={mutate} data={s} />
</>
</ActionButtonGroup>
)
},
},
]
const table = useReactTable({
data: data ?? [],
columns,
getCoreRowModel: getCoreRowModel(),
})
const selectedRows = table.getSelectedRowModel().rows;
return (
<div className="px-8">
<div className="flex mt-6 mb-4">
<h1 className="flex-1 text-3xl font-bold tracking-tight">
Task
</h1>
<HeaderButtonGroup className="flex-2 flex ml-auto gap-2" delete={{
fn: deleteCron,
id: selectedRows.map(r => r.original.id),
mutate: mutate,
}}>
<CronCard mutate={mutate} />
</HeaderButtonGroup>
</div>
{isLoading ? (
<div className="flex flex-col items-center space-y-4">
<Skeleton className="h-[60px] w-[100%] rounded-lg" />
<Skeleton className="h-[60px] w-[100%] rounded-lg" />
<Skeleton className="h-[60px] w-[100%] rounded-lg" />
</div>
) : (
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="text-sm">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="text-xsm">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
)}
</div >
)
}

View File

@@ -64,7 +64,7 @@ export default function NotificationGroupPage() {
}
},
{
header: "Notification methods (ID)",
header: "Notifiers (ID)",
accessorKey: "notifications",
accessorFn: row => row.notifications,
},

View File

@@ -106,7 +106,7 @@ export default function ServicePage() {
accessorFn: row => row.service.duration,
},
{
header: "Notification Group ID",
header: "Notifier Group ID",
accessorKey: "service.ngroup",
accessorFn: row => row.service.notification_group_id,
},

View File

@@ -216,7 +216,6 @@ export interface ModelCronForm {
command?: string;
/** @default 0 */
cover: number;
id: number;
/** @minLength 1 */
name: string;
notification_group_id: number;

10
src/types/cron.ts Normal file
View File

@@ -0,0 +1,10 @@
export const cronTypes: Record<number, string> = {
0: "Scheduled",
1: "Trigger",
}
export const cronCoverageTypes: Record<number, string> = {
0: "Only specific servers",
1: "All excludes specific servers",
2: "The alarmed servers"
}

View File

@@ -5,3 +5,4 @@ export * from './service';
export * from './ddns';
export * from './serverStore';
export * from './serverContext';
export * from './cron';