mirror of
https://github.com/fosrl/pangolin.git
synced 2026-05-04 19:44:47 +00:00
add node graph and editor
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import AlertRuleCredenza from "@app/components/AlertRuleCredenza";
|
||||
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
DataTable,
|
||||
ExtendedColumnDef
|
||||
} from "@app/components/ui/data-table";
|
||||
import { DataTable, ExtendedColumnDef } from "@app/components/ui/data-table";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -24,6 +20,8 @@ import {
|
||||
} from "@app/lib/alertRulesLocalStorage";
|
||||
import { ArrowUpDown, MoreHorizontal } from "lucide-react";
|
||||
import moment from "moment";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Badge } from "@app/components/ui/badge";
|
||||
@@ -32,7 +30,14 @@ type AlertingRulesTableProps = {
|
||||
orgId: string;
|
||||
};
|
||||
|
||||
function sourceSummary(rule: AlertRule, t: (k: string, o?: Record<string, number | string>) => string) {
|
||||
function ruleHref(orgId: string, ruleId: string) {
|
||||
return `/${orgId}/settings/alerting/${ruleId}`;
|
||||
}
|
||||
|
||||
function sourceSummary(
|
||||
rule: AlertRule,
|
||||
t: (k: string, o?: Record<string, number | string>) => string
|
||||
) {
|
||||
if (rule.source.type === "site") {
|
||||
return t("alertingSummarySites", {
|
||||
count: rule.source.siteIds.length
|
||||
@@ -83,10 +88,9 @@ function actionBadges(rule: AlertRule, t: (k: string) => string) {
|
||||
}
|
||||
|
||||
export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
const [rows, setRows] = useState<AlertRule[]>([]);
|
||||
const [credenzaOpen, setCredenzaOpen] = useState(false);
|
||||
const [credenzaRule, setCredenzaRule] = useState<AlertRule | null>(null);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [selected, setSelected] = useState<AlertRule | null>(null);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
@@ -146,10 +150,10 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
{
|
||||
id: "source",
|
||||
friendlyName: t("alertingColumnSource"),
|
||||
header: () => <span className="p-3">{t("alertingColumnSource")}</span>,
|
||||
cell: ({ row }) => (
|
||||
<span>{sourceSummary(row.original, t)}</span>
|
||||
)
|
||||
header: () => (
|
||||
<span className="p-3">{t("alertingColumnSource")}</span>
|
||||
),
|
||||
cell: ({ row }) => <span>{sourceSummary(row.original, t)}</span>
|
||||
},
|
||||
{
|
||||
id: "trigger",
|
||||
@@ -190,9 +194,7 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
friendlyName: t("createdAt"),
|
||||
header: () => (
|
||||
<span className="p-3">{t("createdAt")}</span>
|
||||
),
|
||||
header: () => <span className="p-3">{t("createdAt")}</span>,
|
||||
cell: ({ row }) => (
|
||||
<span>{moment(row.original.createdAt).format("lll")}</span>
|
||||
)
|
||||
@@ -204,13 +206,10 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
cell: ({ row }) => {
|
||||
const r = row.original;
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">
|
||||
{t("openMenu")}
|
||||
</span>
|
||||
@@ -218,14 +217,6 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setCredenzaRule(r);
|
||||
setCredenzaOpen(true);
|
||||
}}
|
||||
>
|
||||
{t("edit")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelected(r);
|
||||
@@ -238,6 +229,11 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={ruleHref(orgId, r.id)}>
|
||||
{t("edit")}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -246,16 +242,6 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<AlertRuleCredenza
|
||||
open={credenzaOpen}
|
||||
setOpen={(v) => {
|
||||
setCredenzaOpen(v);
|
||||
if (!v) setCredenzaRule(null);
|
||||
}}
|
||||
orgId={orgId}
|
||||
rule={credenzaRule}
|
||||
onSaved={refreshFromStorage}
|
||||
/>
|
||||
{selected && (
|
||||
<ConfirmDeleteDialog
|
||||
open={deleteOpen}
|
||||
@@ -282,8 +268,7 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
|
||||
searchPlaceholder={t("alertingSearchRules")}
|
||||
searchColumn="name"
|
||||
onAdd={() => {
|
||||
setCredenzaRule(null);
|
||||
setCredenzaOpen(true);
|
||||
router.push(`/${orgId}/settings/alerting/create`);
|
||||
}}
|
||||
onRefresh={refreshData}
|
||||
isRefreshing={isRefreshing}
|
||||
|
||||
981
src/components/alert-rule-editor/AlertRuleFields.tsx
Normal file
981
src/components/alert-rule-editor/AlertRuleFields.tsx
Normal file
@@ -0,0 +1,981 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList
|
||||
} from "@app/components/ui/command";
|
||||
import {
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger
|
||||
} from "@app/components/ui/popover";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from "@app/components/ui/select";
|
||||
import { TagInput } from "@app/components/tags/tag-input";
|
||||
import { getUserDisplayName } from "@app/lib/getUserDisplayName";
|
||||
import {
|
||||
type AlertRuleFormAction,
|
||||
type AlertRuleFormValues
|
||||
} from "@app/lib/alertRuleForm";
|
||||
import { orgQueries } from "@app/lib/queries";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronsUpDown, Plus, Trash2 } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { Control, UseFormReturn } from "react-hook-form";
|
||||
import { useFormContext, useWatch } from "react-hook-form";
|
||||
import { useDebounce } from "use-debounce";
|
||||
|
||||
export function DropdownAddAction({
|
||||
onPick
|
||||
}: {
|
||||
onPick: (type: "notify" | "sms" | "webhook") => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button type="button" variant="outline" size="sm">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
{t("alertingAddAction")}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-52 p-2" align="end">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="justify-start"
|
||||
onClick={() => {
|
||||
onPick("notify");
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{t("alertingActionNotify")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="justify-start"
|
||||
onClick={() => {
|
||||
onPick("sms");
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{t("alertingActionSms")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="justify-start"
|
||||
onClick={() => {
|
||||
onPick("webhook");
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{t("alertingActionWebhook")}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
function SiteMultiSelect({
|
||||
orgId,
|
||||
value,
|
||||
onChange
|
||||
}: {
|
||||
orgId: string;
|
||||
value: number[];
|
||||
onChange: (v: number[]) => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [q, setQ] = useState("");
|
||||
const [debounced] = useDebounce(q, 150);
|
||||
const { data: sites = [] } = useQuery(
|
||||
orgQueries.sites({ orgId, query: debounced, perPage: 500 })
|
||||
);
|
||||
const toggle = (id: number) => {
|
||||
if (value.includes(id)) {
|
||||
onChange(value.filter((x) => x !== id));
|
||||
} else {
|
||||
onChange([...value, id]);
|
||||
}
|
||||
};
|
||||
const summary =
|
||||
value.length === 0
|
||||
? t("alertingSelectSites")
|
||||
: t("alertingSitesSelected", { count: value.length });
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">{summary}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder={t("siteSearch")}
|
||||
value={q}
|
||||
onValueChange={setQ}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("siteNotFound")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{sites.map((s) => (
|
||||
<CommandItem
|
||||
key={s.siteId}
|
||||
value={`${s.siteId}`}
|
||||
onSelect={() => toggle(s.siteId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={value.includes(s.siteId)}
|
||||
className="mr-2 pointer-events-none"
|
||||
/>
|
||||
{s.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
const ALERT_RESOURCES_PAGE_SIZE = 10;
|
||||
|
||||
function ResourceTenMultiSelect({
|
||||
orgId,
|
||||
value,
|
||||
onChange
|
||||
}: {
|
||||
orgId: string;
|
||||
value: number[];
|
||||
onChange: (v: number[]) => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const { data: resources = [] } = useQuery(
|
||||
orgQueries.resources({
|
||||
orgId,
|
||||
perPage: ALERT_RESOURCES_PAGE_SIZE
|
||||
})
|
||||
);
|
||||
const rows = useMemo(() => {
|
||||
const out: {
|
||||
resourceId: number;
|
||||
name: string;
|
||||
targetIds: number[];
|
||||
}[] = [];
|
||||
for (const r of resources) {
|
||||
const targetIds = r.targets.map((x) => x.targetId);
|
||||
if (targetIds.length > 0) {
|
||||
out.push({
|
||||
resourceId: r.resourceId,
|
||||
name: r.name,
|
||||
targetIds
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}, [resources]);
|
||||
|
||||
const selectedResourceCount = useMemo(
|
||||
() =>
|
||||
rows.filter(
|
||||
(row) =>
|
||||
row.targetIds.length > 0 &&
|
||||
row.targetIds.every((id) => value.includes(id))
|
||||
).length,
|
||||
[rows, value]
|
||||
);
|
||||
|
||||
const toggle = (targetIds: number[]) => {
|
||||
const allOn =
|
||||
targetIds.length > 0 &&
|
||||
targetIds.every((id) => value.includes(id));
|
||||
if (allOn) {
|
||||
onChange(value.filter((id) => !targetIds.includes(id)));
|
||||
} else {
|
||||
onChange([...new Set([...value, ...targetIds])]);
|
||||
}
|
||||
};
|
||||
|
||||
const summary =
|
||||
selectedResourceCount === 0
|
||||
? t("alertingSelectResources")
|
||||
: t("alertingResourcesSelected", {
|
||||
count: selectedResourceCount
|
||||
});
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">{summary}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-[var(--radix-popover-trigger-width)] p-0"
|
||||
align="start"
|
||||
>
|
||||
<div className="max-h-72 overflow-y-auto p-2 space-y-0.5">
|
||||
{rows.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground px-2 py-1.5">
|
||||
{t("alertingResourcesEmpty")}
|
||||
</p>
|
||||
) : (
|
||||
rows.map((row) => {
|
||||
const checked =
|
||||
row.targetIds.length > 0 &&
|
||||
row.targetIds.every((id) =>
|
||||
value.includes(id)
|
||||
);
|
||||
return (
|
||||
<button
|
||||
key={row.resourceId}
|
||||
type="button"
|
||||
onClick={() => toggle(row.targetIds)}
|
||||
className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent"
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
className="pointer-events-none shrink-0"
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="truncate">
|
||||
{row.name}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export function ActionBlock({
|
||||
orgId,
|
||||
index,
|
||||
control,
|
||||
form,
|
||||
onRemove,
|
||||
canRemove
|
||||
}: {
|
||||
orgId: string;
|
||||
index: number;
|
||||
control: Control<AlertRuleFormValues>;
|
||||
form: UseFormReturn<AlertRuleFormValues>;
|
||||
onRemove: () => void;
|
||||
canRemove: boolean;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const type = form.watch(`actions.${index}.type`);
|
||||
return (
|
||||
<div className="rounded-lg border p-4 space-y-3 relative">
|
||||
{canRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute top-2 right-2 h-8 w-8"
|
||||
onClick={onRemove}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
)}
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.type`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingActionType")}</FormLabel>
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={(v) => {
|
||||
const nt = v as AlertRuleFormAction["type"];
|
||||
if (nt === "notify") {
|
||||
form.setValue(`actions.${index}`, {
|
||||
type: "notify",
|
||||
userIds: [],
|
||||
roleIds: [],
|
||||
emailTags: []
|
||||
});
|
||||
} else if (nt === "sms") {
|
||||
form.setValue(`actions.${index}`, {
|
||||
type: "sms",
|
||||
phoneTags: []
|
||||
});
|
||||
} else {
|
||||
form.setValue(`actions.${index}`, {
|
||||
type: "webhook",
|
||||
url: "",
|
||||
method: "POST",
|
||||
headers: [{ key: "", value: "" }],
|
||||
secret: ""
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger className="max-w-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="notify">
|
||||
{t("alertingActionNotify")}
|
||||
</SelectItem>
|
||||
<SelectItem value="sms">
|
||||
{t("alertingActionSms")}
|
||||
</SelectItem>
|
||||
<SelectItem value="webhook">
|
||||
{t("alertingActionWebhook")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{type === "notify" && (
|
||||
<NotifyActionFields
|
||||
orgId={orgId}
|
||||
index={index}
|
||||
control={control}
|
||||
form={form}
|
||||
/>
|
||||
)}
|
||||
{type === "sms" && (
|
||||
<SmsActionFields index={index} control={control} form={form} />
|
||||
)}
|
||||
{type === "webhook" && (
|
||||
<WebhookActionFields
|
||||
index={index}
|
||||
control={control}
|
||||
form={form}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NotifyActionFields({
|
||||
orgId,
|
||||
index,
|
||||
control,
|
||||
form
|
||||
}: {
|
||||
orgId: string;
|
||||
index: number;
|
||||
control: Control<AlertRuleFormValues>;
|
||||
form: UseFormReturn<AlertRuleFormValues>;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [emailActiveIdx, setEmailActiveIdx] = useState<number | null>(null);
|
||||
const userIds = form.watch(`actions.${index}.userIds`) ?? [];
|
||||
const roleIds = form.watch(`actions.${index}.roleIds`) ?? [];
|
||||
const emailTags = form.watch(`actions.${index}.emailTags`) ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-3 pt-1">
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingNotifyUsers")}</FormLabel>
|
||||
<UserMultiSelect
|
||||
orgId={orgId}
|
||||
value={userIds}
|
||||
onChange={(ids) =>
|
||||
form.setValue(`actions.${index}.userIds`, ids)
|
||||
}
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingNotifyRoles")}</FormLabel>
|
||||
<RoleMultiSelect
|
||||
orgId={orgId}
|
||||
value={roleIds}
|
||||
onChange={(ids) =>
|
||||
form.setValue(`actions.${index}.roleIds`, ids)
|
||||
}
|
||||
/>
|
||||
</FormItem>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.emailTags`}
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingNotifyEmails")}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
tags={emailTags}
|
||||
setTags={(updater) => {
|
||||
const next =
|
||||
typeof updater === "function"
|
||||
? updater(emailTags)
|
||||
: updater;
|
||||
form.setValue(
|
||||
`actions.${index}.emailTags`,
|
||||
next
|
||||
);
|
||||
}}
|
||||
activeTagIndex={emailActiveIdx}
|
||||
setActiveTagIndex={setEmailActiveIdx}
|
||||
placeholder={t("alertingEmailPlaceholder")}
|
||||
delimiterList={[",", "Enter"]}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SmsActionFields({
|
||||
index,
|
||||
control,
|
||||
form
|
||||
}: {
|
||||
index: number;
|
||||
control: Control<AlertRuleFormValues>;
|
||||
form: UseFormReturn<AlertRuleFormValues>;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [phoneActiveIdx, setPhoneActiveIdx] = useState<number | null>(null);
|
||||
const phoneTags = form.watch(`actions.${index}.phoneTags`) ?? [];
|
||||
return (
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.phoneTags`}
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingSmsNumbers")}</FormLabel>
|
||||
<FormControl>
|
||||
<TagInput
|
||||
tags={phoneTags}
|
||||
setTags={(updater) => {
|
||||
const next =
|
||||
typeof updater === "function"
|
||||
? updater(phoneTags)
|
||||
: updater;
|
||||
form.setValue(
|
||||
`actions.${index}.phoneTags`,
|
||||
next
|
||||
);
|
||||
}}
|
||||
activeTagIndex={phoneActiveIdx}
|
||||
setActiveTagIndex={setPhoneActiveIdx}
|
||||
placeholder={t("alertingSmsPlaceholder")}
|
||||
delimiterList={[",", "Enter"]}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookActionFields({
|
||||
index,
|
||||
control,
|
||||
form
|
||||
}: {
|
||||
index: number;
|
||||
control: Control<AlertRuleFormValues>;
|
||||
form: UseFormReturn<AlertRuleFormValues>;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
return (
|
||||
<div className="space-y-3 pt-1">
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.url`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="https://example.com/hook"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.method`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingWebhookMethod")}</FormLabel>
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger className="max-w-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{["GET", "POST", "PUT", "PATCH"].map((m) => (
|
||||
<SelectItem key={m} value={m}>
|
||||
{m}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.secret`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingWebhookSecret")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder={t(
|
||||
"alertingWebhookSecretPlaceholder"
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<WebhookHeadersField index={index} control={control} form={form} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookHeadersField({
|
||||
index,
|
||||
control,
|
||||
form
|
||||
}: {
|
||||
index: number;
|
||||
control: Control<AlertRuleFormValues>;
|
||||
form: UseFormReturn<AlertRuleFormValues>;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const headers =
|
||||
form.watch(`actions.${index}.headers` as const) ?? [];
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<FormLabel>{t("alertingWebhookHeaders")}</FormLabel>
|
||||
{headers.map((_, hi) => (
|
||||
<div key={hi} className="flex gap-2 items-start">
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.headers.${hi}.key`}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormControl>
|
||||
<Input {...field} placeholder="Key" />
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`actions.${index}.headers.${hi}.value`}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormControl>
|
||||
<Input {...field} placeholder="Value" />
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0"
|
||||
onClick={() => {
|
||||
const cur =
|
||||
form.getValues(
|
||||
`actions.${index}.headers`
|
||||
) ?? [];
|
||||
form.setValue(
|
||||
`actions.${index}.headers`,
|
||||
cur.filter((__, i) => i !== hi)
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const cur =
|
||||
form.getValues(`actions.${index}.headers`) ?? [];
|
||||
form.setValue(`actions.${index}.headers`, [
|
||||
...cur,
|
||||
{ key: "", value: "" }
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
{t("alertingAddHeader")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserMultiSelect({
|
||||
orgId,
|
||||
value,
|
||||
onChange
|
||||
}: {
|
||||
orgId: string;
|
||||
value: string[];
|
||||
onChange: (v: string[]) => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [q, setQ] = useState("");
|
||||
const [debounced] = useDebounce(q, 150);
|
||||
const { data: users = [] } = useQuery(orgQueries.users({ orgId }));
|
||||
const shown = useMemo(() => {
|
||||
const qq = debounced.trim().toLowerCase();
|
||||
if (!qq) return users.slice(0, 200);
|
||||
return users
|
||||
.filter((u) => {
|
||||
const label = getUserDisplayName({
|
||||
email: u.email,
|
||||
name: u.name,
|
||||
username: u.username
|
||||
}).toLowerCase();
|
||||
return (
|
||||
label.includes(qq) ||
|
||||
(u.email ?? "").toLowerCase().includes(qq)
|
||||
);
|
||||
})
|
||||
.slice(0, 200);
|
||||
}, [users, debounced]);
|
||||
const toggle = (id: string) => {
|
||||
if (value.includes(id)) {
|
||||
onChange(value.filter((x) => x !== id));
|
||||
} else {
|
||||
onChange([...value, id]);
|
||||
}
|
||||
};
|
||||
const summary =
|
||||
value.length === 0
|
||||
? t("alertingSelectUsers")
|
||||
: t("alertingUsersSelected", { count: value.length });
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">{summary}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder={t("searchPlaceholder")}
|
||||
value={q}
|
||||
onValueChange={setQ}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>{t("noResults")}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{shown.map((u) => {
|
||||
const uid = String(u.id);
|
||||
return (
|
||||
<CommandItem
|
||||
key={uid}
|
||||
value={uid}
|
||||
onSelect={() => toggle(uid)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={value.includes(uid)}
|
||||
className="mr-2 pointer-events-none"
|
||||
/>
|
||||
{getUserDisplayName({
|
||||
email: u.email,
|
||||
name: u.name,
|
||||
username: u.username
|
||||
})}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
function RoleMultiSelect({
|
||||
orgId,
|
||||
value,
|
||||
onChange
|
||||
}: {
|
||||
orgId: string;
|
||||
value: number[];
|
||||
onChange: (v: number[]) => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const { data: roles = [] } = useQuery(orgQueries.roles({ orgId }));
|
||||
const toggle = (id: number) => {
|
||||
if (value.includes(id)) {
|
||||
onChange(value.filter((x) => x !== id));
|
||||
} else {
|
||||
onChange([...value, id]);
|
||||
}
|
||||
};
|
||||
const summary =
|
||||
value.length === 0
|
||||
? t("alertingSelectRoles")
|
||||
: t("alertingRolesSelected", { count: value.length });
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">{summary}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandList>
|
||||
<CommandGroup>
|
||||
{roles.map((r) => (
|
||||
<CommandItem
|
||||
key={r.roleId}
|
||||
value={`role-${r.roleId}`}
|
||||
onSelect={() => toggle(r.roleId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={value.includes(r.roleId)}
|
||||
className="mr-2 pointer-events-none"
|
||||
/>
|
||||
{r.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export function AlertRuleSourceFields({
|
||||
orgId,
|
||||
control
|
||||
}: {
|
||||
orgId: string;
|
||||
control: Control<AlertRuleFormValues>;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const { setValue, getValues } = useFormContext<AlertRuleFormValues>();
|
||||
const sourceType = useWatch({ control, name: "sourceType" });
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<FormField
|
||||
control={control}
|
||||
name="sourceType"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingSourceType")}</FormLabel>
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={(v) => {
|
||||
const next = v as AlertRuleFormValues["sourceType"];
|
||||
field.onChange(next);
|
||||
const curTrigger = getValues("trigger");
|
||||
if (next === "site") {
|
||||
if (
|
||||
curTrigger !== "site_online" &&
|
||||
curTrigger !== "site_offline"
|
||||
) {
|
||||
setValue("trigger", "site_offline", {
|
||||
shouldValidate: true
|
||||
});
|
||||
}
|
||||
} else if (
|
||||
curTrigger !== "health_check_healthy" &&
|
||||
curTrigger !== "health_check_unhealthy"
|
||||
) {
|
||||
setValue(
|
||||
"trigger",
|
||||
"health_check_unhealthy",
|
||||
{ shouldValidate: true }
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="site">
|
||||
{t("alertingSourceSite")}
|
||||
</SelectItem>
|
||||
<SelectItem value="health_check">
|
||||
{t("alertingSourceHealthCheck")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{sourceType === "site" ? (
|
||||
<FormField
|
||||
control={control}
|
||||
name="siteIds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingPickSites")}</FormLabel>
|
||||
<SiteMultiSelect
|
||||
orgId={orgId}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<FormField
|
||||
control={control}
|
||||
name="targetIds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingPickResources")}</FormLabel>
|
||||
<ResourceTenMultiSelect
|
||||
orgId={orgId}
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AlertRuleTriggerFields({
|
||||
control
|
||||
}: {
|
||||
control: Control<AlertRuleFormValues>;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const sourceType = useWatch({ control, name: "sourceType" });
|
||||
return (
|
||||
<FormField
|
||||
control={control}
|
||||
name="trigger"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("alertingTrigger")}</FormLabel>
|
||||
<Select
|
||||
key={sourceType}
|
||||
value={field.value}
|
||||
onValueChange={field.onChange}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{sourceType === "site" ? (
|
||||
<>
|
||||
<SelectItem value="site_online">
|
||||
{t("alertingTriggerSiteOnline")}
|
||||
</SelectItem>
|
||||
<SelectItem value="site_offline">
|
||||
{t("alertingTriggerSiteOffline")}
|
||||
</SelectItem>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<SelectItem value="health_check_healthy">
|
||||
{t("alertingTriggerHcHealthy")}
|
||||
</SelectItem>
|
||||
<SelectItem value="health_check_unhealthy">
|
||||
{t("alertingTriggerHcUnhealthy")}
|
||||
</SelectItem>
|
||||
</>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
715
src/components/alert-rule-editor/AlertRuleGraphEditor.tsx
Normal file
715
src/components/alert-rule-editor/AlertRuleGraphEditor.tsx
Normal file
@@ -0,0 +1,715 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ActionBlock,
|
||||
AlertRuleSourceFields,
|
||||
AlertRuleTriggerFields,
|
||||
DropdownAddAction
|
||||
} from "@app/components/alert-rule-editor/AlertRuleFields";
|
||||
import { SettingsContainer } from "@app/components/Settings";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from "@app/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { Switch } from "@app/components/ui/switch";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import {
|
||||
buildFormSchema,
|
||||
defaultFormValues,
|
||||
formValuesToRule,
|
||||
type AlertRuleFormAction,
|
||||
type AlertRuleFormValues
|
||||
} from "@app/lib/alertRuleForm";
|
||||
import { upsertRule } from "@app/lib/alertRulesLocalStorage";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import {
|
||||
Background,
|
||||
Handle,
|
||||
Position,
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
useEdgesState,
|
||||
useNodesState,
|
||||
type Edge,
|
||||
type Node,
|
||||
type NodeProps,
|
||||
type NodeTypes
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Check, ChevronLeft } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useFieldArray, useForm, useWatch } from "react-hook-form";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
type AlertRuleT = ReturnType<typeof useTranslations>;
|
||||
|
||||
export type AlertStepId = "source" | "trigger" | "actions";
|
||||
|
||||
type AlertStepNodeData = {
|
||||
roleLabel: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
configured: boolean;
|
||||
accent: string;
|
||||
topBorderClass: string;
|
||||
};
|
||||
|
||||
function summarizeSource(v: AlertRuleFormValues, t: AlertRuleT) {
|
||||
if (v.sourceType === "site") {
|
||||
if (v.siteIds.length === 0) {
|
||||
return t("alertingNodeNotConfigured");
|
||||
}
|
||||
return t("alertingSummarySites", { count: v.siteIds.length });
|
||||
}
|
||||
if (v.targetIds.length === 0) {
|
||||
return t("alertingNodeNotConfigured");
|
||||
}
|
||||
return t("alertingSummaryHealthChecks", { count: v.targetIds.length });
|
||||
}
|
||||
|
||||
function summarizeTrigger(v: AlertRuleFormValues, t: AlertRuleT) {
|
||||
switch (v.trigger) {
|
||||
case "site_online":
|
||||
return t("alertingTriggerSiteOnline");
|
||||
case "site_offline":
|
||||
return t("alertingTriggerSiteOffline");
|
||||
case "health_check_healthy":
|
||||
return t("alertingTriggerHcHealthy");
|
||||
case "health_check_unhealthy":
|
||||
return t("alertingTriggerHcUnhealthy");
|
||||
default:
|
||||
return v.trigger;
|
||||
}
|
||||
}
|
||||
|
||||
function oneActionConfigured(a: AlertRuleFormAction): boolean {
|
||||
if (a.type === "notify") {
|
||||
return (
|
||||
a.userIds.length > 0 ||
|
||||
a.roleIds.length > 0 ||
|
||||
a.emailTags.length > 0
|
||||
);
|
||||
}
|
||||
if (a.type === "sms") {
|
||||
return a.phoneTags.length > 0;
|
||||
}
|
||||
try {
|
||||
new URL(a.url.trim());
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function actionTypeLabel(a: AlertRuleFormAction, t: AlertRuleT): string {
|
||||
switch (a.type) {
|
||||
case "notify":
|
||||
return t("alertingActionNotify");
|
||||
case "sms":
|
||||
return t("alertingActionSms");
|
||||
case "webhook":
|
||||
return t("alertingActionWebhook");
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeOneAction(a: AlertRuleFormAction, t: AlertRuleT): string {
|
||||
if (a.type === "notify") {
|
||||
if (
|
||||
a.userIds.length === 0 &&
|
||||
a.roleIds.length === 0 &&
|
||||
a.emailTags.length === 0
|
||||
) {
|
||||
return t("alertingNodeNotConfigured");
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (a.userIds.length > 0) {
|
||||
parts.push(t("alertingUsersSelected", { count: a.userIds.length }));
|
||||
}
|
||||
if (a.roleIds.length > 0) {
|
||||
parts.push(t("alertingRolesSelected", { count: a.roleIds.length }));
|
||||
}
|
||||
if (a.emailTags.length > 0) {
|
||||
parts.push(
|
||||
`${t("alertingNotifyEmails")} (${a.emailTags.length})`
|
||||
);
|
||||
}
|
||||
return parts.join(" · ");
|
||||
}
|
||||
if (a.type === "sms") {
|
||||
if (a.phoneTags.length === 0) {
|
||||
return t("alertingNodeNotConfigured");
|
||||
}
|
||||
return `${t("alertingSmsNumbers")}: ${a.phoneTags.length}`;
|
||||
}
|
||||
const url = a.url.trim();
|
||||
if (!url) {
|
||||
return t("alertingNodeNotConfigured");
|
||||
}
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return t("alertingNodeNotConfigured");
|
||||
}
|
||||
}
|
||||
|
||||
function stepConfigured(
|
||||
step: "source" | "trigger",
|
||||
v: AlertRuleFormValues
|
||||
): boolean {
|
||||
if (step === "source") {
|
||||
return v.sourceType === "site"
|
||||
? v.siteIds.length > 0
|
||||
: v.targetIds.length > 0;
|
||||
}
|
||||
return Boolean(v.trigger);
|
||||
}
|
||||
|
||||
function buildActionStepNodeData(
|
||||
index: number,
|
||||
action: AlertRuleFormAction,
|
||||
t: AlertRuleT
|
||||
): AlertStepNodeData {
|
||||
return {
|
||||
roleLabel: `${t("alertingNodeRoleAction")} ${index + 1}`,
|
||||
title: actionTypeLabel(action, t),
|
||||
subtitle: summarizeOneAction(action, t),
|
||||
configured: oneActionConfigured(action),
|
||||
accent: "text-amber-600 dark:text-amber-400",
|
||||
topBorderClass: "border-t-amber-500"
|
||||
};
|
||||
}
|
||||
|
||||
function buildActionsPlaceholderNodeData(t: AlertRuleT): AlertStepNodeData {
|
||||
return {
|
||||
roleLabel: t("alertingNodeRoleAction"),
|
||||
title: t("alertingSectionActions"),
|
||||
subtitle: t("alertingNodeNotConfigured"),
|
||||
configured: false,
|
||||
accent: "text-amber-600 dark:text-amber-400",
|
||||
topBorderClass: "border-t-amber-500"
|
||||
};
|
||||
}
|
||||
|
||||
const AlertStepNode = memo(function AlertStepNodeFn({
|
||||
data,
|
||||
selected
|
||||
}: NodeProps<Node<AlertStepNodeData>>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative rounded-xl border-2 border-t-[3px] bg-card px-5 py-4 shadow-sm min-w-[260px] max-w-[320px] transition-shadow",
|
||||
data.topBorderClass,
|
||||
selected
|
||||
? "border-primary ring-2 ring-primary/25 shadow-md"
|
||||
: "border-border"
|
||||
)}
|
||||
>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
className="!bg-muted-foreground !w-2 !h-2"
|
||||
/>
|
||||
{data.configured && (
|
||||
<Check
|
||||
className="absolute top-3 right-3 h-5 w-5 text-green-600"
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
<p
|
||||
className={cn(
|
||||
"text-[11px] font-semibold uppercase tracking-wide",
|
||||
data.accent
|
||||
)}
|
||||
>
|
||||
{data.roleLabel}
|
||||
</p>
|
||||
<p className="font-semibold text-base mt-1">{data.title}</p>
|
||||
<p className="text-sm text-muted-foreground mt-1.5 line-clamp-3 leading-snug">
|
||||
{data.subtitle}
|
||||
</p>
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
className="!bg-muted-foreground !w-2 !h-2"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const nodeTypes: NodeTypes = {
|
||||
alertStep: AlertStepNode
|
||||
};
|
||||
|
||||
const ACTION_NODE_X_GAP = 280;
|
||||
const ACTION_NODE_Y = 468;
|
||||
const SOURCE_NODE_POS = { x: 120, y: 28 };
|
||||
const TRIGGER_NODE_POS = { x: 120, y: 248 };
|
||||
|
||||
function buildNodeData(
|
||||
stepId: "source" | "trigger",
|
||||
v: AlertRuleFormValues,
|
||||
t: AlertRuleT
|
||||
): AlertStepNodeData {
|
||||
const accents: Record<
|
||||
"source" | "trigger",
|
||||
{ accent: string; topBorderClass: string; role: string; title: string }
|
||||
> = {
|
||||
source: {
|
||||
accent: "text-blue-600 dark:text-blue-400",
|
||||
topBorderClass: "border-t-blue-500",
|
||||
role: t("alertingNodeRoleSource"),
|
||||
title: t("alertingSectionSource")
|
||||
},
|
||||
trigger: {
|
||||
accent: "text-emerald-600 dark:text-emerald-400",
|
||||
topBorderClass: "border-t-emerald-500",
|
||||
role: t("alertingNodeRoleTrigger"),
|
||||
title: t("alertingSectionTrigger")
|
||||
}
|
||||
};
|
||||
const meta = accents[stepId];
|
||||
const subtitle =
|
||||
stepId === "source"
|
||||
? summarizeSource(v, t)
|
||||
: summarizeTrigger(v, t);
|
||||
return {
|
||||
roleLabel: meta.role,
|
||||
title: meta.title,
|
||||
subtitle,
|
||||
configured: stepConfigured(stepId, v),
|
||||
accent: meta.accent,
|
||||
topBorderClass: meta.topBorderClass
|
||||
};
|
||||
}
|
||||
|
||||
type AlertRuleGraphEditorProps = {
|
||||
orgId: string;
|
||||
ruleId: string;
|
||||
createdAt: string;
|
||||
initialValues: AlertRuleFormValues;
|
||||
isNew: boolean;
|
||||
};
|
||||
|
||||
const FORM_ID = "alert-rule-graph-form";
|
||||
|
||||
export default function AlertRuleGraphEditor({
|
||||
orgId,
|
||||
ruleId,
|
||||
createdAt,
|
||||
initialValues,
|
||||
isNew
|
||||
}: AlertRuleGraphEditorProps) {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const schema = useMemo(() => buildFormSchema(t), [t]);
|
||||
const form = useForm<AlertRuleFormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialValues ?? defaultFormValues()
|
||||
});
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control: form.control,
|
||||
name: "actions"
|
||||
});
|
||||
|
||||
const wName = useWatch({ control: form.control, name: "name" }) ?? "";
|
||||
const wEnabled =
|
||||
useWatch({ control: form.control, name: "enabled" }) ?? true;
|
||||
const wSourceType =
|
||||
useWatch({ control: form.control, name: "sourceType" }) ?? "site";
|
||||
const wSiteIds =
|
||||
useWatch({ control: form.control, name: "siteIds" }) ?? [];
|
||||
const wTargetIds =
|
||||
useWatch({ control: form.control, name: "targetIds" }) ?? [];
|
||||
const wTrigger =
|
||||
useWatch({ control: form.control, name: "trigger" }) ??
|
||||
"site_offline";
|
||||
const wActions =
|
||||
useWatch({ control: form.control, name: "actions" }) ?? [];
|
||||
|
||||
const flowValues: AlertRuleFormValues = useMemo(
|
||||
() => ({
|
||||
name: wName,
|
||||
enabled: wEnabled,
|
||||
sourceType: wSourceType,
|
||||
siteIds: wSiteIds,
|
||||
targetIds: wTargetIds,
|
||||
trigger: wTrigger,
|
||||
actions: wActions
|
||||
}),
|
||||
[
|
||||
wName,
|
||||
wEnabled,
|
||||
wSourceType,
|
||||
wSiteIds,
|
||||
wTargetIds,
|
||||
wTrigger,
|
||||
wActions
|
||||
]
|
||||
);
|
||||
|
||||
const [selectedStep, setSelectedStep] = useState<string>("source");
|
||||
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
|
||||
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
|
||||
|
||||
const nodesSyncKeyRef = useRef("");
|
||||
useEffect(() => {
|
||||
const key = JSON.stringify({ flowValues, selectedStep });
|
||||
if (key === nodesSyncKeyRef.current) {
|
||||
return;
|
||||
}
|
||||
nodesSyncKeyRef.current = key;
|
||||
|
||||
const nActions = flowValues.actions.length;
|
||||
const actionNodes: Node[] =
|
||||
nActions === 0
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
type: "alertStep",
|
||||
position: {
|
||||
x: TRIGGER_NODE_POS.x,
|
||||
y: ACTION_NODE_Y
|
||||
},
|
||||
data: buildActionsPlaceholderNodeData(t),
|
||||
selected:
|
||||
selectedStep === "actions" ||
|
||||
selectedStep.startsWith("action-")
|
||||
}
|
||||
]
|
||||
: flowValues.actions.map((action, i) => {
|
||||
const totalWidth =
|
||||
(nActions - 1) * ACTION_NODE_X_GAP;
|
||||
const originX =
|
||||
TRIGGER_NODE_POS.x - totalWidth / 2;
|
||||
return {
|
||||
id: `action-${i}`,
|
||||
type: "alertStep",
|
||||
position: {
|
||||
x: originX + i * ACTION_NODE_X_GAP,
|
||||
y: ACTION_NODE_Y
|
||||
},
|
||||
data: buildActionStepNodeData(i, action, t),
|
||||
selected: selectedStep === `action-${i}`
|
||||
};
|
||||
});
|
||||
|
||||
setNodes([
|
||||
{
|
||||
id: "source",
|
||||
type: "alertStep",
|
||||
position: SOURCE_NODE_POS,
|
||||
data: buildNodeData("source", flowValues, t),
|
||||
selected: selectedStep === "source"
|
||||
},
|
||||
{
|
||||
id: "trigger",
|
||||
type: "alertStep",
|
||||
position: TRIGGER_NODE_POS,
|
||||
data: buildNodeData("trigger", flowValues, t),
|
||||
selected: selectedStep === "trigger"
|
||||
},
|
||||
...actionNodes
|
||||
]);
|
||||
|
||||
const nextEdges: Edge[] = [
|
||||
{
|
||||
id: "e-src-trg",
|
||||
source: "source",
|
||||
target: "trigger",
|
||||
animated: true
|
||||
},
|
||||
...(nActions === 0
|
||||
? [
|
||||
{
|
||||
id: "e-trg-act",
|
||||
source: "trigger",
|
||||
target: "actions",
|
||||
animated: true
|
||||
} as const
|
||||
]
|
||||
: flowValues.actions.map((_, i) => ({
|
||||
id: `e-trg-act-${i}`,
|
||||
source: "trigger",
|
||||
target: `action-${i}`,
|
||||
animated: true
|
||||
})))
|
||||
];
|
||||
setEdges(nextEdges);
|
||||
}, [flowValues, selectedStep, t, setNodes, setEdges]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedStep === "actions" && wActions.length > 0) {
|
||||
setSelectedStep("action-0");
|
||||
}
|
||||
}, [selectedStep, wActions.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (wActions.length === 0 && /^action-\d+$/.test(selectedStep)) {
|
||||
setSelectedStep("actions");
|
||||
}
|
||||
}, [wActions.length, selectedStep]);
|
||||
|
||||
useEffect(() => {
|
||||
const m = /^action-(\d+)$/.exec(selectedStep);
|
||||
if (!m) {
|
||||
return;
|
||||
}
|
||||
const i = Number(m[1], 10);
|
||||
if (i >= wActions.length) {
|
||||
setSelectedStep(
|
||||
wActions.length > 0
|
||||
? `action-${wActions.length - 1}`
|
||||
: "actions"
|
||||
);
|
||||
}
|
||||
}, [wActions.length, selectedStep]);
|
||||
|
||||
const onNodeClick = useCallback((_event: unknown, node: Node) => {
|
||||
setSelectedStep(node.id);
|
||||
}, []);
|
||||
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
const next = formValuesToRule(values, ruleId, createdAt);
|
||||
upsertRule(orgId, next);
|
||||
toast({ title: t("alertingRuleSaved") });
|
||||
if (isNew) {
|
||||
router.replace(`/${orgId}/settings/alerting/${ruleId}`);
|
||||
}
|
||||
});
|
||||
|
||||
const isActionsSidebar =
|
||||
selectedStep === "actions" || selectedStep.startsWith("action-");
|
||||
|
||||
const sidebarTitle = isActionsSidebar
|
||||
? t("alertingConfigureActions")
|
||||
: selectedStep === "source"
|
||||
? t("alertingConfigureSource")
|
||||
: t("alertingConfigureTrigger");
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form id={FORM_ID} onSubmit={onSubmit}>
|
||||
<SettingsContainer>
|
||||
<Card>
|
||||
<CardContent className="p-4 sm:p-5 space-y-4">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:flex-wrap md:items-center">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href={`/${orgId}/settings/alerting`}>
|
||||
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||
{t("alertingBackToRules")}
|
||||
</Link>
|
||||
</Button>
|
||||
{isNew && (
|
||||
<span className="text-xs rounded-md border bg-muted px-2 py-1 text-muted-foreground">
|
||||
{t("alertingDraftBadge")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1 min-w-0 md:min-w-[12rem] md:max-w-md">
|
||||
<FormLabel className="sr-only">
|
||||
{t("name")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={t(
|
||||
"alertingRuleNamePlaceholder"
|
||||
)}
|
||||
className="font-medium"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-3 md:ml-auto">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center gap-2 space-y-0">
|
||||
<FormLabel className="text-sm font-normal cursor-pointer whitespace-nowrap">
|
||||
{t("alertingRuleEnabled")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={
|
||||
field.onChange
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit">
|
||||
{t("save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 items-start">
|
||||
<Card className="flex flex-col w-full overflow-hidden">
|
||||
<CardHeader className="pb-2 pt-5 px-5 space-y-1 sm:px-6">
|
||||
<CardTitle className="text-lg font-bold tracking-tight">
|
||||
{t("alertingGraphCanvasTitle")}
|
||||
</CardTitle>
|
||||
<CardDescription className="pt-0">
|
||||
{t("alertingGraphCanvasDescription")}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4 sm:p-5 sm:px-6 pt-0">
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border bg-muted/30 overflow-hidden",
|
||||
"min-h-[min(66vh,560px)] lg:min-h-[680px]"
|
||||
)}
|
||||
>
|
||||
<ReactFlowProvider>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
nodeTypes={nodeTypes}
|
||||
onNodeClick={onNodeClick}
|
||||
fitView
|
||||
fitViewOptions={{
|
||||
padding: 0.35
|
||||
}}
|
||||
minZoom={0.5}
|
||||
maxZoom={1.25}
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
elementsSelectable
|
||||
panOnScroll
|
||||
zoomOnScroll
|
||||
proOptions={{
|
||||
hideAttribution: true
|
||||
}}
|
||||
className="bg-transparent !h-full !w-full min-h-[min(66vh,560px)] lg:min-h-[680px]"
|
||||
>
|
||||
<Background gap={16} size={1} />
|
||||
</ReactFlow>
|
||||
</ReactFlowProvider>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="flex flex-col w-full">
|
||||
<CardHeader className="pb-2 pt-5 px-5 space-y-1 sm:px-6">
|
||||
<CardTitle className="text-lg font-bold tracking-tight">
|
||||
{sidebarTitle}
|
||||
</CardTitle>
|
||||
<CardDescription className="pt-0">
|
||||
{t("alertingSidebarHint")}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4 sm:p-5 sm:px-6 pt-0">
|
||||
<div className="space-y-6">
|
||||
{selectedStep === "source" && (
|
||||
<AlertRuleSourceFields
|
||||
orgId={orgId}
|
||||
control={form.control}
|
||||
/>
|
||||
)}
|
||||
{selectedStep === "trigger" && (
|
||||
<AlertRuleTriggerFields
|
||||
control={form.control}
|
||||
/>
|
||||
)}
|
||||
{isActionsSidebar && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-sm font-medium">
|
||||
{t(
|
||||
"alertingSectionActions"
|
||||
)}
|
||||
</span>
|
||||
<DropdownAddAction
|
||||
onPick={(type) => {
|
||||
const newIndex =
|
||||
fields.length;
|
||||
if (type === "notify") {
|
||||
append({
|
||||
type: "notify",
|
||||
userIds: [],
|
||||
roleIds: [],
|
||||
emailTags: []
|
||||
});
|
||||
} else if (
|
||||
type === "sms"
|
||||
) {
|
||||
append({
|
||||
type: "sms",
|
||||
phoneTags: []
|
||||
});
|
||||
} else {
|
||||
append({
|
||||
type: "webhook",
|
||||
url: "",
|
||||
method: "POST",
|
||||
headers: [
|
||||
{
|
||||
key: "",
|
||||
value: ""
|
||||
}
|
||||
],
|
||||
secret: ""
|
||||
});
|
||||
}
|
||||
setSelectedStep(
|
||||
`action-${newIndex}`
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{fields.map((f, index) => (
|
||||
<ActionBlock
|
||||
key={f.id}
|
||||
orgId={orgId}
|
||||
index={index}
|
||||
control={form.control}
|
||||
form={form}
|
||||
onRemove={() =>
|
||||
remove(index)
|
||||
}
|
||||
canRemove
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</SettingsContainer>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user