Skip to content

Open-source status page, incident response and uptime monitoring

feat: notification-form (#915)

Maximilian Kaskef0ed15611063
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/[id]/edit/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/[id]/edit/page.tsx
index e37076064..d3f379e18 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/[id]/edit/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/[id]/edit/page.tsx
@@ -1,4 +1,4 @@
-import { NotificationForm } from "@/components/forms/notification-form";
+import { NotificationForm } from "@/components/forms/notification/form";
import { api } from "@/trpc/server";
export default async function EditPage({
@@ -7,6 +7,7 @@ export default async function EditPage({
params: { workspaceSlug: string; id: string };
}) {
const workspace = await api.workspace.getWorkspace.query();
+ const monitors = await api.monitor.getMonitorsByWorkspace.query();
const notification = await api.notification.getNotificationById.query({
id: Number(params.id),
@@ -14,7 +15,11 @@ export default async function EditPage({
return (
<NotificationForm
- defaultValues={notification}
+ defaultValues={{
+ ...notification,
+ monitors: notification.monitor.map(({ monitor }) => monitor.id),
+ }}
+ monitors={monitors}
workspacePlan={workspace.plan}
provider={notification.provider}
/>
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/[channel]/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/[channel]/page.tsx
index c8461ed0a..0a3f4e80f 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/[channel]/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/[channel]/page.tsx
@@ -1,5 +1,5 @@
import { ProFeatureAlert } from "@/components/billing/pro-feature-alert";
-import { NotificationForm } from "@/components/forms/notification-form";
+import { NotificationForm } from "@/components/forms/notification/form";
import { api } from "@/trpc/server";
import { notificationProviderSchema } from "@openstatus/db/src/schema";
import { getLimit } from "@openstatus/plans";
@@ -17,6 +17,7 @@ export default async function ChannelPage({
if (!validation.success) notFound();
const workspace = await api.workspace.getWorkspace.query();
+ const monitors = await api.monitor.getMonitorsByWorkspace.query();
const provider = validation.data;
@@ -36,6 +37,7 @@ export default async function ChannelPage({
workspacePlan={workspace.plan}
nextUrl="../"
provider={provider}
+ monitors={monitors}
/>
);
}
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/pagerduty/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/pagerduty/page.tsx
index 42b770c51..2e8cd9005 100644
--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/pagerduty/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/notifications/new/pagerduty/page.tsx
@@ -1,5 +1,5 @@
import { ProFeatureAlert } from "@/components/billing/pro-feature-alert";
-import { NotificationForm } from "@/components/forms/notification-form";
+import { NotificationForm } from "@/components/forms/notification/form";
import { api } from "@/trpc/server";
import { PagerDutySchema } from "@openstatus/notification-pagerduty";
import { getLimit } from "@openstatus/plans";
@@ -17,6 +17,7 @@ export default async function PagerDutyPage({
searchParams: { [key: string]: string | string[] | undefined };
}) {
const workspace = await api.workspace.getWorkspace.query();
+ const monitors = await api.monitor.getMonitorsByWorkspace.query();
const params = searchParamsSchema.parse(searchParams);
if (!params.config) {
@@ -39,6 +40,7 @@ export default async function PagerDutyPage({
nextUrl="../"
provider="pagerduty"
callbackData={params.config}
+ monitors={monitors}
/>
</>
);
diff --git a/apps/web/src/app/app/[workspaceSlug]/onboarding/page.tsx b/apps/web/src/app/app/[workspaceSlug]/onboarding/page.tsx
index ff9545054..8526afde6 100644
--- a/apps/web/src/app/app/[workspaceSlug]/onboarding/page.tsx
+++ b/apps/web/src/app/app/[workspaceSlug]/onboarding/page.tsx
@@ -4,12 +4,10 @@ import { redirect } from "next/navigation";
import { Button } from "@openstatus/ui";
import { Header } from "@/components/dashboard/header";
-import { MonitorForm } from "@/components/forms/monitor-form";
import { StatusPageForm } from "@/components/forms/status-page/form";
import { api } from "@/trpc/server";
import { Description } from "./_components/description";
-
-// FIXME: uses legact MonitorForm and StatusPageForm
+import { MonitorForm } from "@/components/forms/monitor/form";
export default async function Onboarding({
params,
@@ -37,7 +35,10 @@ export default async function Onboarding({
/>
<div className="grid h-full w-full gap-6 md:grid-cols-3 md:gap-8">
<div className="md:col-span-2">
- <MonitorForm notifications={allNotifications} />
+ <MonitorForm
+ notifications={allNotifications}
+ defaultSection="request"
+ />
</div>
<div className="hidden h-full md:col-span-1 md:block">
<Description step="monitor" />
diff --git a/apps/web/src/app/app/onboarding/page.tsx b/apps/web/src/app/app/onboarding/page.tsx
new file mode 100644
index 000000000..f3543455e
--- /dev/null
+++ b/apps/web/src/app/app/onboarding/page.tsx
@@ -0,0 +1,15 @@
+import { auth } from "@/lib/auth";
+import { api } from "@/trpc/server";
+import { redirect } from "next/navigation";
+
+export default async function OnboardingPage() {
+ const session = await auth();
+
+ if (!session) redirect("/app/login");
+
+ const workspace = await api.workspace.getWorkspace.query();
+
+ if (!workspace) redirect("/app/login");
+
+ return redirect(`/app/${workspace.slug}/onboarding`);
+}
diff --git a/apps/web/src/app/play/checker/_components/testimonial.tsx b/apps/web/src/app/play/checker/_components/testimonial.tsx
index e4b177379..a2cc974f1 100644
--- a/apps/web/src/app/play/checker/_components/testimonial.tsx
+++ b/apps/web/src/app/play/checker/_components/testimonial.tsx
@@ -1,23 +1,22 @@
-import { Shell } from "@/components/dashboard/shell";
+import Image from "next/image";
export const Testimonial = () => {
return (
<div className="mx-auto max-w-2xl lg:max-w-4xl">
- <figure className="mt-10">
- <blockquote className="text-center font-semibold text-2xl leading-8 sm:text-2xl sm:leading-9">
- <p>“Just don't give up on your users”</p>
+ <figure className="grid gap-4">
+ <blockquote className="text-center font-semibold text-xl leading-8 after:text-muted-foreground before:text-muted-foreground sm:text-2xl sm:leading-9 after:content-['”'] before:content-['“']">
+ Just don't give up on your users
</blockquote>
- <figcaption className="mt-10">
- <div className="mt-4 flex items-center justify-center space-x-3 text-base">
- <div>
- <div className="font-semibold">Glauber Costa</div>
-
- <div className="text-muted-foreground">CEO of Turso</div>
- </div>
- <img
- className="h-10 w-10 rounded-full"
+ <figcaption className="flex items-center justify-center space-x-3 text-base">
+ <div className="text-sm">
+ <div className="font-medium">Glauber Costa</div>
+ <div className="text-muted-foreground">CEO of Turso</div>
+ </div>
+ <div className="relative h-10 w-10 overflow-hidden rounded-full border">
+ <Image
+ fill={true}
src="/assets/checker/glauber.png"
- alt=""
+ alt="Glauber Costa"
/>
</div>
</figcaption>
diff --git a/apps/web/src/components/forms/monitor-form.tsx b/apps/web/src/components/forms/monitor-form.tsx
index dcb24cd54..795b4ef53 100644
--- a/apps/web/src/components/forms/monitor-form.tsx
+++ b/apps/web/src/components/forms/monitor-form.tsx
@@ -1,3 +1,5 @@
+// REMINDER: legacy form - please use /forms/monitor/form.tsx
+
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -17,7 +19,6 @@ import {
monitorMethods,
monitorMethodsSchema,
monitorPeriodicitySchema,
- workspacePlans,
} from "@openstatus/db/src/schema";
import { getLimit } from "@openstatus/plans";
import {
@@ -34,10 +35,6 @@ import {
CommandItem,
CommandList,
Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
DialogTrigger,
Form,
FormControl,
@@ -67,12 +64,9 @@ import { flyRegionsDict } from "@openstatus/utils";
import { LoadingAnimation } from "@/components/loading-animation";
import { FailedPingAlertConfirmation } from "@/components/modals/failed-ping-alert-confirmation";
import type { RegionChecker } from "@/components/ping-response-analysis/utils";
-import useUpdateSearchParams from "@/hooks/use-update-search-params";
import { toastAction } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { api } from "@/trpc/client";
-import type { Writeable } from "@/types/utils";
-import { NotificationForm } from "./notification-form";
const cronJobs = [
{ value: "30s", label: "30 seconds" },
diff --git a/apps/web/src/components/forms/monitor/section-notifications.tsx b/apps/web/src/components/forms/monitor/section-notifications.tsx
index f316079df..7a5c01c3c 100644
--- a/apps/web/src/components/forms/monitor/section-notifications.tsx
+++ b/apps/web/src/components/forms/monitor/section-notifications.tsx
@@ -8,16 +8,8 @@ import type {
Notification,
WorkspacePlan,
} from "@openstatus/db/src/schema";
-import { getLimit } from "@openstatus/plans";
import {
Badge,
- Button,
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
FormControl,
FormDescription,
FormField,
@@ -26,7 +18,6 @@ import {
FormMessage,
} from "@openstatus/ui";
-import { NotificationForm } from "../notification-form";
import { CheckboxLabel } from "../shared/checkbox-label";
interface Props {
diff --git a/apps/web/src/components/forms/notification-form.tsx b/apps/web/src/components/forms/notification-form.tsx
deleted file mode 100644
index 2b583b6d6..000000000
--- a/apps/web/src/components/forms/notification-form.tsx
+++ /dev/null
@@ -1,284 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import { useMemo, useTransition } from "react";
-import { useForm } from "react-hook-form";
-
-import type {
- InsertNotification,
- NotificationProvider,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import { insertNotificationSchema } from "@openstatus/db/src/schema";
-import { sendTestDiscordMessage } from "@openstatus/notification-discord";
-import { sendTestSlackMessage } from "@openstatus/notification-slack";
-import {
- Button,
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { toCapitalize } from "@/lib/utils";
-import { api } from "@/trpc/client";
-
-function getDefaultProviderData(defaultValues?: InsertNotification) {
- if (!defaultValues?.provider) return ""; // FIXME: input can empty - needs to be undefined
- return JSON.parse(defaultValues?.data || "{}")[defaultValues?.provider];
-}
-
-function setProviderData(provider: NotificationProvider, data: string) {
- return { [provider]: data };
-}
-
-function getProviderMetaData(provider: NotificationProvider) {
- switch (provider) {
- case "email":
- return {
- dataType: "email",
- placeholder: "[email protected]",
- setupDocLink: null,
- sendTest: null,
- plans: ["free", "starter", "pro", "team"],
- };
-
- case "slack":
- return {
- dataType: "url",
- placeholder: "https://hooks.slack.com/services/xxx...",
- setupDocLink:
- "https://api.slack.com/messaging/webhooks#getting_started",
- sendTest: sendTestSlackMessage,
- plans: ["free", "starter", "pro", "team"],
- };
-
- case "discord":
- return {
- dataType: "url",
- placeholder: "https://discord.com/api/webhooks/{channelId}/xxx...",
- setupDocLink: "https://support.discord.com/hc/en-us/articles/228383668",
- sendTest: sendTestDiscordMessage,
- plans: ["free", "starter", "pro", "team"],
- };
- case "sms":
- return {
- dataType: "tel",
- placeholder: "+123456789",
- setupDocLink: null,
- sendTest: null,
- plans: ["pro", "team"],
- };
- case "pagerduty":
- return {
- dataType: null,
- placeholder: "",
- setupDocLink:
- "https://docs.openstatus.dev/synthetic/features/notification/pagerduty",
- sendTest: null,
- plans: ["starter", "pro", "team"],
- };
-
- default:
- return {
- dataType: "url",
- placeholder: "xxxx",
- setupDocLink: `https://docs.openstatus.dev/integrations/${provider}`,
- send: null,
- plans: ["free", "starter", "pro", "team"],
- };
- }
-}
-
-interface Props {
- defaultValues?: InsertNotification;
- onSubmit?: () => void;
- workspacePlan: WorkspacePlan;
- nextUrl?: string;
- provider: NotificationProvider;
- callbackData?: string;
-}
-
-export function NotificationForm({
- defaultValues,
- onSubmit: onExternalSubmit,
- workspacePlan,
- nextUrl,
- provider,
- callbackData,
-}: Props) {
- const [isPending, startTransition] = useTransition();
- const [isTestPending, startTestTransition] = useTransition();
- const router = useRouter();
- const form = useForm<InsertNotification>({
- resolver: zodResolver(insertNotificationSchema),
- defaultValues: {
- ...defaultValues,
- provider,
- name: defaultValues?.name || "",
- data: getDefaultProviderData(defaultValues),
- },
- });
- const watchWebhookUrl = form.watch("data");
- const providerMetaData = getProviderMetaData(provider);
-
- async function onSubmit({ provider, data, ...rest }: InsertNotification) {
- startTransition(async () => {
- try {
- if (provider === "pagerduty") {
- if (callbackData) {
- data = callbackData;
- }
- }
- if (data === "") {
- form.setError("data", { message: "This field is required" });
- return;
- }
- if (defaultValues) {
- await api.notification.update.mutate({
- provider,
- data: JSON.stringify(setProviderData(provider, data)),
- ...rest,
- });
- } else {
- await api.notification.create.mutate({
- provider,
- data: JSON.stringify(setProviderData(provider, data)),
- ...rest,
- });
- }
- if (nextUrl) {
- router.push(nextUrl);
- }
- router.refresh();
- toastAction("saved");
- } catch {
- toastAction("error");
- } finally {
- onExternalSubmit?.();
- }
- });
- }
-
- async function sendTestWebhookPing() {
- const webhookUrl = form.getValues("data");
- if (!webhookUrl) return;
- startTestTransition(async () => {
- const isSuccessfull = await providerMetaData.sendTest?.(webhookUrl);
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="grid w-full gap-6"
- id="notification-form" // we use a form id to connect the submit button to the form (as we also have the form nested inside of `MonitorForm`)
- >
- <div className="grid gap-4 sm:grid-cols-3">
- <div className="my-1.5 flex flex-col gap-2">
- <p className="font-semibold text-sm leading-none">Alerts</p>
- <p className="text-muted-foreground text-sm">
- Select the notification channels you want to be informed.
- </p>
- </div>
- <div className="grid gap-6 sm:col-span-2 sm:grid-cols-2">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="sm:col-span-1 sm:self-baseline">
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input placeholder="Dev Team" {...field} />
- </FormControl>
- <FormDescription>
- Define a name for the channel.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- {providerMetaData.dataType && (
- <FormField
- control={form.control}
- name="data"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- {/* make the first letter capital */}
- <div className="flex items-center justify-between">
- <FormLabel>{toCapitalize(provider)}</FormLabel>
- </div>
- <FormControl>
- <Input
- type={providerMetaData.dataType}
- placeholder={providerMetaData.placeholder}
- {...field}
- disabled={
- !providerMetaData.plans?.includes(workspacePlan)
- }
- />
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The data required.
- {providerMetaData.setupDocLink && (
- <a
- href={providerMetaData.setupDocLink}
- target="_blank"
- className="underline hover:no-underline"
- rel="noreferrer"
- >
- How to setup your {toCapitalize(provider)} webhook
- </a>
- )}
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- )}
- </div>
- </div>
- <div className="flex gap-4 sm:justify-end">
- {providerMetaData.sendTest && (
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- size="lg"
- disabled={!watchWebhookUrl || isTestPending}
- onClick={sendTestWebhookPing}
- >
- {!isTestPending ? (
- "Test Webhook"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- )}
- <Button
- form="notification-form"
- className="w-full sm:w-auto"
- size="lg"
- disabled={isPending}
- >
- {!isPending ? "Confirm" : <LoadingAnimation />}
- </Button>
- </div>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/notification/config.ts b/apps/web/src/components/forms/notification/config.ts
index 0c251052b..7f39a3294 100644
--- a/apps/web/src/components/forms/notification/config.ts
+++ b/apps/web/src/components/forms/notification/config.ts
@@ -57,6 +57,17 @@ export function getProviderMetaData(provider: NotificationProvider) {
plans: plans.filter((plan) => allPlans[plan].limits.sms),
};
+ case "pagerduty":
+ return {
+ label: "PagerDuty",
+ dataType: null,
+ placeholder: "",
+ setupDocLink:
+ "https://docs.openstatus.dev/synthetic/features/notification/pagerduty",
+ sendTest: null,
+ plans: plans.filter((plan) => allPlans[plan].limits.pagerduty),
+ };
+
default:
return {
label: "Webhook",
diff --git a/apps/web/src/components/forms/notification/form.tsx b/apps/web/src/components/forms/notification/form.tsx
index fd0dd293b..927b79a5f 100644
--- a/apps/web/src/components/forms/notification/form.tsx
+++ b/apps/web/src/components/forms/notification/form.tsx
@@ -2,64 +2,73 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
-import { useMemo, useTransition } from "react";
+import { useTransition } from "react";
import { useForm } from "react-hook-form";
import type {
InsertNotification,
+ Monitor,
+ NotificationProvider,
WorkspacePlan,
} from "@openstatus/db/src/schema";
import { insertNotificationSchema } from "@openstatus/db/src/schema";
-import { Button, Form } from "@openstatus/ui";
+import { Badge, Form } from "@openstatus/ui";
-import { LoadingAnimation } from "@/components/loading-animation";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/components/dashboard/tabs";
import { toast, toastAction } from "@/lib/toast";
import { api } from "@/trpc/client";
-import { SchemaError } from "@openstatus/error";
import { TRPCClientError } from "@trpc/client";
-import { ZodError, type ZodIssue } from "zod";
import { SaveButton } from "../shared/save-button";
-import {
- getDefaultProviderData,
- getProviderMetaData,
- setProviderData,
-} from "./config";
+import { getDefaultProviderData, setProviderData } from "./config";
import { General } from "./general";
+import { SectionConnect } from "./section-connect";
interface Props {
defaultValues?: InsertNotification;
+ defaultSection?: string;
onSubmit?: () => void;
+ monitors?: Monitor[];
workspacePlan: WorkspacePlan;
nextUrl?: string;
+ provider: NotificationProvider;
+ callbackData?: string;
}
export function NotificationForm({
defaultValues,
+ defaultSection = "connect",
onSubmit: onExternalSubmit,
workspacePlan,
+ monitors,
nextUrl,
+ provider,
+ callbackData,
}: Props) {
const [isPending, startTransition] = useTransition();
- const [isTestPending, startTestTransition] = useTransition();
const router = useRouter();
const form = useForm<InsertNotification>({
resolver: zodResolver(insertNotificationSchema),
defaultValues: {
...defaultValues,
+ provider,
name: defaultValues?.name || "",
data: getDefaultProviderData(defaultValues),
},
});
- const watchProvider = form.watch("provider");
- const watchWebhookUrl = form.watch("data");
- const providerMetaData = useMemo(
- () => getProviderMetaData(watchProvider),
- [watchProvider],
- );
async function onSubmit({ provider, data, ...rest }: InsertNotification) {
startTransition(async () => {
try {
+ if (provider === "pagerduty") {
+ if (callbackData) {
+ data = callbackData;
+ }
+ }
if (data === "") {
form.setError("data", { message: "This field is required" });
return;
@@ -91,19 +100,6 @@ export function NotificationForm({
});
}
- async function sendTestWebhookPing() {
- const webhookUrl = form.getValues("data");
- if (!webhookUrl) return;
- startTestTransition(async () => {
- const isSuccessfull = await providerMetaData.sendTest?.(webhookUrl);
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
return (
<Form {...form}>
<form
@@ -112,23 +108,22 @@ export function NotificationForm({
className="flex flex-col gap-4"
>
<General form={form} plan={workspacePlan} />
+ <Tabs defaultValue={defaultSection} className="w-full">
+ <TabsList>
+ <TabsTrigger value="connect">
+ Connect{" "}
+ {defaultValues?.monitors.length ? (
+ <Badge variant="secondary" className="ml-1">
+ {defaultValues?.monitors.length}
+ </Badge>
+ ) : null}
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="connect">
+ <SectionConnect form={form} monitors={monitors} />
+ </TabsContent>
+ </Tabs>
<div className="flex gap-4 sm:justify-end">
- {providerMetaData.sendTest && (
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- size="lg"
- disabled={!watchWebhookUrl || isTestPending}
- onClick={sendTestWebhookPing}
- >
- {!isTestPending ? (
- "Test Webhook"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- )}
<SaveButton
form="notification-form"
isPending={isPending}
diff --git a/apps/web/src/components/forms/notification/general.tsx b/apps/web/src/components/forms/notification/general.tsx
index 5dd3017df..84fb10a70 100644
--- a/apps/web/src/components/forms/notification/general.tsx
+++ b/apps/web/src/components/forms/notification/general.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo } from "react";
+import { useMemo, useTransition } from "react";
import type { UseFormReturn } from "react-hook-form";
import type {
@@ -8,10 +8,7 @@ import type {
WorkspacePlan,
} from "@openstatus/db/src/schema";
import {
- notificationProvider,
- notificationProviderSchema,
-} from "@openstatus/db/src/schema";
-import {
+ Button,
FormControl,
FormDescription,
FormField,
@@ -19,15 +16,12 @@ import {
FormLabel,
FormMessage,
Input,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
} from "@openstatus/ui";
import { SectionHeader } from "../shared/section-header";
import { getProviderMetaData } from "./config";
+import { toastAction } from "@/lib/toast";
+import { LoadingAnimation } from "@/components/loading-animation";
interface Props {
form: UseFormReturn<InsertNotification>;
@@ -35,61 +29,34 @@ interface Props {
}
export function General({ form, plan }: Props) {
+ const [isTestPending, startTestTransition] = useTransition();
const watchProvider = form.watch("provider");
+ const watchWebhookUrl = form.watch("data");
const providerMetaData = useMemo(
() => getProviderMetaData(watchProvider),
- [watchProvider],
+ [watchProvider]
);
+ async function sendTestWebhookPing() {
+ const webhookUrl = form.getValues("data");
+ if (!webhookUrl) return;
+ startTestTransition(async () => {
+ const isSuccessfull = await providerMetaData.sendTest?.(webhookUrl);
+ if (isSuccessfull) {
+ toastAction("test-success");
+ } else {
+ toastAction("test-error");
+ }
+ });
+ }
+
return (
<div className="grid gap-4 sm:grid-cols-3 sm:gap-6">
<SectionHeader
title="Alert"
- description="Select the notification channels you want to be informed."
+ description={`Update your ${providerMetaData.label} settings`}
/>
<div className="grid gap-4 sm:col-span-2 sm:grid-cols-2">
- <FormField
- control={form.control}
- name="provider"
- render={({ field }) => (
- <FormItem className="sm:col-span-1 sm:self-baseline">
- <FormLabel>Provider</FormLabel>
- <Select
- onValueChange={(value) =>
- field.onChange(notificationProviderSchema.parse(value))
- }
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger className="capitalize">
- <SelectValue placeholder="Select Provider" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {notificationProvider.map((provider) => {
- const providerData = getProviderMetaData(provider);
- const enabled = providerData.plans?.includes(plan);
-
- return (
- <SelectItem
- key={provider}
- value={provider}
- className="capitalize"
- disabled={!enabled}
- >
- {providerData.label}
- </SelectItem>
- );
- })}
- </SelectContent>
- </Select>
- <FormDescription>
- What channel/provider to send a notification.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
<FormField
control={form.control}
name="name"
@@ -104,7 +71,7 @@ export function General({ form, plan }: Props) {
</FormItem>
)}
/>
- {watchProvider && (
+ {providerMetaData.dataType && (
<FormField
control={form.control}
name="data"
@@ -137,6 +104,23 @@ export function General({ form, plan }: Props) {
)}
/>
)}
+ <div className="col-span-full text-right">
+ {providerMetaData.sendTest && (
+ <Button
+ type="button"
+ variant="secondary"
+ className="w-full sm:w-auto"
+ disabled={!watchWebhookUrl || isTestPending}
+ onClick={sendTestWebhookPing}
+ >
+ {!isTestPending ? (
+ "Test Webhook"
+ ) : (
+ <LoadingAnimation variant="inverse" />
+ )}
+ </Button>
+ )}
+ </div>
</div>
</div>
);
diff --git a/apps/web/src/components/forms/notification/section-connect.tsx b/apps/web/src/components/forms/notification/section-connect.tsx
new file mode 100644
index 000000000..97bc40c0f
--- /dev/null
+++ b/apps/web/src/components/forms/notification/section-connect.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import * as React from "react";
+import type { UseFormReturn } from "react-hook-form";
+
+import type { InsertNotification, Monitor } from "@openstatus/db/src/schema";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@openstatus/ui";
+
+import { CheckboxLabel } from "../shared/checkbox-label";
+
+interface Props {
+ form: UseFormReturn<InsertNotification>;
+ monitors?: Monitor[];
+}
+
+export function SectionConnect({ form, monitors }: Props) {
+ return (
+ <div className="grid w-full gap-4">
+ <div className="flex flex-col gap-3">
+ <FormField
+ control={form.control}
+ name="monitors"
+ render={() => (
+ <FormItem>
+ <div className="mb-4">
+ <FormLabel>Monitors</FormLabel>
+ <FormDescription>
+ Attach the notification to specific monitors.
+ </FormDescription>
+ </div>
+ <div className="grid grid-cols-1 grid-rows-1 gap-6 md:grid-cols-3 sm:grid-cols-2">
+ {monitors?.map((item) => (
+ <FormField
+ key={item.id}
+ control={form.control}
+ name="monitors"
+ render={({ field }) => {
+ return (
+ <FormItem key={item.id} className="h-full w-full">
+ <FormControl className="w-full">
+ <CheckboxLabel
+ id={String(item.id)}
+ name="monitor"
+ checked={field.value?.includes(item.id)}
+ onCheckedChange={(checked) => {
+ return checked
+ ? field.onChange([
+ ...(field.value || []),
+ item.id,
+ ])
+ : field.onChange(
+ field.value?.filter(
+ (value) => value !== item.id
+ )
+ );
+ }}
+ className="flex-col items-start truncate"
+ >
+ <span>{item.name}</span>
+ <span className="font-normal text-muted-foreground text-sm">
+ {item.url}
+ </span>
+ </CheckboxLabel>
+ </FormControl>
+ </FormItem>
+ );
+ }}
+ />
+ ))}
+ </div>
+ {!monitors || monitors.length === 0 ? (
+ <FormDescription>Missing monitors.</FormDescription>
+ ) : null}
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/monitor-charts/chart.tsx b/apps/web/src/components/monitor-charts/chart.tsx
index c197b71fd..dcb6349a7 100644
--- a/apps/web/src/components/monitor-charts/chart.tsx
+++ b/apps/web/src/components/monitor-charts/chart.tsx
@@ -77,7 +77,10 @@ const customTooltip = ({
className={cn("flex flex-1 gap-2", !isActive && "opacity-60")}
>
<div
- className={`bg- flex w-1 flex-col${category.color}-500 rounded`}
+ className={cn(
+ "flex w-1 flex-col rounded",
+ `bg-${category.color}-500`
+ )}
/>
<div className="flex w-full justify-between gap-2">
<p className="shrink-0 text-tremor-content dark:text-dark-tremor-content">
diff --git a/apps/web/src/components/monitor-charts/simple-chart.tsx b/apps/web/src/components/monitor-charts/simple-chart.tsx
index 7bb4444db..679a4023c 100644
--- a/apps/web/src/components/monitor-charts/simple-chart.tsx
+++ b/apps/web/src/components/monitor-charts/simple-chart.tsx
@@ -4,6 +4,7 @@ import type { CustomTooltipProps } from "@tremor/react";
import { LineChart } from "@tremor/react";
import { dataFormatter } from "./utils";
+import { cn } from "@/lib/utils";
export interface SimpleChartProps {
data: { timestamp: string; [key: string]: string }[];
@@ -48,7 +49,10 @@ const customTooltip = ({ payload, active, label }: CustomTooltipProps) => {
// biome-ignore lint/suspicious/noArrayIndexKey: <explanation>
<div key={idx} className="flex flex-1 gap-2">
<div
- className={`bg- flex w-1 flex-col${category.color}-500 rounded`}
+ className={cn(
+ "flex w-1 flex-col rounded",
+ `bg-${category.color}-500`
+ )}
/>
<div className="flex flex-col gap-1">
<p className="text-tremor-content dark:text-dark-tremor-content">
diff --git a/apps/web/src/lib/auth/index.ts b/apps/web/src/lib/auth/index.ts
index 3dba7b950..dce1d2ae9 100644
--- a/apps/web/src/lib/auth/index.ts
+++ b/apps/web/src/lib/auth/index.ts
@@ -100,7 +100,7 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
},
pages: {
signIn: "/app/login",
- // newUser: "/app/onboarding", // TODO: rethink this as we still have the `slug` to use
+ newUser: "/app/onboarding",
},
// basePath: "/api/auth", // default is `/api/auth`
// secret: process.env.AUTH_SECRET, // default is `AUTH_SECRET`
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index 2328823cf..0559aeed2 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -39,6 +39,7 @@ const publicAppPaths = [
"/app/sign-up",
"/app/login",
"/app/invite",
+ "/app/onboarding",
];
// remove auth middleware if needed
diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.ts
index f34e5873f..614140d43 100644
--- a/packages/api/src/router/notification.ts
+++ b/packages/api/src/router/notification.ts
@@ -1,11 +1,13 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
-import { and, eq } from "@openstatus/db";
+import { and, eq, inArray } from "@openstatus/db";
import {
NotificationDataSchema,
insertNotificationSchema,
+ monitor,
notification,
+ notificationsToMonitors,
selectMonitorSchema,
selectNotificationSchema,
} from "@openstatus/db/src/schema";
@@ -20,7 +22,7 @@ export const notificationRouter = createTRPCRouter({
create: protectedProcedure
.input(insertNotificationSchema)
.mutation(async (opts) => {
- const { ...props } = opts.input;
+ const { monitors, ...props } = opts.input;
const notificationLimit = getLimit(
opts.ctx.workspace.plan,
@@ -55,6 +57,15 @@ export const notificationRouter = createTRPCRouter({
.returning()
.get();
+ const values = monitors.map((monitorId) => ({
+ notificationId: _notification.id,
+ monitorId,
+ }));
+
+ if (values.length) {
+ await opts.ctx.db.insert(notificationsToMonitors).values(values);
+ }
+
if (env.JITSU_HOST !== undefined && env.JITSU_WRITE_KEY !== undefined) {
await trackNewNotification(opts.ctx.user, {
provider: _notification.provider,
@@ -69,7 +80,7 @@ export const notificationRouter = createTRPCRouter({
.mutation(async (opts) => {
if (!opts.input.id) return;
- const { ...props } = opts.input;
+ const { monitors, ...props } = opts.input;
const _data = NotificationDataSchema.safeParse(JSON.parse(props.data));
@@ -80,7 +91,7 @@ export const notificationRouter = createTRPCRouter({
});
}
- return await opts.ctx.db
+ const currentNotification = await opts.ctx.db
.update(notification)
.set({ ...props, updatedAt: new Date() })
.where(
@@ -91,6 +102,64 @@ export const notificationRouter = createTRPCRouter({
)
.returning()
.get();
+
+ // TODO: relation
+
+ if (monitors.length) {
+ const allMonitors = await opts.ctx.db.query.monitor.findMany({
+ where: and(
+ eq(monitor.workspaceId, opts.ctx.workspace.id),
+ inArray(monitor.id, monitors),
+ ),
+ });
+
+ if (allMonitors.length !== monitors.length) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You don't have access to all the monitors.",
+ });
+ }
+ }
+
+ const currentMonitorsToNotifications = await opts.ctx.db
+ .select()
+ .from(notificationsToMonitors)
+ .where(
+ eq(notificationsToMonitors.notificationId, currentNotification.id),
+ )
+ .all();
+
+ const removedMonitors = currentMonitorsToNotifications
+ .map(({ monitorId }) => monitorId)
+ .filter((x) => !monitors?.includes(x));
+
+ if (removedMonitors.length) {
+ await opts.ctx.db
+ .delete(notificationsToMonitors)
+ .where(
+ and(
+ inArray(notificationsToMonitors.monitorId, removedMonitors),
+ eq(
+ notificationsToMonitors.notificationId,
+ currentNotification.id,
+ ),
+ ),
+ );
+ }
+
+ const values = monitors.map((monitorId) => ({
+ notificationId: currentNotification.id,
+ monitorId,
+ }));
+
+ if (values.length) {
+ await opts.ctx.db
+ .insert(notificationsToMonitors)
+ .values(values)
+ .onConflictDoNothing();
+ }
+
+ return currentNotification;
}),
deleteNotification: protectedProcedure
@@ -110,19 +179,25 @@ export const notificationRouter = createTRPCRouter({
getNotificationById: protectedProcedure
.input(z.object({ id: z.number() }))
.query(async (opts) => {
- const _notification = await opts.ctx.db
- .select()
- .from(notification)
- .where(
- and(
- eq(notification.id, opts.input.id),
- eq(notification.id, opts.input.id),
- eq(notification.workspaceId, opts.ctx.workspace.id),
- ),
- )
- .get();
-
- return selectNotificationSchema.parse(_notification);
+ const _notification = await opts.ctx.db.query.notification.findFirst({
+ where: and(
+ eq(notification.id, opts.input.id),
+ eq(notification.id, opts.input.id),
+ eq(notification.workspaceId, opts.ctx.workspace.id),
+ ),
+ // FIXME: plural
+ with: { monitor: { with: { monitor: true } } },
+ });
+
+ const schema = selectNotificationSchema.extend({
+ monitor: z.array(
+ z.object({
+ monitor: selectMonitorSchema,
+ }),
+ ),
+ });
+
+ return schema.parse(_notification);
}),
getNotificationsByWorkspace: protectedProcedure.query(async (opts) => {
diff --git a/packages/db/src/schema/notifications/validation.ts b/packages/db/src/schema/notifications/validation.ts
index 0c9d67916..21444b57a 100644
--- a/packages/db/src/schema/notifications/validation.ts
+++ b/packages/db/src/schema/notifications/validation.ts
@@ -13,14 +13,15 @@ export const selectNotificationSchema = createSelectSchema(notification).extend(
return String(val);
}, z.string())
.default("{}"),
- }
+ },
);
// we need to extend, otherwise data can be `null` or `undefined` - default is not
export const insertNotificationSchema = createInsertSchema(notification).extend(
{
data: z.string().default("{}"),
- }
+ monitors: z.array(z.number()).optional().default([]),
+ },
);
export type InsertNotification = z.infer<typeof insertNotificationSchema>;
@@ -28,7 +29,7 @@ export type Notification = z.infer<typeof selectNotificationSchema>;
export type NotificationProvider = z.infer<typeof notificationProviderSchema>;
const phoneRegex = new RegExp(
- /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/
+ /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/,
);
export const phoneSchema = z.string().regex(phoneRegex, "Invalid Number!");