Basic ui is working

This commit is contained in:
Owen
2026-04-15 15:26:27 -07:00
parent 3c6775992d
commit 5e505224d0
11 changed files with 634 additions and 318 deletions

View File

@@ -11,123 +11,131 @@ import {
} from "@app/components/ui/dropdown-menu";
import { Switch } from "@app/components/ui/switch";
import { toast } from "@app/hooks/useToast";
import {
type AlertRule,
deleteRule,
isoNow,
loadRules,
upsertRule
} from "@app/lib/alertRulesLocalStorage";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { orgQueries } from "@app/lib/queries";
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";
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
type AlertingRulesTableProps = {
orgId: string;
};
function ruleHref(orgId: string, ruleId: string) {
type AlertRuleRow = {
alertRuleId: number;
orgId: string;
name: string;
eventType: string;
enabled: boolean;
cooldownSeconds: number;
lastTriggeredAt: number | null;
createdAt: number;
updatedAt: number;
siteIds: number[];
healthCheckIds: number[];
};
function ruleHref(orgId: string, ruleId: number) {
return `/${orgId}/settings/alerting/${ruleId}`;
}
function sourceSummary(
rule: AlertRule,
rule: AlertRuleRow,
t: (k: string, o?: Record<string, number | string>) => string
) {
if (rule.source.type === "site") {
return t("alertingSummarySites", {
count: rule.source.siteIds.length
});
if (
rule.eventType === "site_online" ||
rule.eventType === "site_offline"
) {
return t("alertingSummarySites", { count: rule.siteIds.length });
}
return t("alertingSummaryHealthChecks", {
count: rule.source.targetIds.length
count: rule.healthCheckIds.length
});
}
function triggerLabel(rule: AlertRule, t: (k: string) => string) {
switch (rule.trigger) {
function triggerLabel(
rule: AlertRuleRow,
t: (k: string) => string
) {
switch (rule.eventType) {
case "site_online":
return t("alertingTriggerSiteOnline");
case "site_offline":
return t("alertingTriggerSiteOffline");
case "health_check_healthy":
return t("alertingTriggerHcHealthy");
case "health_check_unhealthy":
case "health_check_not_healthy":
return t("alertingTriggerHcUnhealthy");
default:
return rule.trigger;
return rule.eventType;
}
}
function actionBadges(rule: AlertRule, t: (k: string) => string) {
return rule.actions.map((a, i) => {
if (a.type === "notify") {
return (
<Badge key={`notify-${i}`} variant="secondary">
{t("alertingActionNotify")}
</Badge>
);
}
if (a.type === "sms") {
return (
<Badge key={`sms-${i}`} variant="secondary">
{t("alertingActionSms")}
</Badge>
);
}
return (
<Badge key={`webhook-${i}`} variant="secondary">
{t("alertingActionWebhook")}
</Badge>
);
});
}
export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
const router = useRouter();
const t = useTranslations();
const [rows, setRows] = useState<AlertRule[]>([]);
const api = createApiClient(useEnvContext());
const queryClient = useQueryClient();
const [deleteOpen, setDeleteOpen] = useState(false);
const [selected, setSelected] = useState<AlertRule | null>(null);
const [isRefreshing, setIsRefreshing] = useState(false);
const [selected, setSelected] = useState<AlertRuleRow | null>(null);
const [togglingId, setTogglingId] = useState<number | null>(null);
const refreshFromStorage = useCallback(() => {
setRows(loadRules(orgId));
}, [orgId]);
const {
data: rows = [],
isLoading,
refetch,
isRefetching
} = useQuery(orgQueries.alertRules({ orgId }));
useEffect(() => {
refreshFromStorage();
}, [refreshFromStorage]);
const invalidate = () =>
queryClient.invalidateQueries(orgQueries.alertRules({ orgId }));
const refreshData = async () => {
setIsRefreshing(true);
const setEnabled = async (rule: AlertRuleRow, enabled: boolean) => {
setTogglingId(rule.alertRuleId);
try {
await new Promise((r) => setTimeout(r, 200));
refreshFromStorage();
await api.post(`/org/${orgId}/alert-rule/${rule.alertRuleId}`, {
enabled
});
await invalidate();
} catch (e) {
toast({
title: t("error"),
description: formatAxiosError(e),
variant: "destructive"
});
} finally {
setIsRefreshing(false);
setTogglingId(null);
}
};
const setEnabled = (rule: AlertRule, enabled: boolean) => {
upsertRule(orgId, { ...rule, enabled, updatedAt: isoNow() });
refreshFromStorage();
};
const confirmDelete = async () => {
if (!selected) return;
deleteRule(orgId, selected.id);
refreshFromStorage();
setDeleteOpen(false);
setSelected(null);
toast({ title: t("alertingRuleDeleted") });
try {
await api.delete(
`/org/${orgId}/alert-rule/${selected.alertRuleId}`
);
await invalidate();
toast({ title: t("alertingRuleDeleted") });
} catch (e) {
toast({
title: t("error"),
description: formatAxiosError(e),
variant: "destructive"
});
} finally {
setDeleteOpen(false);
setSelected(null);
}
};
const columns: ExtendedColumnDef<AlertRule>[] = [
const columns: ExtendedColumnDef<AlertRuleRow>[] = [
{
accessorKey: "name",
enableHiding: false,
@@ -163,18 +171,6 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
),
cell: ({ row }) => <span>{triggerLabel(row.original, t)}</span>
},
{
id: "actionsCol",
friendlyName: t("alertingColumnActions"),
header: () => (
<span className="p-3">{t("alertingColumnActions")}</span>
),
cell: ({ row }) => (
<div className="flex flex-wrap gap-1 max-w-[14rem]">
{actionBadges(row.original, t)}
</div>
)
},
{
accessorKey: "enabled",
friendlyName: t("alertingColumnEnabled"),
@@ -186,6 +182,7 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
return (
<Switch
checked={r.enabled}
disabled={togglingId === r.alertRuleId}
onCheckedChange={(v) => setEnabled(r, v)}
/>
);
@@ -230,7 +227,7 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
</DropdownMenuContent>
</DropdownMenu>
<Button variant="outline" asChild>
<Link href={ruleHref(orgId, r.id)}>
<Link href={ruleHref(orgId, r.alertRuleId)}>
{t("edit")}
</Link>
</Button>
@@ -270,8 +267,8 @@ export default function AlertingRulesTable({ orgId }: AlertingRulesTableProps) {
onAdd={() => {
router.push(`/${orgId}/settings/alerting/create`);
}}
onRefresh={refreshData}
isRefreshing={isRefreshing}
onRefresh={() => refetch()}
isRefreshing={isRefetching || isLoading}
addButtonText={t("alertingAddRule")}
enableColumnVisibility
stickyLeftColumn="name"

View File

@@ -172,9 +172,7 @@ function SiteMultiSelect({
);
}
const ALERT_RESOURCES_PAGE_SIZE = 10;
function ResourceTenMultiSelect({
function HealthCheckMultiSelect({
orgId,
value,
onChange
@@ -185,58 +183,46 @@ function ResourceTenMultiSelect({
}) {
const t = useTranslations();
const [open, setOpen] = useState(false);
const { data: resources = [] } = useQuery(
orgQueries.resources({
orgId,
perPage: ALERT_RESOURCES_PAGE_SIZE
})
const [q, setQ] = useState("");
const [debounced] = useDebounce(q, 150);
const { data: healthChecks = [] } = useQuery(
orgQueries.healthChecks({ orgId })
);
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
});
}
const shown = useMemo(() => {
const query = debounced.trim().toLowerCase();
const base = query
? healthChecks.filter((hc) =>
hc.resourceName.toLowerCase().includes(query)
)
: healthChecks;
// Always keep already-selected items visible even if they fall outside the search
if (query && value.length > 0) {
const selectedNotInBase = healthChecks.filter(
(hc) =>
value.includes(hc.targetHealthCheckId) &&
!base.some(
(b) => b.targetHealthCheckId === hc.targetHealthCheckId
)
);
return [...selectedNotInBase, ...base];
}
return out;
}, [resources]);
return base;
}, [healthChecks, debounced, value]);
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)));
const toggle = (id: number) => {
if (value.includes(id)) {
onChange(value.filter((x) => x !== id));
} else {
onChange([...new Set([...value, ...targetIds])]);
onChange([...value, id]);
}
};
const summary =
selectedResourceCount === 0
? t("alertingSelectResources")
: t("alertingResourcesSelected", {
count: selectedResourceCount
});
value.length === 0
? t("alertingSelectHealthChecks")
: t("alertingHealthChecksSelected", { count: value.length });
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -255,38 +241,42 @@ function ResourceTenMultiSelect({
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"
<Command shouldFilter={false}>
<CommandInput
placeholder={t("alertingSearchHealthChecks")}
value={q}
onValueChange={setQ}
/>
<CommandList>
<CommandEmpty>
{t("alertingHealthChecksEmpty")}
</CommandEmpty>
<CommandGroup>
{shown.map((hc) => (
<CommandItem
key={hc.targetHealthCheckId}
value={`${hc.targetHealthCheckId}:${hc.resourceName}`}
onSelect={() =>
toggle(hc.targetHealthCheckId)
}
className="cursor-pointer"
>
<Checkbox
checked={checked}
className="pointer-events-none shrink-0"
checked={value.includes(
hc.targetHealthCheckId
)}
className="mr-2 pointer-events-none shrink-0"
aria-hidden
tabIndex={-1}
/>
<span className="truncate">
{row.name}
{hc.resourceName}
</span>
</button>
);
})
)}
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
@@ -909,11 +899,13 @@ export function AlertRuleSourceFields({
) : (
<FormField
control={control}
name="targetIds"
name="healthCheckIds"
render={({ field }) => (
<FormItem>
<FormLabel>{t("alertingPickResources")}</FormLabel>
<ResourceTenMultiSelect
<FormLabel>
{t("alertingPickHealthChecks")}
</FormLabel>
<HealthCheckMultiSelect
orgId={orgId}
value={field.value}
onChange={field.onChange}

View File

@@ -29,11 +29,14 @@ import { toast } from "@app/hooks/useToast";
import {
buildFormSchema,
defaultFormValues,
formValuesToRule,
formValuesToApiPayload,
type AlertRuleFormAction,
type AlertRuleFormValues
} from "@app/lib/alertRuleForm";
import { upsertRule } from "@app/lib/alertRulesLocalStorage";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import type { CreateAlertRuleResponse } from "@server/private/routers/alertRule";
import type { AxiosResponse } from "axios";
import { cn } from "@app/lib/cn";
import {
Background,
@@ -77,10 +80,10 @@ function summarizeSource(v: AlertRuleFormValues, t: AlertRuleT) {
}
return t("alertingSummarySites", { count: v.siteIds.length });
}
if (v.targetIds.length === 0) {
if (v.healthCheckIds.length === 0) {
return t("alertingNodeNotConfigured");
}
return t("alertingSummaryHealthChecks", { count: v.targetIds.length });
return t("alertingSummaryHealthChecks", { count: v.healthCheckIds.length });
}
function summarizeTrigger(v: AlertRuleFormValues, t: AlertRuleT) {
@@ -175,7 +178,7 @@ function stepConfigured(
if (step === "source") {
return v.sourceType === "site"
? v.siteIds.length > 0
: v.targetIds.length > 0;
: v.healthCheckIds.length > 0;
}
return Boolean(v.trigger);
}
@@ -300,8 +303,7 @@ function buildNodeData(
type AlertRuleGraphEditorProps = {
orgId: string;
ruleId: string;
createdAt: string;
alertRuleId?: number;
initialValues: AlertRuleFormValues;
isNew: boolean;
};
@@ -310,13 +312,14 @@ const FORM_ID = "alert-rule-graph-form";
export default function AlertRuleGraphEditor({
orgId,
ruleId,
createdAt,
alertRuleId,
initialValues,
isNew
}: AlertRuleGraphEditorProps) {
const t = useTranslations();
const router = useRouter();
const api = createApiClient(useEnvContext());
const [isSaving, setIsSaving] = useState(false);
const schema = useMemo(() => buildFormSchema(t), [t]);
const form = useForm<AlertRuleFormValues>({
resolver: zodResolver(schema),
@@ -335,8 +338,8 @@ export default function AlertRuleGraphEditor({
useWatch({ control: form.control, name: "sourceType" }) ?? "site";
const wSiteIds =
useWatch({ control: form.control, name: "siteIds" }) ?? [];
const wTargetIds =
useWatch({ control: form.control, name: "targetIds" }) ?? [];
const wHealthCheckIds =
useWatch({ control: form.control, name: "healthCheckIds" }) ?? [];
const wTrigger =
useWatch({ control: form.control, name: "trigger" }) ??
"site_offline";
@@ -349,7 +352,7 @@ export default function AlertRuleGraphEditor({
enabled: wEnabled,
sourceType: wSourceType,
siteIds: wSiteIds,
targetIds: wTargetIds,
healthCheckIds: wHealthCheckIds,
trigger: wTrigger,
actions: wActions
}),
@@ -358,7 +361,7 @@ export default function AlertRuleGraphEditor({
wEnabled,
wSourceType,
wSiteIds,
wTargetIds,
wHealthCheckIds,
wTrigger,
wActions
]
@@ -472,7 +475,7 @@ export default function AlertRuleGraphEditor({
if (!m) {
return;
}
const i = Number(m[1], 10);
const i = parseInt(m[1], 10);
if (i >= wActions.length) {
setSelectedStep(
wActions.length > 0
@@ -486,12 +489,33 @@ export default function AlertRuleGraphEditor({
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 onSubmit = form.handleSubmit(async (values) => {
setIsSaving(true);
try {
const payload = formValuesToApiPayload(values);
if (isNew) {
const res = await api.put<
AxiosResponse<CreateAlertRuleResponse>
>(`/org/${orgId}/alert-rule`, payload);
toast({ title: t("alertingRuleSaved") });
router.replace(
`/${orgId}/settings/alerting/${res.data.data.alertRuleId}`
);
} else {
await api.post(
`/org/${orgId}/alert-rule/${alertRuleId}`,
payload
);
toast({ title: t("alertingRuleSaved") });
}
} catch (e) {
toast({
title: t("error"),
description: formatAxiosError(e),
variant: "destructive"
});
} finally {
setIsSaving(false);
}
});
@@ -565,8 +589,8 @@ export default function AlertRuleGraphEditor({
</FormItem>
)}
/>
<Button type="submit">
{t("save")}
<Button type="submit" disabled={isSaving}>
{isSaving ? t("saving") : t("save")}
</Button>
</div>
</div>