implement notification page (#8)

This commit is contained in:
UUBulb
2024-11-20 21:37:03 +08:00
committed by GitHub
parent e37f30d335
commit b3588b3378
27 changed files with 1133 additions and 36 deletions

14
src/api/alert-rule.ts Normal file
View File

@@ -0,0 +1,14 @@
import { ModelAlertRuleForm } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const createAlertRule = async (data: ModelAlertRuleForm): Promise<number> => {
return fetcher<number>(FetcherMethod.POST, '/api/v1/alert-rule', data);
}
export const updateAlertRule = async (id: number, data: ModelAlertRuleForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/alert-rule/${id}`, data);
}
export const deleteAlertRules = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/alert-rule', id);
}

View File

@@ -1,4 +1,4 @@
import { ModelNotificationGroupForm } from "@/types" import { ModelNotificationGroupForm, ModelNotificationGroupResponseItem } from "@/types"
import { fetcher, FetcherMethod } from "./api" import { fetcher, FetcherMethod } from "./api"
export const createNotificationGroup = async (data: ModelNotificationGroupForm): Promise<number> => { export const createNotificationGroup = async (data: ModelNotificationGroupForm): Promise<number> => {
@@ -12,3 +12,7 @@ export const updateNotificationGroup = async (id: number, data: ModelNotificatio
export const deleteNotificationGroups = async (id: number[]): Promise<void> => { 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);
} }
export const getNotificationGroups = async (): Promise<ModelNotificationGroupResponseItem[]> => {
return fetcher<ModelNotificationGroupResponseItem[]>(FetcherMethod.GET, '/api/v1/notification-group', null);
}

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

@@ -0,0 +1,18 @@
import { ModelNotificationForm, ModelNotification } from "@/types"
import { fetcher, FetcherMethod } from "./api"
export const createNotification = async (data: ModelNotificationForm): Promise<number> => {
return fetcher<number>(FetcherMethod.POST, '/api/v1/notification', data);
}
export const updateNotification = async (id: number, data: ModelNotificationForm): Promise<void> => {
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/notification/${id}`, data);
}
export const deleteNotification = async (id: number[]): Promise<void> => {
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/notification', id);
}
export const getNotification = async (): Promise<ModelNotification[]> => {
return fetcher<ModelNotification[]>(FetcherMethod.GET, '/api/v1/notification', null);
}

View File

