Compare commits

...

6 Commits

Author SHA1 Message Date
Fred KISSIE 21032bc22b test alert email works 2026-08-11 22:25:26 +02:00
Fred KISSIE 899c47e9a3 🚧 write process test alert function 2026-08-11 20:52:13 +02:00
Fred KISSIE 403b8a12e4 🚧 wip 2026-08-07 20:57:54 +02:00
Fred KISSIE 3f305e4d5c 🚧 process test alert 2026-08-07 20:52:25 +02:00
Fred KISSIE 6689a8d93e 🚧 wip: test alert rule 2026-08-07 19:05:28 +02:00
Owen e91c344e64 Update link to be correct 2026-08-07 10:21:15 -04:00
12 changed files with 528 additions and 45 deletions
+6
View File
@@ -1695,6 +1695,8 @@
"alertingRuleSaved": "Alert rule saved", "alertingRuleSaved": "Alert rule saved",
"alertingRuleSavedCreatedDescription": "Your new alert rule was created. You can keep editing it on this page.", "alertingRuleSavedCreatedDescription": "Your new alert rule was created. You can keep editing it on this page.",
"alertingRuleSavedUpdatedDescription": "Your changes to this alert rule were saved.", "alertingRuleSavedUpdatedDescription": "Your changes to this alert rule were saved.",
"alertingTestAlertSent": "Test alert sent",
"alertingTestAlertSentDescription": "A test alert was sent to the actions configured on this rule.",
"alertingEditRule": "Edit Alert Rule", "alertingEditRule": "Edit Alert Rule",
"alertingCreateRule": "Create Alert Rule", "alertingCreateRule": "Create Alert Rule",
"alertingRuleCredenzaDescription": "Choose what to watch, when to fire, and how to notify", "alertingRuleCredenzaDescription": "Choose what to watch, when to fire, and how to notify",
@@ -1804,6 +1806,10 @@
"alertingRulesBannerDescription": "Each rule ties together what to watch (a site, health check, or resource), when to fire (for example offline or unhealthy), and how to notify your team via email, webhooks, or integrations. Use this list to create, enable, and manage those rules.", "alertingRulesBannerDescription": "Each rule ties together what to watch (a site, health check, or resource), when to fire (for example offline or unhealthy), and how to notify your team via email, webhooks, or integrations. Use this list to create, enable, and manage those rules.",
"alertingHealthChecksBannerTitle": "Monitor Health & Resources", "alertingHealthChecksBannerTitle": "Monitor Health & Resources",
"alertingHealthChecksBannerDescription": "Health checks are HTTP or TCP monitors you define once. You can then use them as sources in alert rules so you get notified when a target becomes healthy or unhealthy. Health checks on resources also appear here.", "alertingHealthChecksBannerDescription": "Health checks are HTTP or TCP monitors you define once. You can then use them as sources in alert rules so you get notified when a target becomes healthy or unhealthy. Health checks on resources also appear here.",
"alertingTestRule": "Test Alert Rule",
"alertingNoActionsTitle": "No actions configured",
"alertingNoActionsSaveDescription": "Add at least one action so this rule can notify someone when it fires.",
"alertingNoActionsTestDescription": "Add at least one action before you can test this rule.",
"standaloneHcTableTitle": "Health Checks", "standaloneHcTableTitle": "Health Checks",
"standaloneHcSearchPlaceholder": "Search health checks…", "standaloneHcSearchPlaceholder": "Search health checks…",
"standaloneHcAddButton": "Create Health Check", "standaloneHcAddButton": "Create Health Check",
+1
View File
@@ -151,6 +151,7 @@ export enum ActionsEnum {
createAlertRule = "createAlertRule", createAlertRule = "createAlertRule",
updateAlertRule = "updateAlertRule", updateAlertRule = "updateAlertRule",
deleteAlertRule = "deleteAlertRule", deleteAlertRule = "deleteAlertRule",
testAlertRule = "testAlertRule",
listAlertRules = "listAlertRules", listAlertRules = "listAlertRules",
listOrgLabels = "listOrgLabels", listOrgLabels = "listOrgLabels",
createOrgLabel = "createOrgLabel", createOrgLabel = "createOrgLabel",
+30 -3
View File
@@ -31,9 +31,24 @@ export type AlertNotificationProps = {
orgId: string; orgId: string;
data: Record<string, unknown>; data: Record<string, unknown>;
dashboardLink: string; dashboardLink: string;
isTestAlert?: boolean;
}; };
function getEventMeta(eventType: AlertEventType): { function getEventMeta(
eventType: AlertEventType,
isTestAlert: boolean = false
): {
heading: string;
previewText: string;
summary: string;
statusLabel: string | null;
statusColor: string | null;
} {
const meta = getBaseEventMeta(eventType);
return isTestAlert ? { ...meta, heading: `[TEST] ${meta.heading}` } : meta;
}
function getBaseEventMeta(eventType: AlertEventType): {
heading: string; heading: string;
previewText: string; previewText: string;
summary: string; summary: string;
@@ -180,8 +195,14 @@ function formatDataItems(
} }
export const AlertNotification = (props: AlertNotificationProps) => { export const AlertNotification = (props: AlertNotificationProps) => {
const { eventType, orgId, data, dashboardLink } = props; const {
const meta = getEventMeta(eventType); eventType,
orgId,
data,
dashboardLink,
isTestAlert = false
} = props;
const meta = getEventMeta(eventType, isTestAlert);
const dataItems = formatDataItems(data); const dataItems = formatDataItems(data);
const isToggle = const isToggle =
@@ -242,6 +263,12 @@ export const AlertNotification = (props: AlertNotificationProps) => {
Open your dashboard to view more details and manage Open your dashboard to view more details and manage
your alert rules. your alert rules.
</EmailText> </EmailText>
{isTestAlert && (
<EmailText>
This is a test alert. No action is required,
and no real event has occurred.
</EmailText>
)}
<EmailSection> <EmailSection>
<ButtonLink href={dashboardLink}> <ButtonLink href={dashboardLink}>
@@ -0,0 +1,103 @@
import { db, userOrgRoles, users } from "@server/db";
import logger from "@server/logger";
import type {
EmailAlertAction,
TestAlertContext,
WebhookAlertConfig
} from "@server/routers/alertRule/types";
import { eq, inArray } from "drizzle-orm";
import { sendAlertEmail } from "./sendAlertEmail";
import { decrypt } from "@server/lib/crypto";
import config from "@server/lib/config";
import { sendAlertWebhook } from "./sendAlertWebhook";
export async function processTestAlerts(context: TestAlertContext) {
const emailActions = context.actions.filter(
(action) => action.type === "email"
);
// Process email actions
for (const action of emailActions) {
try {
const recipients = await resolveEmailRecipients(action);
if (recipients.length > 0) {
await sendAlertEmail(recipients, {
...context,
isTest: true
});
}
} catch (err) {
logger.error(`processTestAlerts: failed to send alert email`, err);
}
}
const webhookActions = context.actions.filter(
(action) => action.type === "webhook"
);
const serverSecret = config.getRawConfig().server.secret!;
for (const action of webhookActions) {
try {
let webhookConfig: WebhookAlertConfig = { authType: "none" };
if (action.config) {
try {
const decrypted = decrypt(action.config, serverSecret);
webhookConfig = JSON.parse(decrypted) as WebhookAlertConfig;
} catch (err) {
logger.error(
`processTestAlerts: failed to decrypt webhook`,
err
);
continue;
}
}
await sendAlertWebhook(action.webhookUrl, webhookConfig, context);
} catch (err) {
logger.error(
`processTestAlerts: failed to send alert webhook `,
err
);
}
}
}
/**
* Resolves all email addresses for a given `emailActionId`.
*
* Recipients may be:
* - Direct users (by `userId`)
* - All users in a role (by `roleId`, resolved via `userOrgRoles`)
* - Direct external email addresses
*/
async function resolveEmailRecipients(
action: EmailAlertAction
): Promise<string[]> {
const emailList: string[] = [];
emailList.push(...(action.emails ?? []));
if (action.userIds && action.userIds?.length > 0) {
const userList = await db
.select({ email: users.email })
.from(users)
.where(inArray(users.userId, action.userIds));
emailList.push(
...userList.filter((u) => u.email !== null).map((u) => u.email!)
);
}
if (action.roleIds && action.roleIds?.length > 0) {
const userList = await db
.select({ email: users.email })
.from(userOrgRoles)
.innerJoin(users, eq(userOrgRoles.userId, users.userId))
.where(inArray(userOrgRoles.roleId, action.roleIds.map(Number)));
emailList.push(
...userList.filter((u) => u.email !== null).map((u) => u.email!)
);
}
return [...new Set(emailList)];
}
+34 -15
View File
@@ -15,7 +15,24 @@ import { sendEmail } from "@server/emails";
import AlertNotification from "@server/emails/templates/AlertNotification"; import AlertNotification from "@server/emails/templates/AlertNotification";
import config from "@server/lib/config"; import config from "@server/lib/config";
import logger from "@server/logger"; import logger from "@server/logger";
import { AlertContext } from "@server/routers/alertRule/types"; import {
AlertContext,
type AlertEventType
} from "@server/routers/alertRule/types";
type EmailAlertContext = {
eventType: AlertEventType;
orgId: string;
/** Set for site_online / site_offline events */
siteId?: number;
/** Set for health_check_* events */
healthCheckId?: number;
/** Set for resource_* events */
resourceId?: number;
/** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>;
isTest?: boolean;
};
/** /**
* Sends an alert notification email to every address in `recipients`. * Sends an alert notification email to every address in `recipients`.
@@ -27,7 +44,7 @@ import { AlertContext } from "@server/routers/alertRule/types";
*/ */
export async function sendAlertEmail( export async function sendAlertEmail(
recipients: string[], recipients: string[],
context: AlertContext context: EmailAlertContext
): Promise<void> { ): Promise<void> {
if (recipients.length === 0) { if (recipients.length === 0) {
return; return;
@@ -46,7 +63,8 @@ export async function sendAlertEmail(
eventType: context.eventType, eventType: context.eventType,
orgId: context.orgId, orgId: context.orgId,
data: context.data, data: context.data,
dashboardLink dashboardLink,
isTestAlert: context.isTest
}), }),
{ {
from, from,
@@ -70,34 +88,35 @@ export async function sendAlertEmail(
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function buildSubject(context: AlertContext): string { function buildSubject(context: EmailAlertContext): string {
const prefix = context.isTest ? "[Test Alert]" : "[Alert]";
switch (context.eventType) { switch (context.eventType) {
case "site_online": case "site_online":
return "[Alert] Site Back Online"; return `${prefix} Site Back Online`;
case "site_offline": case "site_offline":
return "[Alert] Site Offline"; return `${prefix} Site Offline`;
case "site_toggle": case "site_toggle":
return "[Alert] Site Status Changed"; return `${prefix} Site Status Changed`;
case "health_check_healthy": case "health_check_healthy":
return "[Alert] Health Check Recovered"; return `${prefix} Health Check Recovered`;
case "health_check_unhealthy": case "health_check_unhealthy":
return "[Alert] Health Check Failing"; return `${prefix} Health Check Failing`;
case "health_check_toggle": case "health_check_toggle":
return "[Alert] Health Check Status Changed"; return `${prefix} Health Check Status Changed`;
case "resource_healthy": case "resource_healthy":
return "[Alert] Resource Healthy"; return `${prefix} Resource Healthy`;
case "resource_unhealthy": case "resource_unhealthy":
return "[Alert] Resource Unhealthy"; return `${prefix} Resource Unhealthy`;
case "resource_degraded": case "resource_degraded":
return "[Alert] Resource Degraded"; return `${prefix} Resource Degraded`;
case "resource_toggle": case "resource_toggle":
return "[Alert] Resource Status Changed"; return `${prefix} Resource Status Changed`;
default: { default: {
// Exhaustiveness fallback should never be reached with a // Exhaustiveness fallback should never be reached with a
// well-typed caller, but keeps runtime behaviour predictable. // well-typed caller, but keeps runtime behaviour predictable.
const _exhaustive: never = context.eventType; const _exhaustive: never = context.eventType;
void _exhaustive; void _exhaustive;
return "[Alert] Event Notification"; return `${prefix} Event Notification`;
} }
} }
} }
+2 -1
View File
@@ -15,4 +15,5 @@ export * from "./createAlertRule";
export * from "./updateAlertRule"; export * from "./updateAlertRule";
export * from "./deleteAlertRule"; export * from "./deleteAlertRule";
export * from "./listAlertRules"; export * from "./listAlertRules";
export * from "./getAlertRule"; export * from "./getAlertRule";
export * from "./testAlertRule";
@@ -0,0 +1,212 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025-2026 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import {
alertRules,
alertSites,
alertHealthChecks,
alertResources
} from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
import { and, asc, desc, eq, inArray, like, or, sql } from "drizzle-orm";
import {
ListAlertRulesResponse,
type AlertAction,
type EmailAlertAction
} from "@server/routers/alertRule/types";
import { processTestAlerts } from "@server/private/lib/alerts/processTestAlerts";
import { getRandomItemInArray } from "@app/lib/getRandomItemInArray";
const paramsSchema = z.strictObject({
orgId: z.string().nonempty()
});
export const SITE_EVENT_TYPES = [
"site_online",
"site_offline",
"site_toggle"
] as const;
export const HC_EVENT_TYPES = [
"health_check_healthy",
"health_check_unhealthy",
"health_check_toggle"
] as const;
export const RESOURCE_EVENT_TYPES = [
"resource_healthy",
"resource_unhealthy",
"resource_degraded",
"resource_toggle"
] as const;
const webhookActionSchema = z.strictObject({
webhookUrl: z.url(),
config: z.string().optional(),
enabled: z.boolean().optional().default(true)
});
const bodySchema = z.object({
eventType: z.enum([
...HC_EVENT_TYPES,
...SITE_EVENT_TYPES,
...RESOURCE_EVENT_TYPES
]),
// Email recipients (flat)
userIds: z.array(z.string().nonempty()).optional().default([]),
roleIds: z.array(z.number()).optional().default([]),
emails: z.array(z.email()).optional().default([]),
// Webhook actions
webhookActions: z.array(webhookActionSchema).optional().default([])
});
export async function testAlertRule(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const body = parsedBody.data;
const collectedActions: AlertAction[] = [];
if (
body.emails.length > 0 ||
body.roleIds.length > 0 ||
body.userIds.length > 0
) {
collectedActions.push({
type: "email",
emails: body.emails,
roleIds: body.roleIds,
userIds: body.userIds
});
}
for (const action of body.webhookActions) {
collectedActions.push({
type: "webhook",
...action
});
}
let data: Record<string, any> = {};
switch (body.eventType) {
case "site_toggle":
data = {
status: getRandomItemInArray(["online", "offline"]),
siteName: "Test Site Alert"
};
break;
case "site_offline":
data = {
status: "offline",
siteName: "Test Site Alert"
};
break;
case "site_online":
data = {
status: "online",
siteName: "Test Site Alert"
};
break;
case "resource_toggle":
data = {
status: getRandomItemInArray([
"healthy",
"unhealthy",
"degraded"
]),
siteName: "Test Resource Alert"
};
break;
case "resource_healthy":
data = {
status: "healthy",
siteName: "Test Resource Alert"
};
break;
case "resource_unhealthy":
data = {
status: "unhealthy",
siteName: "Test Resource Alert"
};
break;
case "resource_degraded":
data = {
status: "degraded",
siteName: "Test Resource Alert"
};
break;
case "health_check_toggle":
data = {
status: getRandomItemInArray(["healthy", "unhealthy"]),
healthCheckName: "Test Health Check Alert"
};
break;
case "health_check_healthy":
data = {
status: "healthy",
healthCheckName: "Test Health Check Alert"
};
break;
case "health_check_unhealthy":
data = {
status: "unhealthy",
healthCheckName: "Test Health Check Alert"
};
break;
default:
break;
}
// TODO: process alert rule
await processTestAlerts({
eventType: body.eventType,
orgId,
actions: collectedActions,
data
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
+8
View File
@@ -808,6 +808,14 @@ authenticated.get(
alertRule.listAlertRules alertRule.listAlertRules
); );
authenticated.post(
"/org/:orgId/test-alert-rule",
verifyValidLicense,
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.testAlertRule),
alertRule.testAlertRule
);
authenticated.get( authenticated.get(
"/org/:orgId/alert-rule/:alertRuleId", "/org/:orgId/alert-rule/:alertRuleId",
verifyValidLicense, verifyValidLicense,
+23
View File
@@ -124,3 +124,26 @@ export interface AlertContext {
/** Human-readable context data included in emails and webhook payloads */ /** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>; data: Record<string, unknown>;
} }
export type EmailAlertAction = {
type: "email";
userIds?: string[];
roleIds?: number[];
emails?: string[];
};
export type WebhookAlertAction = {
type: "webhook";
webhookUrl: string;
enabled: boolean;
config?: string | undefined;
};
export type AlertAction = EmailAlertAction | WebhookAlertAction;
export interface TestAlertContext {
eventType: AlertEventType;
actions: AlertAction[];
orgId: string;
/** Human-readable context data included in emails and webhook payloads */
data: Record<string, unknown>;
}
@@ -181,7 +181,7 @@ export default function NetworkingPage() {
<SettingsSectionDescription> <SettingsSectionDescription>
{t("remoteExitNodeNetworkingDescription")} {t("remoteExitNodeNetworkingDescription")}
<a <a
href="https://docs.pangolin.net/placeholder" href="https://docs.pangolin.net/manage/remote-node/backhaul"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="text-primary hover:underline inline-flex items-center gap-1" className="text-primary hover:underline inline-flex items-center gap-1"
@@ -6,7 +6,9 @@ import {
AlertRuleSourceFields, AlertRuleSourceFields,
AlertRuleTriggerFields AlertRuleTriggerFields
} from "@app/components/alert-rule-editor/AlertRuleFields"; } from "@app/components/alert-rule-editor/AlertRuleFields";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
import { SettingsContainer } from "@app/components/Settings"; import { SettingsContainer } from "@app/components/Settings";
import { SwitchInput } from "@app/components/SwitchInput";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { Card, CardContent } from "@app/components/ui/card"; import { Card, CardContent } from "@app/components/ui/card";
import { import {
@@ -19,6 +21,7 @@ import {
FormMessage FormMessage
} from "@app/components/ui/form"; } from "@app/components/ui/form";
import { Input } from "@app/components/ui/input"; import { Input } from "@app/components/ui/input";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { import {
buildFormSchema, buildFormSchema,
@@ -27,19 +30,15 @@ import {
type AlertRuleFormValues type AlertRuleFormValues
} from "@app/lib/alertRuleForm"; } from "@app/lib/alertRuleForm";
import { createApiClient, formatAxiosError } from "@app/lib/api"; import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { zodResolver } from "@hookform/resolvers/zod";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import type { CreateAlertRuleResponse } from "@server/routers/alertRule/types"; import type { CreateAlertRuleResponse } from "@server/routers/alertRule/types";
import type { AxiosResponse } from "axios"; import type { AxiosResponse } from "axios";
import { zodResolver } from "@hookform/resolvers/zod"; import { Cog, Flag, Zap, ZapIcon } from "lucide-react";
import { ChevronLeft, Cog, Flag, Zap } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState, type ReactNode } from "react";
import { useFieldArray, useForm, type Resolver } from "react-hook-form";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert"; import { useRouter } from "next/navigation";
import { SwitchInput } from "@app/components/SwitchInput"; import { useActionState, useMemo, useTransition, type ReactNode } from "react";
import { tierMatrix } from "@server/lib/billing/tierMatrix"; import { useFieldArray, useForm, type Resolver } from "react-hook-form";
import { Badge } from "../ui/badge"; import { Badge } from "../ui/badge";
const FORM_ID = "alert-rule-form"; const FORM_ID = "alert-rule-form";
@@ -115,7 +114,6 @@ export default function AlertRuleGraphEditor({
const t = useTranslations(); const t = useTranslations();
const router = useRouter(); const router = useRouter();
const api = createApiClient(useEnvContext()); const api = createApiClient(useEnvContext());
const [isSaving, setIsSaving] = useState(false);
const schema = useMemo(() => buildFormSchema(t), [t]); const schema = useMemo(() => buildFormSchema(t), [t]);
const form = useForm<AlertRuleFormValues>({ const form = useForm<AlertRuleFormValues>({
resolver: zodResolver(schema) as Resolver<AlertRuleFormValues>, resolver: zodResolver(schema) as Resolver<AlertRuleFormValues>,
@@ -127,8 +125,22 @@ export default function AlertRuleGraphEditor({
name: "actions" name: "actions"
}); });
const onSubmit = form.handleSubmit(async (values) => { const saveAlert = async () => {
setIsSaving(true); const isValid = await form.trigger();
if (!isValid) {
const values = form.getValues();
if (values.actions.length === 0) {
toast({
variant: "warning",
title: t("alertingNoActionsTitle"),
description: t("alertingNoActionsSaveDescription")
});
}
return;
}
const values = form.getValues();
try { try {
const payload = formValuesToApiPayload(values); const payload = formValuesToApiPayload(values);
if (isNew) { if (isNew) {
@@ -158,14 +170,65 @@ export default function AlertRuleGraphEditor({
description: formatAxiosError(e), description: formatAxiosError(e),
variant: "destructive" variant: "destructive"
}); });
} finally {
setIsSaving(false);
} }
}); // const submit = form.handleSubmit(async (values) => {
// });
// await submit();
};
const testAlert = async () => {
const isValid = await form.trigger();
if (!isValid) {
const values = form.getValues();
if (values.actions.length === 0) {
toast({
variant: "warning",
title: t("alertingNoActionsTitle"),
description: t("alertingNoActionsTestDescription")
});
}
return;
}
const values = form.getValues();
try {
const payload = formValuesToApiPayload(values);
if (isNew) {
const res = await api.post<
AxiosResponse<CreateAlertRuleResponse>
>(`/org/${orgId}/test-alert-rule`, payload);
toast({
title: t("alertingTestAlertSent"),
description: t("alertingTestAlertSentDescription")
});
} else {
await api.post(
`/org/${orgId}/alert-rule/${alertRuleId}`,
payload
);
toast({
title: t("alertingTestAlertSent"),
description: t("alertingTestAlertSentDescription")
});
}
} catch (e) {
toast({
title: t("error"),
description: formatAxiosError(e),
variant: "destructive"
});
}
};
const [, formAction, isSaving] = useActionState(saveAlert, null);
const [isTestingAlert, startTransition] = useTransition();
return ( return (
<Form {...form}> <Form {...form}>
<form id={FORM_ID} onSubmit={onSubmit}> <form id={FORM_ID} action={formAction}>
<SettingsContainer> <SettingsContainer>
<PaidFeaturesAlert tiers={tierMatrix.alertingRules} /> <PaidFeaturesAlert tiers={tierMatrix.alertingRules} />
<div className="flex flex-col lg:flex-row gap-6 lg:gap-8 items-start"> <div className="flex flex-col lg:flex-row gap-6 lg:gap-8 items-start">
@@ -263,14 +326,29 @@ export default function AlertRuleGraphEditor({
</FormItem> </FormItem>
)} )}
/> />
<Button <div className="flex flex-col items-center w-full gap-3">
type="submit" <Button
className="w-full" type="submit"
disabled={isSaving} className="w-full"
loading={isSaving} disabled={isSaving}
> loading={isSaving}
{t("save")} >
</Button> {t("save")}
</Button>
<Button
type="button"
variant="outline"
className="w-full gap-1.5"
onClick={() =>
startTransition(testAlert)
}
loading={isTestingAlert}
>
{t("alertingTestRule")}
<ZapIcon className="size-3.5 flex-none" />
</Button>
</div>
</fieldset> </fieldset>
</CardContent> </CardContent>
</Card> </Card>
+5
View File
@@ -0,0 +1,5 @@
export function getRandomItemInArray<T>(array: T[]) {
// Source - https://stackoverflow.com/a/4550514
const randomElement = array[Math.floor(Math.random() * array.length)];
return randomElement;
}