@@ -1,4 +1,4 @@
import { ModelTerminalForm, ModelCreateTerminalResponse } from "@/types"; import { ModelCreateTerminalResponse } from "@/types";
import { fetcher, FetcherMethod } from "./api" import { fetcher, FetcherMethod } from "./api"
export const createTerminal = async (id: number): Promise<ModelCreateTerminalResponse> => { export const createTerminal = async (id: number): Promise<ModelCreateTerminalResponse> => {

View File

@@ -0,0 +1,281 @@
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 {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { ModelAlertRule } from "@/types"
import { createAlertRule, updateAlertRule } from "@/api/alert-rule"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { conv } from "@/lib/utils"
import { useState } from "react"
import { KeyedMutator } from "swr"
import { asOptionalField } from "@/lib/utils"
import { IconButton } from "@/components/xui/icon-button"
import { triggerModes } from "@/types"
import { Textarea } from "./ui/textarea"
interface AlertRuleCardProps {
data?: ModelAlertRule;
mutate: KeyedMutator<ModelAlertRule[]>;
}
const ruleSchema = z.object({
type: z.string(),
min: asOptionalField(z.number()),
max: asOptionalField(z.number()),
cycle_start: asOptionalField(z.string()),
cycle_interval: asOptionalField(z.number()),
cycle_unit: asOptionalField(z.enum(['hour', 'day', 'week', 'month', 'year'])),
duration: asOptionalField(z.number()),
cover: z.number().int().min(0),
ignore: asOptionalField(z.record(z.boolean())),
next_transfer_at: asOptionalField(z.record(z.string())),
last_cycle_status: asOptionalField((z.boolean())),
});
const alertRuleFormSchema = z.object({
name: z.string().min(1),
rules_raw: z.string().refine((val) => {
try {
JSON.parse(val);
return true;
} catch (e) {
return false;
}
}, {
message: 'Invalid JSON string',
}),
rules: z.array(ruleSchema),
fail_trigger_tasks: z.array(z.string()).transform((v => {
return v.filter(Boolean).map(Number);
})),
recover_trigger_tasks: z.array(z.string()).transform((v => {
return v.filter(Boolean).map(Number);
})),
notification_group_id: z.coerce.number().int(),
trigger_mode: z.coerce.number().int().min(0),
enable: asOptionalField(z.boolean()),
});
export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) => {
const form = useForm<z.infer<typeof alertRuleFormSchema>>({
resolver: zodResolver(alertRuleFormSchema),
defaultValues: data ? {
...data,
rules_raw: JSON.stringify(data.rules),
} : {
name: "",
rules_raw: "",
rules: [],
fail_trigger_tasks: [],
recover_trigger_tasks: [],
notification_group_id: 0,
trigger_mode: 0,
},
resetOptions: {
keepDefaultValues: false,
}
})
const [open, setOpen] = useState(false);
const onSubmit = async (values: z.infer<typeof alertRuleFormSchema>) => {
values.rules = JSON.parse(values.rules_raw);
data?.id ? await updateAlertRule(data.id, values) : await createAlertRule(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 Alert Rule</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
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="rules_raw"
render={({ field }) => (
<FormItem>
<FormLabel>Rules</FormLabel>
<FormControl>
<Textarea
className="resize-y"
{...field}
/>
</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>
)}
/>
<FormField
control={form.control}
name="trigger_mode"
render={({ field }) => (
<FormItem>
<FormLabel>Trigger Mode</FormLabel>
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
<FormControl>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(triggerModes).map(([k, v]) => (
<SelectItem key={k} value={k}>{v}</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="fail_trigger_tasks"
render={({ field }) => (
<FormItem>
<FormLabel>Tasks to trigger on an alarm (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="recover_trigger_tasks"
render={({ field }) => (
<FormItem>
<FormLabel>Tasks to trigger after recovery (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="enable"
render={({ field }) => (
<FormItem className="flex items-center space-x-2">
<FormControl>
<div className="flex items-center gap-2">
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
<Label className="text-sm">Enable</Label>
</div>
</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

@@ -58,7 +58,7 @@ const ddnsFormSchema = z.object({
access_secret: asOptionalField(z.string()), access_secret: asOptionalField(z.string()),
webhook_url: asOptionalField(z.string().url()), webhook_url: asOptionalField(z.string().url()),
webhook_method: asOptionalField(z.coerce.number().int().min(1).max(255)), webhook_method: asOptionalField(z.coerce.number().int().min(1).max(255)),
webhook_request_type: asOptionalField(z.coerce.number().int().min(1).max(255).default(1)), webhook_request_type: asOptionalField(z.coerce.number().int().min(1).max(255)),
webhook_request_body: asOptionalField(z.string()), webhook_request_body: asOptionalField(z.string()),
webhook_headers: asOptionalField(z.string()), webhook_headers: asOptionalField(z.string()),
}); });

View File

@@ -5,11 +5,11 @@ import {
} from "@/components/ui/tabs" } from "@/components/ui/tabs"
import { Link, useLocation } from "react-router-dom" import { Link, useLocation } from "react-router-dom"
export const GroupTab = () => { export const GroupTab = ({ className }: { className?: string }) => {
const location = useLocation(); const location = useLocation();
return ( return (
<Tabs defaultValue={location.pathname}> <Tabs defaultValue={location.pathname} className={className}>
<TabsList className="grid w-full grid-cols-2"> <TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="/dashboard/server-group" asChild> <TabsTrigger value="/dashboard/server-group" asChild>
<Link to="/dashboard/server-group">Server</Link> <Link to="/dashboard/server-group">Server</Link>

View File

@@ -47,6 +47,11 @@ export default function Header() {
<Link to="/dashboard/cron">Task</Link> <Link to="/dashboard/cron">Task</Link>
</NzNavigationMenuLink> </NzNavigationMenuLink>
</NavigationMenuItem> </NavigationMenuItem>
<NavigationMenuItem>
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/notification" || location.pathname === "/dashboard/alert-rule"} className={navigationMenuTriggerStyle()}>
<Link to="/dashboard/notification">Notification</Link>
</NzNavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem> <NavigationMenuItem>
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/ddns"} className={navigationMenuTriggerStyle()}> <NzNavigationMenuLink asChild active={location.pathname === "/dashboard/ddns"} className={navigationMenuTriggerStyle()}>
<Link to="/dashboard/ddns">Dynamic DNS</Link> <Link to="/dashboard/ddns">Dynamic DNS</Link>

View File

@@ -27,7 +27,8 @@ import { useState } from "react"
import { KeyedMutator } from "swr" import { KeyedMutator } from "swr"
import { IconButton } from "@/components/xui/icon-button" import { IconButton } from "@/components/xui/icon-button"
import { createNotificationGroup, updateNotificationGroup } from "@/api/notification-group" import { createNotificationGroup, updateNotificationGroup } from "@/api/notification-group"
import { conv } from "@/lib/utils" import { MultiSelect } from "@/components/xui/multi-select"
import { useNotification } from "@/hooks/useNotfication"
interface NotificationGroupCardProps { interface NotificationGroupCardProps {
data?: ModelNotificationGroupResponseItem; data?: ModelNotificationGroupResponseItem;
@@ -44,7 +45,10 @@ const notificationGroupFormSchema = z.object({
export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ data, mutate }) => { export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ data, mutate }) => {
const form = useForm<z.infer<typeof notificationGroupFormSchema>>({ const form = useForm<z.infer<typeof notificationGroupFormSchema>>({
resolver: zodResolver(notificationGroupFormSchema), resolver: zodResolver(notificationGroupFormSchema),
defaultValues: data ? data : { defaultValues: data ? {
name: data.group.name,
notifications: data.notifications,
} : {
name: "", name: "",
notifications: [], notifications: [],
}, },
@@ -62,6 +66,12 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
form.reset(); form.reset();
} }
const { notifiers } = useNotification();
const notifierList = notifiers?.map(n => ({
value: `${n.id}`,
label: n.name,
})) || [{ value: "", label: "" }];
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
@@ -103,17 +113,11 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Notifiers</FormLabel> <FormLabel>Notifiers</FormLabel>
<FormControl> <MultiSelect
<Input options={notifierList}
placeholder="1,2,3" onValueChange={field.onChange}
{...field} defaultValue={field.value?.map(String)}
value={conv.arrToStr(field.value ?? [])}
onChange={e => {
const arr = conv.strToArr(e.target.value);
field.onChange(arr);
}}
/> />
</FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}

View File

@@ -0,0 +1,23 @@
import {
Tabs,
TabsList,
TabsTrigger,
} from "@/components/ui/tabs"
import { Link, useLocation } from "react-router-dom"
export const NotificationTab = ({ className }: { className?: string }) => {
const location = useLocation();
return (
<Tabs defaultValue={location.pathname} className={className}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="/dashboard/notification" asChild>
<Link to="/dashboard/notification">Notifier</Link>
</TabsTrigger>
<TabsTrigger value="/dashboard/alert-rule" asChild>
<Link to="/dashboard/alert-rule">Alert Rule</Link>
</TabsTrigger>
</TabsList>
</Tabs>
)
}

263
src/components/notifier.tsx Normal file
View File

@@ -0,0 +1,263 @@
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 {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { ModelNotification } from "@/types"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { useState } from "react"
import { KeyedMutator } from "swr"
import { asOptionalField } from "@/lib/utils"
import { IconButton } from "@/components/xui/icon-button"
import { nrequestTypes, nrequestMethods } from "@/types"
import { createNotification, updateNotification } from "@/api/notification"
import { Textarea } from "./ui/textarea"
interface NotifierCardProps {
data?: ModelNotification;
mutate: KeyedMutator<ModelNotification[]>;
}
const notificationFormSchema = z.object({
name: z.string().min(1),
url: z.string().url(),
request_method: z.coerce.number().int().min(1).max(255),
request_type: z.coerce.number().int().min(1).max(255),
request_header: z.string(),
request_body: z.string(),
verify_tls: asOptionalField(z.boolean()),
skip_check: asOptionalField(z.boolean()),
});
export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
const form = useForm<z.infer<typeof notificationFormSchema>>({
resolver: zodResolver(notificationFormSchema),
defaultValues: data ? data : {
name: "",
url: "",
request_method: 1,
request_type: 1,
request_header: "",
request_body: "",
},
resetOptions: {
keepDefaultValues: false,
}
})
const [open, setOpen] = useState(false);
const onSubmit = async (values: z.infer<typeof notificationFormSchema>) => {
data?.id ? await updateNotification(data.id, values) : await createNotification(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 Notifier</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 Notifier"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="url"
render={({ field }) => (
<FormItem>
<FormLabel>URL</FormLabel>
<FormControl>
<Input
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="request_method"
render={({ field }) => (
<FormItem>
<FormLabel>Request Method</FormLabel>
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Request Method" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(nrequestMethods).map(([k, v]) => (
<SelectItem key={k} value={k}>{v}</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="request_type"
render={({ field }) => (
<FormItem>
<FormLabel>Request Type</FormLabel>
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Request Type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(nrequestTypes).map(([k, v]) => (
<SelectItem key={k} value={k}>{v}</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="request_header"
render={({ field }) => (
<FormItem>
<FormLabel>Header</FormLabel>
<FormControl>
<Textarea
className="resize-y"
placeholder='{"User-Agent":"Nezha-Agent"}'
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="request_body"
render={({ field }) => (
<FormItem>
<FormLabel>Body</FormLabel>
<FormControl>
<Textarea
className="resize-y h-[240px]"
placeholder='{&#13;&#10; "content":"#NEZHA#",&#13;&#10; "ServerName":"#SERVER.NAME#",&#13;&#10; "ServerIP":"#SERVER.IP#",&#13;&#10; "ServerIPV4":"#SERVER.IPV4#",&#13;&#10; "ServerIPV6":"#SERVER.IPV6#",&#13;&#10; "CPU":"#SERVER.CPU#",&#13;&#10; "MEM":"#SERVER.MEM#",&#13;&#10; "SWAP":"#SERVER.SWAP#",&#13;&#10; "DISK":"#SERVER.DISK#",&#13;&#10; "NetInSpeed":"#SERVER.NETINSPEED#",&#13;&#10; "NetOutSpeed":"#SERVER.NETOUTSPEED#",&#13;&#10; "TransferIn":"#SERVER.TRANSFERIN#",&#13;&#10; "TranferOut":"#SERVER.TRANSFEROUT#",&#13;&#10; "Load1":"#SERVER.LOAD1#",&#13;&#10; "Load5":"#SERVER.LOAD5#",&#13;&#10; "Load15":"#SERVER.LOAD15#",&#13;&#10; "TCP_CONN_COUNT":"#SERVER.TCPCONNCOUNT",&#13;&#10; "UDP_CONN_COUNT":"#SERVER.UDPCONNCOUNT"&#13;&#10;}'
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="verify_tls"
render={({ field }) => (
<FormItem className="flex items-center space-x-2">
<FormControl>
<div className="flex items-center gap-2">
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
<Label className="text-sm">Verify TLS</Label>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="skip_check"
render={({ field }) => (
<FormItem className="flex items-center space-x-2">
<FormControl>
<div className="flex items-center gap-2">
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
<Label className="text-sm">Do Not Send Test Message</Label>
</div>
</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

@@ -27,7 +27,7 @@ import { useState } from "react"
import { KeyedMutator } from "swr" import { KeyedMutator } from "swr"
import { IconButton } from "@/components/xui/icon-button" import { IconButton } from "@/components/xui/icon-button"
import { createServerGroup, updateServerGroup } from "@/api/server-group" import { createServerGroup, updateServerGroup } from "@/api/server-group"
import { MultiSelect } from "@/components/xui/multi-select"; import { MultiSelect } from "@/components/xui/multi-select"
import { useServer } from "@/hooks/useServer" import { useServer } from "@/hooks/useServer"
interface ServerGroupCardProps { interface ServerGroupCardProps {

View File

@@ -0,0 +1,52 @@
import { createContext, useContext, useEffect, useMemo } from "react"
import { useNotificationStore } from "./useNotificationStore"
import { getNotificationGroups } from "@/api/notification-group"
import { getNotification } from "@/api/notification"
import { NotificationContextProps } from "@/types"
const NotificationContext = createContext<NotificationContextProps>({});
interface NotificationProviderProps {
children: React.ReactNode;
withNotifier?: boolean;
withNotifierGroup?: boolean;
}
export const NotificationProvider: React.FC<NotificationProviderProps> = ({ children, withNotifier, withNotifierGroup }) => {
const notifierGroup = useNotificationStore(store => store.notifierGroup);
const setNotifierGroup = useNotificationStore(store => store.setNotifierGroup);
const notifiers = useNotificationStore(store => store.notifiers);
const setNotifier = useNotificationStore(store => store.setNotifier);
useEffect(() => {
if (withNotifierGroup)
(async () => {
try {
const ng = await getNotificationGroups();
setNotifierGroup(ng);
} catch (error) {
setNotifierGroup(undefined);
}
})();
if (withNotifier)
(async () => {
try {
const n = await getNotification();
setNotifier(n);
} catch (error) {
setNotifier(undefined);
}
})();
}, [])
const value: NotificationContextProps = useMemo(() => ({
notifiers: notifiers,
notifierGroup: notifierGroup,
}), [notifiers, notifierGroup]);
return <NotificationContext.Provider value={value}>{children}</NotificationContext.Provider>;
}
export const useNotification = () => {
return useContext(NotificationContext);
};

View File

@@ -0,0 +1,18 @@
import { NotificationStore } from '@/types'
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
export const useNotificationStore = create<NotificationStore, [['zustand/persist', NotificationStore]]>(
persist(
(set, get) => ({
notifiers: get()?.notifiers,
notifierGroup: get()?.notifierGroup,
setNotifier: notifiers => set({ notifiers }),
setNotifierGroup: notifierGroup => set({ notifierGroup }),
}),
{
name: 'notificationStore',
storage: createJSONStorage(() => localStorage),
},
),
)

View File

@@ -20,7 +20,10 @@ import NATPage from './routes/nat';
import ServerGroupPage from './routes/server-group'; import ServerGroupPage from './routes/server-group';
import NotificationGroupPage from './routes/notification-group'; import NotificationGroupPage from './routes/notification-group';
import { ServerProvider } from './hooks/useServer'; import { ServerProvider } from './hooks/useServer';
import { NotificationProvider } from './hooks/useNotfication';
import CronPage from './routes/cron'; import CronPage from './routes/cron';
import NotificationPage from './routes/notification';
import AlertRulePage from './routes/alert-rule';
const router = createBrowserRouter([ const router = createBrowserRouter([
{ {
@@ -44,6 +47,14 @@ const router = createBrowserRouter([
path: "/dashboard/cron", path: "/dashboard/cron",
element: <CronPage />, element: <CronPage />,
}, },
{
path: "/dashboard/notification",
element: <NotificationProvider withNotifierGroup><NotificationPage /></NotificationProvider>,
},
{
path: "/dashboard/alert-rule",
element: <AlertRulePage />,
},
{ {
path: "/dashboard/ddns", path: "/dashboard/ddns",
element: <DDNSPage />, element: <DDNSPage />,
@@ -58,7 +69,7 @@ const router = createBrowserRouter([
}, },
{ {
path: "/dashboard/notification-group", path: "/dashboard/notification-group",
element: <NotificationGroupPage />, element: <NotificationProvider withNotifier><NotificationGroupPage /></NotificationProvider>,
}, },
{ {
path: "/dashboard/terminal/:id", path: "/dashboard/terminal/:id",

186
src/routes/alert-rule.tsx Normal file
View File

@@ -0,0 +1,186 @@
import { swrFetcher } from "@/api/api"
import { Checkbox } from "@/components/ui/checkbox"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
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 { ModelAlertRule, triggerModes } from "@/types"
import { deleteAlertRules } from "@/api/alert-rule"
import { NotificationTab } from "@/components/notification-tab"
import { AlertRuleCard } from "@/components/alert-rule"
export default function AlertRulePage() {
const { data, mutate, error, isLoading } = useSWR<ModelAlertRule[]>("/api/v1/alert-rule", swrFetcher);
useEffect(() => {
if (error)
toast("Error", {
description: `Error fetching resource: ${error.message}.`,
})
}, [error])
const columns: ColumnDef<ModelAlertRule>[] = [
{
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: "Notifier Group",
accessorKey: "ngroup",
accessorFn: row => row.notification_group_id,
},
{
header: "Trigger Mode",
accessorKey: "trigger Mode",
accessorFn: row => triggerModes[row.trigger_mode] || '',
},
{
header: "Rules",
accessorKey: "rules",
accessorFn: row => JSON.stringify(row.rules),
},
{
header: "Tasks to trigger on alert",
accessorKey: "failTriggerTasks",
accessorFn: row => row.fail_trigger_tasks,
},
{
header: "Tasks to trigger after recovery",
accessorKey: "recoverTriggerTasks",
accessorFn: row => row.recover_trigger_tasks,
},
{
header: "Enable",
accessorKey: "enable",
accessorFn: row => row.enable,
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => {
const s = row.original
return (
<ActionButtonGroup className="flex gap-2" delete={{
fn: deleteAlertRules,
id: s.id,
mutate: mutate,
}}>
<AlertRuleCard 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 gap-[60%]">
<NotificationTab className="flex-1" />
<HeaderButtonGroup className="flex-2 flex gap-2 ml-auto" delete={{
fn: deleteAlertRules,
id: selectedRows.map(r => r.original.id),
mutate: mutate,
}}>
<AlertRuleCard 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

@@ -96,9 +96,9 @@ export default function NotificationGroupPage() {
return ( return (
<div className="px-8"> <div className="px-8">
<div className="flex mt-6 mb-4"> <div className="flex mt-6 mb-4 gap-[60%]">
<GroupTab /> <GroupTab className="flex-1" />
<HeaderButtonGroup className="flex gap-2 ml-auto" delete={{ <HeaderButtonGroup className="flex-2 flex gap-2 ml-auto" delete={{
fn: deleteNotificationGroups, fn: deleteNotificationGroups,
id: selectedRows.map(r => r.original.group.id), id: selectedRows.map(r => r.original.group.id),
mutate: mutate mutate: mutate

184
src/routes/notification.tsx Normal file
View File

@@ -0,0 +1,184 @@
import { swrFetcher } from "@/api/api"
import { Checkbox } from "@/components/ui/checkbox"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
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 { ModelNotification } from "@/types"
import { deleteNotification } from "@/api/notification"
import { NotificationTab } from "@/components/notification-tab"
import { NotifierCard } from "@/components/notifier"
import { useNotification } from "@/hooks/useNotfication"
export default function NotificationPage() {
const { data, mutate, error, isLoading } = useSWR<ModelNotification[]>("/api/v1/notification", swrFetcher);
const { notifierGroup } = useNotification();
useEffect(() => {
if (error)
toast("Error", {
description: `Error fetching resource: ${error.message}.`,
})
}, [error])
const columns: ColumnDef<ModelNotification>[] = [
{
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: "Groups",
accessorKey: "groups",
accessorFn: row => {
return notifierGroup?.filter(ng => ng.notifications?.includes(row.id))
.map(ng => ng.group.id)
|| [];
},
},
{
header: "URL",
accessorKey: "url",
cell: ({ row }) => {
const s = row.original;
return (
<div className="max-w-64 whitespace-normal break-words">
{s.url}
</div>
)
}
},
{
header: "Verify TLS",
accessorKey: "verify_tls",
accessorFn: row => row.verify_tls,
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => {
const s = row.original
return (
<ActionButtonGroup className="flex gap-2" delete={{
fn: deleteNotification,
id: s.id,
mutate: mutate,
}}>
<NotifierCard 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 gap-[60%]">
<NotificationTab className="flex-1" />
<HeaderButtonGroup className="flex-2 flex gap-2 ml-auto" delete={{
fn: deleteNotification,
id: selectedRows.map(r => r.original.id),
mutate: mutate
}}>
<NotifierCard 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

@@ -96,9 +96,9 @@ export default function ServerGroupPage() {
return ( return (
<div className="px-8"> <div className="px-8">
<div className="flex mt-6 mb-4"> <div className="flex mt-6 mb-4 gap-[60%]">
<GroupTab /> <GroupTab className="flex-1" />
<HeaderButtonGroup className="flex ml-auto gap-2" delete={{ <HeaderButtonGroup className="flex-2 flex ml-auto gap-2" delete={{
fn: deleteServerGroups, fn: deleteServerGroups,
id: selectedRows.map(r => r.original.group.id), id: selectedRows.map(r => r.original.group.id),
mutate: mutate mutate: mutate

View File

@@ -72,7 +72,7 @@ export default function ServerPage() {
header: "Groups", header: "Groups",
accessorKey: "groups", accessorKey: "groups",
accessorFn: row => { accessorFn: row => {
return serverGroups?.filter(sg => sg.servers.includes(row.id)) return serverGroups?.filter(sg => sg.servers?.includes(row.id))
.map(sg => sg.group.id) .map(sg => sg.group.id)
|| []; || [];
}, },

View File

@@ -116,7 +116,7 @@ export default function ServicePage() {
accessorFn: row => row.service.enable_trigger_task ?? false, accessorFn: row => row.service.enable_trigger_task ?? false,
}, },
{ {
header: "Tasks to trigger on an alarm", header: "Tasks to trigger on alert",
accessorKey: "service.failTriggerTasks", accessorKey: "service.failTriggerTasks",
accessorFn: row => row.service.fail_trigger_tasks, accessorFn: row => row.service.fail_trigger_tasks,
}, },

4
src/types/alert-rule.tsx Normal file
View File

@@ -0,0 +1,4 @@
export const triggerModes: Record<number, string> = {
0: "Always",
1: "Once",
}

View File

@@ -390,19 +390,22 @@ export interface ModelRule {
/** 覆盖范围 RuleCoverAll/IgnoreAll */ /** 覆盖范围 RuleCoverAll/IgnoreAll */
cover: number; cover: number;
/** 流量统计周期 */ /** 流量统计周期 */
cycle_interval: number; cycle_interval?: number;
/** 流量统计的开始时间 */ /** 流量统计的开始时间 */
cycle_start: string; cycle_start?: string;
/** 流量统计周期单位默认hour,可选(hour, day, week, month, year) */ /**
cycle_unit: string; * 流量统计周期单位默认hour,可选(hour, day, week, month, year)
* @default "hour"
*/
cycle_unit?: "hour" | "day" | "week" | "month" | "year";
/** 持续时间 (秒) */ /** 持续时间 (秒) */
duration: number; duration?: number;
/** 覆盖范围的排除 */ /** 覆盖范围的排除 */
ignore: Record<string, boolean>; ignore?: Record<string, boolean>;
/** 最大阈值 (百分比、字节 kb ÷ 1024) */ /** 最大阈值 (百分比、字节 kb ÷ 1024) */
max: number; max?: number;
/** 最小阈值 (百分比、字节 kb ÷ 1024) */ /** 最小阈值 (百分比、字节 kb ÷ 1024) */
min: number; min?: number;
/** /**
* 指标类型cpu、memory、swap、disk、net_in_speed、net_out_speed * 指标类型cpu、memory、swap、disk、net_in_speed、net_out_speed
* net_all_speed、transfer_in、transfer_out、transfer_all、offline * net_all_speed、transfer_in、transfer_out、transfer_all、offline

View File

@@ -6,3 +6,7 @@ export * from './ddns';
export * from './serverStore'; export * from './serverStore';
export * from './serverContext'; export * from './serverContext';
export * from './cron'; export * from './cron';
export * from './notification';
export * from './alert-rule';
export * from './notificationStore';
export * from './notificationContext';

View File

@@ -0,0 +1,9 @@
export const nrequestMethods: Record<number, string> = {
1: "GET",
2: "POST",
}
export const nrequestTypes: Record<number, string> = {
1: "JSON",
2: "Form",
}

View File

@@ -0,0 +1,6 @@
import { ModelNotification, ModelNotificationGroupResponseItem } from "@/types";
export interface NotificationContextProps {
notifiers?: ModelNotification[];
notifierGroup?: ModelNotificationGroupResponseItem[];
}

View File

@@ -0,0 +1,8 @@
import { ModelNotification, ModelNotificationGroupResponseItem } from "@/types";
export interface NotificationStore {
notifiers?: ModelNotification[];
notifierGroup?: ModelNotificationGroupResponseItem[];
setNotifier: (notifiers?: ModelNotification[]) => void;
setNotifierGroup: (notifierGroup?: ModelNotificationGroupResponseItem[]) => void;
}