Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
🚨 Alerting (#326)
Thibault Le Ouay9ec013968263
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0d7849aca..00667ac98 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -17,9 +17,10 @@"@openstatus/db": "workspace:*","@openstatus/emails": "workspace:*","@openstatus/plans": "workspace:*",+ "@openstatus/notification-emails": "workspace:*","@openstatus/tinybird": "workspace:*",- "@openstatus/upstash": "workspace:*","@openstatus/ui": "workspace:*",+ "@openstatus/upstash": "workspace:*","@openstatus/vercel": "workspace:*","@sentry/integrations": "7.65.0","@sentry/nextjs": "7.65.0",@@ -58,7 +59,7 @@"rehype-react": "7.2.0","remark-parse": "10.0.2","remark-rehype": "10.1.0",- "resend": "0.15.3",+ "resend": "1.1.0","shiki": "0.14.3","stripe": "12.17.0","superjson": "1.13.1",diff --git a/apps/web/src/app/api/checker/cron/_cron.ts b/apps/web/src/app/api/checker/cron/_cron.tsindex db4f313ef..5148f12d3 100644--- a/apps/web/src/app/api/checker/cron/_cron.ts+++ b/apps/web/src/app/api/checker/cron/_cron.ts@@ -57,6 +57,7 @@ export const cron = async ({headers: row.headers,body: row.body,cronTimestamp: timestamp,+ status: row.status,pageIds: allPages.map((p) => String(p.pageId)),};@@ -79,6 +80,7 @@ export const cron = async ({body: row.body,headers: row.headers,pageIds: allPages.map((p) => String(p.pageId)),+ status: row.status,};const result = c.publishJSON({@@ -100,6 +102,7 @@ export const cron = async ({cronTimestamp: timestamp,method: "GET",pageIds: ["openstatus"],+ status: "active",};// TODO: fetch + try - catch + retry oncediff --git a/apps/web/src/app/api/checker/regions/_checker.ts b/apps/web/src/app/api/checker/regions/_checker.tsindex f24d933c7..e512955c4 100644--- a/apps/web/src/app/api/checker/regions/_checker.ts+++ b/apps/web/src/app/api/checker/regions/_checker.ts@@ -2,6 +2,8 @@ import { Receiver } from "@upstash/qstash/cloudflare";import { nanoid } from "nanoid";import type { z } from "zod";+import { db, eq, schema } from "@openstatus/db";+import { selectNotificationSchema } from "@openstatus/db/src/schema";import {publishPingResponse,tbIngestPingResponse,@@ -11,6 +13,7 @@ import {import { env } from "@/env";import type { Payload } from "../schema";import { payloadSchema } from "../schema";+import { providerToFunction } from "../utils";export const monitorSchema = tbIngestPingResponse.pick({url: true,@@ -85,6 +88,14 @@ export const checker = async (request: Request, region: string) => {const endTime = Date.now();const latency = endTime - startTime;await monitor(res, result.data, region, latency);+ if (res.ok) {+ if (result.data?.status === "error") {+ await updateMonitorStatus({+ monitorId: result.data.monitorId,+ status: "active",+ });+ }+ }} catch (e) {console.error(e);// if on the third retry we still get an error, we should report it@@ -95,6 +106,14 @@ export const checker = async (request: Request, region: string) => {region,-1,);+ if (result.data?.status !== "error") {+ await triggerAlerting({ monitorId: result.data.monitorId });+ await updateMonitorStatus({+ monitorId: result.data.monitorId,+ status: "error",+ });+ }+ // Here we do the alerting}}}};@@ -121,3 +140,39 @@ export const ping = async (return res;};++const triggerAlerting = async ({ monitorId }: { monitorId: string }) => {+ const notifications = await db+ .select()+ .from(schema.notificationsToMonitors)+ .innerJoin(+ schema.notification,+ eq(schema.notification.id, schema.notificationsToMonitors.notificationId),+ )+ .innerJoin(+ schema.monitor,+ eq(schema.monitor.id, schema.notificationsToMonitors.monitorId),+ )+ .where(eq(schema.monitor.id, Number(monitorId)))+ .all();+ for (const notif of notifications) {+ await providerToFunction[notif.notification.provider]({+ monitor: notif.monitor,+ notification: selectNotificationSchema.parse(notif.notification),+ });+ }+};++const updateMonitorStatus = async ({+ monitorId,+ status,+}: {+ monitorId: string;+ status: z.infer<typeof schema.statusSchema>;+}) => {+ await db+ .update(schema.monitor)+ .set({ status })+ .where(eq(schema.monitor.id, Number(monitorId)))+ .run();+};diff --git a/apps/web/src/app/api/checker/schema.ts b/apps/web/src/app/api/checker/schema.tsindex b5dad10bf..d5875ca61 100644--- a/apps/web/src/app/api/checker/schema.ts+++ b/apps/web/src/app/api/checker/schema.ts@@ -1,6 +1,6 @@import { z } from "zod";-import { METHODS } from "@openstatus/db/src/schema";+import { METHODS, status } from "@openstatus/db/src/schema";export const payloadSchema = z.object({workspaceId: z.string(),@@ -11,6 +11,7 @@ export const payloadSchema = z.object({url: z.string(),cronTimestamp: z.number(),pageIds: z.array(z.string()),+ status: z.enum(status),});export type Payload = z.infer<typeof payloadSchema>;diff --git a/apps/web/src/app/api/checker/utils.ts b/apps/web/src/app/api/checker/utils.tsnew file mode 100644index 000000000..4b073c146--- /dev/null+++ b/apps/web/src/app/api/checker/utils.ts@@ -0,0 +1,40 @@+import type { z } from "zod";++import type {+ basicMonitorSchema,+ providerName,+ selectNotificationSchema,+} from "@openstatus/db/src/schema";+import { send as sendEmail } from "@openstatus/notification-emails";++type ProviderName = (typeof providerName)[number];++type sendNotificationType = ({+ monitor,+ notification,+}: {+ monitor: z.infer<typeof basicMonitorSchema>;+ notification: z.infer<typeof selectNotificationSchema>;+}) => Promise<void>;++export const providerToFunction = {+ email: sendEmail,+ slack: async ({+ monitor,+ notification,+ }: {+ monitor: any;+ notification: any;+ }) => {+ /* TODO: implement */+ },+ discord: async ({+ monitor,+ notification,+ }: {+ monitor: any;+ notification: any;+ }) => {+ /* TODO: implement */+ },+} satisfies Record<ProviderName, sendNotificationType>;diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsxindex 43bed916b..f6284fc73 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/edit/page.tsx@@ -1,8 +1,6 @@import { notFound } from "next/navigation";import * as z from "zod";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@openstatus/ui";-import { Header } from "@/components/dashboard/header";import { MonitorForm } from "@/components/forms/montitor-form";import { api } from "@/trpc/server";@@ -28,12 +26,24 @@ export default async function EditPage({}const { id } = search.data;+ const { workspaceSlug } = params;const monitor = id && (await api.monitor.getMonitorByID.query({ id }));const workspace = await api.workspace.getWorkspace.query({- slug: params.workspaceSlug,+ slug: workspaceSlug,});+ const monitorNotifications = id+ ? await api.monitor.getAllNotificationsForMonitor.query({+ id,+ })+ : [];++ const notifications =+ await api.notification.getNotificationsByWorkspace.query({+ workspaceSlug,+ });+return (<div className="grid gap-6 md:grid-cols-2 md:gap-8"><Header@@ -42,9 +52,16 @@ export default async function EditPage({/><div className="col-span-full"><MonitorForm- workspaceSlug={params.workspaceSlug}- defaultValues={monitor || undefined}+ defaultValues={+ monitor+ ? {+ ...monitor,+ notifications: monitorNotifications?.map(({ id }) => id),+ }+ : undefined+ }plan={workspace?.plan}+ {...{ workspaceSlug, notifications }}/></div></div>diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/_components/empty-state.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/_components/empty-state.tsxnew file mode 100644index 000000000..a228a1ac5--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/_components/empty-state.tsx@@ -0,0 +1,20 @@+import Link from "next/link";++import { Button } from "@openstatus/ui";++import { EmptyState as DefaultEmptyState } from "@/components/dashboard/empty-state";++export function EmptyState() {+ return (+ <DefaultEmptyState+ icon="bell"+ title="No notifications"+ description="Create your first notification channel"+ action={+ <Button asChild>+ <Link href="./notifications/edit">Create</Link>+ </Button>+ }+ />+ );+}diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/loading.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/loading.tsxnew file mode 100644index 000000000..41fdbbaa9--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/loading.tsx@@ -0,0 +1,19 @@+import { Skeleton } from "@openstatus/ui";++import { Header } from "@/components/dashboard/header";+import { SkeletonForm } from "@/components/forms/skeleton-form";++export default function Loading() {+ return (+ <div className="grid gap-6 md:grid-cols-2 md:gap-8">+ <div className="col-span-full flex w-full justify-between">+ <Header.Skeleton>+ <Skeleton className="h-9 w-20" />+ </Header.Skeleton>+ </div>+ <div className="col-span-full">+ <SkeletonForm />+ </div>+ </div>+ );+}diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/page.tsxnew file mode 100644index 000000000..6b9be41d6--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/page.tsx@@ -0,0 +1,51 @@+import { notFound } from "next/navigation";+import * as z from "zod";++import { Header } from "@/components/dashboard/header";+import { NotificationForm } from "@/components/forms/notification-form";+import { api } from "@/trpc/server";++/**+ * allowed URL search params+ */+const searchParamsSchema = z.object({+ id: z.coerce.number().optional(),+});++export default async function EditPage({+ params,+ searchParams,+}: {+ params: { workspaceSlug: string };+ searchParams: { [key: string]: string | string[] | undefined };+}) {+ const search = searchParamsSchema.safeParse(searchParams);++ if (!search.success) {+ return notFound();+ }++ const { id } = search.data;++ const notification =+ id && (await api.notification.getNotificationById.query({ id }));++ return (+ <div className="grid gap-6 md:grid-cols-2 md:gap-8">+ <Header+ title="Notification"+ description={+ notification+ ? "Update your notification channel"+ : "Create your notification channel"+ }+ />+ <div className="col-span-full">+ <NotificationForm+ workspaceSlug={params.workspaceSlug}+ defaultValues={notification || undefined}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/loading.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/loading.tsxnew file mode 100644index 000000000..5fab49f41--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/loading.tsx@@ -0,0 +1,19 @@+import { Skeleton } from "@openstatus/ui";++import { Header } from "@/components/dashboard/header";+import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton";++export default function Loading() {+ return (+ <div className="grid gap-6 md:grid-cols-2 md:gap-8">+ <div className="col-span-full flex w-full justify-between">+ <Header.Skeleton>+ <Skeleton className="h-9 w-20" />+ </Header.Skeleton>+ </div>+ <div className="col-span-full w-full">+ <DataTableSkeleton />+ </div>+ </div>+ );+}diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/page.tsxnew file mode 100644index 000000000..cf5e5ba7a--- /dev/null+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/page.tsx@@ -0,0 +1,48 @@+import * as React from "react";+import Link from "next/link";++import { Button } from "@openstatus/ui";++import { Header } from "@/components/dashboard/header";+import { HelpCallout } from "@/components/dashboard/help-callout";+import { columns } from "@/components/data-table/notification/columns";+import { DataTable } from "@/components/data-table/notification/data-table";+import { api } from "@/trpc/server";+import { EmptyState } from "./_components/empty-state";++export default async function MonitorPage({+ params,+}: {+ params: { workspaceSlug: string };+}) {+ const notifications =+ await api.notification.getNotificationsByWorkspace.query({+ workspaceSlug: params.workspaceSlug,+ });++ return (+ <div className="grid min-h-full grid-cols-1 grid-rows-[auto,1fr,auto] gap-6 md:grid-cols-2 md:gap-8">+ <Header+ title="Notifications"+ description="Overview of all your notification channels."+ actions={+ <Button asChild>+ <Link href="./notifications/edit">Create</Link>+ </Button>+ }+ />+ {notifications && notifications.length > 0 ? (+ <div className="col-span-full">+ <DataTable columns={columns} data={notifications} />+ </div>+ ) : (+ <div className="col-span-full">+ <EmptyState />+ </div>+ )}+ <div className="mt-8 md:mt-12">+ <HelpCallout />+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/data-table/notification/columns.tsx b/apps/web/src/components/data-table/notification/columns.tsxnew file mode 100644index 000000000..05a5f87bd--- /dev/null+++ b/apps/web/src/components/data-table/notification/columns.tsx@@ -0,0 +1,40 @@+"use client";++import type { ColumnDef } from "@tanstack/react-table";++import type { Notification } from "@openstatus/db/src/schema";+import { Badge } from "@openstatus/ui";++import { DataTableRowActions } from "./data-table-row-actions";++export const columns: ColumnDef<Notification>[] = [+ {+ accessorKey: "name",+ header: "Name",+ },+ {+ accessorKey: "provider",+ header: "Provider",+ cell: ({ row }) => {+ return (+ <Badge variant="secondary" className="capitalize">+ {row.getValue("provider")}+ </Badge>+ );+ },+ },+ // {+ // accessorKey: "data",+ // header: "Data",+ // },+ {+ id: "actions",+ cell: ({ row }) => {+ return (+ <div className="text-right">+ <DataTableRowActions row={row} />+ </div>+ );+ },+ },+];diff --git a/apps/web/src/components/data-table/notification/data-table-row-actions.tsx b/apps/web/src/components/data-table/notification/data-table-row-actions.tsxnew file mode 100644index 000000000..d6f03ca07--- /dev/null+++ b/apps/web/src/components/data-table/notification/data-table-row-actions.tsx@@ -0,0 +1,108 @@+"use client";++import * as React from "react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import type { Row } from "@tanstack/react-table";+import { MoreHorizontal } from "lucide-react";++import { selectNotificationSchema } from "@openstatus/db/src/schema";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@openstatus/ui";++import { LoadingAnimation } from "@/components/loading-animation";+import { useToastAction } from "@/hooks/use-toast-action";+import { api } from "@/trpc/client";++interface DataTableRowActionsProps<TData> {+ row: Row<TData>;+}++export function DataTableRowActions<TData>({+ row,+}: DataTableRowActionsProps<TData>) {+ const notification = selectNotificationSchema.parse(row.original);+ const router = useRouter();+ const { toast } = useToastAction();+ const [alertOpen, setAlertOpen] = React.useState(false);+ const [isPending, startTransition] = React.useTransition();++ async function onDelete() {+ startTransition(async () => {+ console.log({ notification });+ try {+ if (!notification.id) return;+ await api.notification.deleteNotification.mutate({+ id: notification.id,+ });+ toast("deleted");+ router.refresh();+ setAlertOpen(false);+ } catch {+ toast("error");+ }+ });+ }++ return (+ <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ className="data-[state=open]:bg-accent h-8 w-8 p-0"+ >+ <span className="sr-only">Open menu</span>+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <Link href={`./notifications/edit?id=${notification.id}`}>+ <DropdownMenuItem>Edit</DropdownMenuItem>+ </Link>+ <AlertDialogTrigger asChild>+ <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">+ Delete+ </DropdownMenuItem>+ </AlertDialogTrigger>+ </DropdownMenuContent>+ </DropdownMenu>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>+ <AlertDialogDescription>+ This action cannot be undone. This will permanently delete the+ notification.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={(e) => {+ e.preventDefault();+ onDelete();+ }}+ disabled={isPending}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {!isPending ? "Delete" : <LoadingAnimation />}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/apps/web/src/components/data-table/notification/data-table.tsx b/apps/web/src/components/data-table/notification/data-table.tsxnew file mode 100644index 000000000..bbe2814b4--- /dev/null+++ b/apps/web/src/components/data-table/notification/data-table.tsx@@ -0,0 +1,81 @@+"use client";++import * as React from "react";+import type { ColumnDef } from "@tanstack/react-table";+import {+ flexRender,+ getCoreRowModel,+ useReactTable,+} from "@tanstack/react-table";++import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@openstatus/ui";++interface DataTableProps<TData, TValue> {+ columns: ColumnDef<TData, TValue>[];+ data: TData[];+}++export function DataTable<TData, TValue>({+ columns,+ data,+}: DataTableProps<TData, TValue>) {+ const table = useReactTable({+ data,+ columns,+ getCoreRowModel: getCoreRowModel(),+ });++ return (+ <div className="rounded-md border">+ <Table>+ <TableHeader className="bg-muted/50">+ {table.getHeaderGroups().map((headerGroup) => (+ <TableRow key={headerGroup.id} className="hover:bg-transparent">+ {headerGroup.headers.map((header) => {+ return (+ <TableHead key={header.id}>+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext(),+ )}+ </TableHead>+ );+ })}+ </TableRow>+ ))}+ </TableHeader>+ <TableBody>+ {table.getRowModel().rows?.length ? (+ table.getRowModel().rows.map((row) => (+ <TableRow+ key={row.id}+ data-state={row.getIsSelected() && "selected"}+ >+ {row.getVisibleCells().map((cell) => (+ <TableCell key={cell.id}>+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </TableCell>+ ))}+ </TableRow>+ ))+ ) : (+ <TableRow>+ <TableCell colSpan={columns.length} className="h-24 text-center">+ No results.+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div>+ );+}diff --git a/apps/web/src/components/forms/incident-form.tsx b/apps/web/src/components/forms/incident-form.tsxindex b51db5d1c..38cc32850 100644--- a/apps/web/src/components/forms/incident-form.tsx+++ b/apps/web/src/components/forms/incident-form.tsx@@ -13,6 +13,10 @@ import {StatusEnum,} from "@openstatus/db/src/schema";import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,Button,Checkbox,DateTimePicker,@@ -116,181 +120,217 @@ export function IncidentForm({e.preventDefault();form.handleSubmit(onSubmit)(e);}}- className="grid w-full grid-cols-1 items-center gap-6 sm:grid-cols-6"+ className="grid w-full gap-6">- <FormField- control={form.control}- name="title"- render={({ field }) => (- <FormItem className="sm:col-span-4">- <FormLabel>Title</FormLabel>- <FormControl>- <Input placeholder="" {...field} />- </FormControl>- <FormDescription>The title of your page.</FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="status"- render={({ field }) => (- <FormItem className="col-span-full space-y-1">- <FormLabel>Status</FormLabel>- <FormDescription>Select the current status.</FormDescription>- <FormMessage />- <RadioGroup- onValueChange={(value) =>- field.onChange(StatusEnum.parse(value))- } // value is a string- defaultValue={field.value}- className="grid grid-cols-2 gap-4 sm:grid-cols-4 sm:gap-8"- >- {availableStatus.map((status) => {- const { value, label, icon } = statusDict[status];- const Icon = Icons[icon];- return (- <FormItem key={value}>- <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">- <FormControl>- <RadioGroupItem value={value} className="sr-only" />- </FormControl>- <div className="border-border text-muted-foreground flex w-full items-center justify-center rounded-lg border p-2 px-6 py-3 text-center">- <Icon className="mr-2 h-4 w-4" />- {label}- </div>- </FormLabel>- </FormItem>- );- })}- </RadioGroup>- </FormItem>- )}- />- {/* include update on creation */}- {!defaultValues ? (- <div className="bg-accent/40 border-border col-span-full -m-3 grid gap-6 rounded-lg border p-3 sm:grid-cols-6">+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">Inform</p>+ <p className="text-muted-foreground text-sm">+ Keep your users informed about what just happened.+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2 sm:grid-cols-3"><FormFieldcontrol={form.control}- name="message"+ name="title"render={({ field }) => (<FormItem className="sm:col-span-4">- <FormLabel>Message</FormLabel>- <Tabs defaultValue="write">- <TabsList>- <TabsTrigger value="write">Write</TabsTrigger>- <TabsTrigger value="preview">Preview</TabsTrigger>- </TabsList>- <TabsContent value="write">- <FormControl>- <Textarea- placeholder="We are encountering..."- className="h-auto w-full resize-none"- rows={9}- {...field}- />- </FormControl>- </TabsContent>- <TabsContent value="preview">- <Preview md={form.getValues("message")} />- </TabsContent>- </Tabs>- <FormDescription>- Tell your user what's happening. Supports markdown.- </FormDescription>+ <FormLabel>Title</FormLabel>+ <FormControl>+ <Input placeholder="Downtime..." {...field} />+ </FormControl>+ <FormDescription>The title of your outage.</FormDescription><FormMessage /></FormItem>)}/><FormFieldcontrol={form.control}- name="date"+ name="status"render={({ field }) => (- <FormItem className="flex flex-col sm:col-span-full">- <FormLabel>Date</FormLabel>- <DateTimePicker- date={field.value ? new Date(field.value) : new Date()}- setDate={(date) => {- field.onChange(date);- }}- />- <FormDescription>- The date and time when the incident took place.- </FormDescription>+ <FormItem className="col-span-full space-y-1">+ <FormLabel>Status</FormLabel>+ <FormDescription>Select the current status.</FormDescription>+ <FormMessage />+ <RadioGroup+ onValueChange={(value) =>+ field.onChange(StatusEnum.parse(value))+ } // value is a string+ defaultValue={field.value}+ className="grid grid-cols-2 gap-4 sm:grid-cols-4"+ >+ {availableStatus.map((status) => {+ const { value, label, icon } = statusDict[status];+ const Icon = Icons[icon];+ return (+ <FormItem key={value}>+ <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">+ <FormControl>+ <RadioGroupItem+ value={value}+ className="sr-only"+ />+ </FormControl>+ <div className="border-border text-muted-foreground flex w-full items-center justify-center rounded-lg border px-3 py-2 text-center text-sm">+ <Icon className="mr-2 h-4 w-4 shrink-0" />+ <span className="truncate">{label}</span>+ </div>+ </FormLabel>+ </FormItem>+ );+ })}+ </RadioGroup>+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="monitors"+ render={() => (+ <FormItem className="sm:col-span-full">+ <div className="mb-4">+ <FormLabel>Monitors</FormLabel>+ <FormDescription>+ Select the monitors that you want to refer the incident+ to.+ </FormDescription>+ </div>+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">+ {monitors?.map((item) => (+ <FormField+ key={item.id}+ control={form.control}+ name="monitors"+ render={({ field }) => {+ return (+ <FormItem+ key={item.id}+ className="flex flex-row items-start space-x-3 space-y-0"+ >+ <FormControl>+ <Checkbox+ 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,+ ),+ );+ }}+ />+ </FormControl>+ <div className="grid gap-1.5 leading-none">+ <div className="flex items-center gap-2">+ <FormLabel className="font-normal">+ {item.name}+ </FormLabel>+ <span+ className={cn(+ "rounded-full p-1",+ item.active+ ? "bg-green-500"+ : "bg-red-500",+ )}+ ></span>+ </div>+ <p className="text-muted-foreground truncate text-sm">+ {item.description}+ </p>+ </div>+ </FormItem>+ );+ }}+ />+ ))}+ </div><FormMessage /></FormItem>)}/></div>- ) : null}- <FormField- control={form.control}- name="monitors"- render={() => (- <FormItem className="sm:col-span-full">- <div className="mb-4">- <FormLabel>Monitors</FormLabel>- <FormDescription>- Select the monitors that you want to refer the incident to.- </FormDescription>- </div>- <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">- {monitors?.map((item) => (- <FormField- key={item.id}- control={form.control}- name="monitors"- render={({ field }) => {- return (- <FormItem- key={item.id}- className="flex flex-row items-start space-x-3 space-y-0"- >- <FormControl>- <Checkbox- 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,- ),- );- }}- />- </FormControl>- <div className="grid gap-1.5 leading-none">- <div className="flex items-center gap-2">- <FormLabel className="font-normal">- {item.name}- </FormLabel>- <span- className={cn(- "rounded-full p-1",- item.active ? "bg-green-500" : "bg-red-500",- )}- ></span>- </div>- <p className="text-muted-foreground truncate text-sm">- {item.description}- </p>- </div>+ </div>+ {/* include update on creation */}+ {!defaultValues ? (+ <Accordion type="single" defaultValue="message" collapsible>+ <AccordionItem value="message">+ <AccordionTrigger>Message</AccordionTrigger>+ <AccordionContent>+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">+ Incident Update+ </p>+ <p className="text-muted-foreground text-sm">+ What is actually going wrong?+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2 sm:grid-cols-2">+ <FormField+ control={form.control}+ name="message"+ render={({ field }) => (+ <FormItem className="sm:col-span-4">+ <FormLabel>Message</FormLabel>+ <Tabs defaultValue="write">+ <TabsList>+ <TabsTrigger value="write">Write</TabsTrigger>+ <TabsTrigger value="preview">Preview</TabsTrigger>+ </TabsList>+ <TabsContent value="write">+ <FormControl>+ <Textarea+ placeholder="We are encountering..."+ className="h-auto w-full resize-none"+ rows={9}+ {...field}+ />+ </FormControl>+ </TabsContent>+ <TabsContent value="preview">+ <Preview md={form.getValues("message")} />+ </TabsContent>+ </Tabs>+ <FormDescription>+ Tell your user what's happening. Supports+ markdown.+ </FormDescription>+ <FormMessage /></FormItem>- );- }}- />- ))}- </div>- <FormMessage />- </FormItem>- )}- />- <div className="sm:col-span-full">+ )}+ />+ <FormField+ control={form.control}+ name="date"+ render={({ field }) => (+ <FormItem className="flex flex-col sm:col-span-full">+ <FormLabel>Date</FormLabel>+ <DateTimePicker+ date={+ field.value ? new Date(field.value) : new Date()+ }+ setDate={(date) => {+ field.onChange(date);+ }}+ />+ <FormDescription>+ The date and time when the incident took place.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ ) : null}+ <div className="flex sm:justify-end"><Button className="w-full sm:w-auto" size="lg">{!isPending ? "Confirm" : <LoadingAnimation />}</Button>diff --git a/apps/web/src/components/forms/incident-update-form.tsx b/apps/web/src/components/forms/incident-update-form.tsxindex b1ab7ce02..486a2427b 100644--- a/apps/web/src/components/forms/incident-update-form.tsx+++ b/apps/web/src/components/forms/incident-update-form.tsx@@ -90,96 +90,110 @@ export function IncidentUpdateForm({e.preventDefault();form.handleSubmit(onSubmit)(e);}}- className="grid w-full grid-cols-1 items-center gap-6 sm:grid-cols-6"+ className="grid w-full gap-6">- <FormField- control={form.control}- name="status"- render={({ field }) => (- <FormItem className="col-span-full space-y-1">- <FormLabel>Status</FormLabel>- <FormDescription>Select the current status.</FormDescription>- <FormMessage />- <RadioGroup- onValueChange={(value) =>- field.onChange(StatusEnum.parse(value))- } // value is a string- defaultValue={field.value}- className="grid grid-cols-2 gap-4 sm:grid-cols-4 sm:gap-8"- >- {availableStatus.map((status) => {- const { value, label, icon } = statusDict[status];- const Icon = Icons[icon];- return (- <FormItem key={value}>- <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">- <FormControl>- <RadioGroupItem value={value} className="sr-only" />- </FormControl>- <div className="border-border text-muted-foreground flex w-full items-center justify-center rounded-lg border p-2 px-6 py-3 text-center">- <Icon className="mr-2 h-4 w-4" />- {label}- </div>- </FormLabel>- </FormItem>- );- })}- </RadioGroup>- </FormItem>- )}- />- <FormField- control={form.control}- name="message"- render={({ field }) => (- <FormItem className="sm:col-span-4">- <FormLabel>Message</FormLabel>- <Tabs defaultValue="write">- <TabsList>- <TabsTrigger value="write">Write</TabsTrigger>- <TabsTrigger value="preview">Preview</TabsTrigger>- </TabsList>- <TabsContent value="write">- <FormControl>- <Textarea- placeholder="We are encountering..."- className="h-auto w-full resize-none"- rows={9}- {...field}- />- </FormControl>- </TabsContent>- <TabsContent value="preview">- <Preview md={form.getValues("message")} />- </TabsContent>- </Tabs>- <FormDescription>- Tell your user what's happening. Supports markdown.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="date"- render={({ field }) => (- <FormItem className="flex flex-col sm:col-span-full">- <FormLabel>Date</FormLabel>- <DateTimePicker- date={new Date(field.value)}- setDate={(date) => {- field.onChange(date);- }}- />- <FormDescription>- The date and time when the incident took place.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <div className="sm:col-span-full">+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">Inform</p>+ <p className="text-muted-foreground text-sm">+ Keep your users informed about what just happened.+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2 sm:grid-cols-3">+ <FormField+ control={form.control}+ name="status"+ render={({ field }) => (+ <FormItem className="space-y-1 sm:col-span-full">+ <FormLabel>Status</FormLabel>+ <FormDescription>Select the current status.</FormDescription>+ <FormMessage />+ <RadioGroup+ onValueChange={(value) =>+ field.onChange(StatusEnum.parse(value))+ } // value is a string+ defaultValue={field.value}+ className="grid grid-cols-2 gap-4 sm:grid-cols-4"+ >+ {availableStatus.map((status) => {+ const { value, label, icon } = statusDict[status];+ const Icon = Icons[icon];+ return (+ <FormItem key={value}>+ <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">+ <FormControl>+ <RadioGroupItem+ value={value}+ className="sr-only"+ />+ </FormControl>+ <div className="border-border text-muted-foreground flex w-full items-center justify-center rounded-lg border px-3 py-2 text-center text-sm">+ <Icon className="mr-2 h-4 w-4 shrink-0" />+ <span className="truncate">{label}</span>+ </div>+ </FormLabel>+ </FormItem>+ );+ })}+ </RadioGroup>+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="message"+ render={({ field }) => (+ <FormItem className="sm:col-span-full">+ <FormLabel>Message</FormLabel>+ <Tabs defaultValue="write">+ <TabsList>+ <TabsTrigger value="write">Write</TabsTrigger>+ <TabsTrigger value="preview">Preview</TabsTrigger>+ </TabsList>+ <TabsContent value="write">+ <FormControl>+ <Textarea+ placeholder="We are encountering..."+ className="h-auto w-full resize-none"+ rows={9}+ {...field}+ />+ </FormControl>+ </TabsContent>+ <TabsContent value="preview">+ <Preview md={form.getValues("message")} />+ </TabsContent>+ </Tabs>+ <FormDescription>+ Tell your user what's happening. Supports markdown.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="date"+ render={({ field }) => (+ <FormItem className="flex flex-col sm:col-span-2">+ <FormLabel>Date</FormLabel>+ <DateTimePicker+ className="w-full"+ date={new Date(field.value)}+ setDate={(date) => {+ field.onChange(date);+ }}+ />+ <FormDescription>+ The date and time when the incident took place.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </div>+ <div className="flex sm:justify-end"><Button className="w-full sm:w-auto" size="lg">{!isPending ? "Confirm" : <LoadingAnimation />}</Button>diff --git a/apps/web/src/components/forms/montitor-form.tsx b/apps/web/src/components/forms/montitor-form.tsxindex dea0afbf5..d51da89bd 100644--- a/apps/web/src/components/forms/montitor-form.tsx+++ b/apps/web/src/components/forms/montitor-form.tsx@@ -1,6 +1,5 @@"use client";-import { METHODS } from "http";import * as React from "react";import { useRouter } from "next/navigation";import { zodResolver } from "@hookform/resolvers/zod";@@ -8,18 +7,30 @@ import { Check, ChevronsUpDown, Wand2, X } from "lucide-react";import { useFieldArray, useForm } from "react-hook-form";import * as z from "zod";+import type { selectNotificationSchema } from "@openstatus/db/src/schema";import {insertMonitorSchema,periodicityEnum,} from "@openstatus/db/src/schema";import { allPlans } from "@openstatus/plans";import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,Button,+ Checkbox,Command,CommandEmpty,CommandGroup,CommandInput,CommandItem,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,Form,FormControl,FormDescription,@@ -38,19 +49,19 @@ import {SelectValue,Switch,Textarea,- toast,Tooltip,TooltipContent,TooltipProvider,TooltipTrigger,} from "@openstatus/ui";+import { LoadingAnimation } from "@/components/loading-animation";import { regionsDict } from "@/data/regions-dictionary";import { useToastAction } from "@/hooks/use-toast-action";import useUpdateSearchParams from "@/hooks/use-update-search-params";import { cn } from "@/lib/utils";import { api } from "@/trpc/client";-import { LoadingAnimation } from "../loading-animation";+import { NotificationForm } from "./notification-form";const cronJobs = [{ value: "1m", label: "1 minute" },@@ -80,13 +91,15 @@ type MonitorProps = z.infer<typeof mergedSchema>;interface Props {defaultValues?: MonitorProps;workspaceSlug: string;- plan?: "free" | "pro"; // HOTFIX - We can think of returning `workspace` instead of `workspaceSlug`+ plan?: "free" | "pro";+ notifications?: z.infer<typeof selectNotificationSchema>[]; // HOTFIX - We can think of returning `workspace` instead of `workspaceSlug`}export function MonitorForm({defaultValues,workspaceSlug,plan = "free",+ notifications,}: Props) {const form = useForm<MonitorProps>({resolver: zodResolver(mergedSchema), // too much - we should only validate the values we ask inside of the form!@@ -103,11 +116,13 @@ export function MonitorForm({: [{ key: "", value: "" }],body: defaultValues?.body ?? "",method: defaultValues?.method ?? "GET",+ notifications: defaultValues?.notifications ?? [],},});const router = useRouter();const [isPending, startTransition] = React.useTransition();const [isTestPending, startTestTransition] = React.useTransition();+ const [openDialog, setOpenDialog] = React.useState(false);const { toast } = useToastAction();const watchMethod = form.watch("method");const updateSearchParams = useUpdateSearchParams();@@ -187,334 +202,486 @@ export function MonitorForm({const limit = allPlans[plan].limits.periodicity;return (- <Form {...form}>- <form- onSubmit={form.handleSubmit(onSubmit)}- className="grid w-full grid-cols-1 items-center gap-6 sm:grid-cols-6"- >- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem className="sm:col-span-3">- <FormLabel>Name</FormLabel>- <FormControl>- <Input placeholder="Documenso" {...field} />- </FormControl>- <FormDescription>Displayed on the status page.</FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="description"- render={({ field }) => (- <FormItem className="sm:col-span-5">- <FormLabel>Description</FormLabel>- <FormControl>- <Input- placeholder="Determines the api health of our services."- {...field}- />- </FormControl>- <FormDescription>- Provide your users with information about it.{" "}- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="method"- render={({ field }) => (- <FormItem className="sm:col-span-1 sm:col-start-1 sm:self-baseline">- <FormLabel>Method</FormLabel>- <Select- onValueChange={(value) => {- field.onChange(methodsEnum.parse(value));- form.resetField("body", { defaultValue: "" });- }}- defaultValue={field.value}- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select" />- </SelectTrigger>- </FormControl>- <SelectContent>- {methods.map((method) => (- <SelectItem key={method} value={method}>- {method}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="url"- render={({ field }) => (- <FormItem className="sm:col-span-4">- <FormLabel>URL</FormLabel>- <FormControl>- {/* <InputWithAddons- leading="https://"- placeholder="documenso.com/api/health"- {...field}- /> */}- <Input- placeholder="https://documenso.com/api/health"- {...field}- />- </FormControl>- <FormDescription>- Here is the URL you want to monitor.{" "}- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <div className="space-y-2 sm:col-span-full">- {/* TODO: add FormDescription for latest key/value */}- <FormLabel>Request Header</FormLabel>- {fields.map((field, index) => (- <div key={field.id} className="grid grid-cols-6 gap-6">+ <Dialog open={openDialog} onOpenChange={(val) => setOpenDialog(val)}>+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="grid w-full gap-6"+ >+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">+ Endpoint Check+ </p>+ <p className="text-muted-foreground text-sm">+ The easiest way to get started.+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2"><FormFieldcontrol={form.control}- name={`headers.${index}.key`}+ name="name"render={({ field }) => (- <FormItem className="col-span-2">+ <FormItem>+ <FormLabel>Name</FormLabel><FormControl>- <Input placeholder="key" {...field} />+ <Input placeholder="Documenso" {...field} /></FormControl>+ <FormDescription>+ Displayed on the status page.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="url"+ render={({ field }) => (+ <FormItem>+ <FormLabel>URL</FormLabel>+ <FormControl>+ {/* <InputWithAddons+ leading="https://"+ placeholder="documenso.com/api/health"+ {...field}+ /> */}+ <Input+ placeholder="https://documenso.com/api/health"+ {...field}+ />+ </FormControl>+ <FormDescription>+ Here is the URL you want to monitor.{" "}+ </FormDescription>+ <FormMessage /></FormItem>)}/>- <div className="col-span-4 flex items-center space-x-2">- <FormField- control={form.control}- name={`headers.${index}.value`}- render={({ field }) => (- <FormItem className="w-full">- <FormControl>- <Input placeholder="value" {...field} />- </FormControl>- </FormItem>- )}- />- <Button- size="icon"- variant="ghost"- type="button"- onClick={() => remove(Number(field.id))}- >- <X className="h-4 w-4" />- </Button>- </div></div>- ))}- <div>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => append({ key: "", value: "" })}- >- Add Custom Header- </Button></div>- </div>- {watchMethod === "POST" && (- <div className="sm:col-span-4 sm:col-start-1">- <FormField- control={form.control}- name="body"- render={({ field }) => (- <FormItem>- <div className="flex items-end justify-between">- <FormLabel>Body</FormLabel>- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Button- type="button"- variant="ghost"- size="icon"- onClick={onPrettifyJSON}- >- <Wand2 className="h-4 w-4" />- </Button>- </TooltipTrigger>- <TooltipContent>- <p>Prettify JSON</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>+ <Accordion type="single" collapsible>+ <AccordionItem value="http-request-settings">+ <AccordionTrigger>HTTP Request Settings</AccordionTrigger>+ <AccordionContent>+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">+ Custom Request+ </p>+ <p className="text-muted-foreground text-sm">+ If your endpoint is secured, add additional configuration+ to the request we send.+ </p></div>- <FormControl>- <Textarea- rows={8}- placeholder='{ "hello": "world" }'- {...field}- />- </FormControl>- <FormDescription>Write your json payload.</FormDescription>- <FormMessage />- </FormItem>- )}- />- </div>- )}- <div className="sm:col-span-2 sm:col-start-1">- <Button- type="button"- variant="default"- className="w-full md:w-auto"- size="lg"- onClick={sendTestPing}- >- {!isTestPending ? "Test Request" : <LoadingAnimation />}- </Button>- </div>- <FormField- control={form.control}- name="periodicity"- render={({ field }) => (- <FormItem className="sm:col-span-3 sm:col-start-1 sm:self-baseline">- <FormLabel>Frequency</FormLabel>- <Select- onValueChange={(value) =>- field.onChange(periodicityEnum.parse(value))- }- defaultValue={field.value}- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="How often should it check your endpoint?" />- </SelectTrigger>- </FormControl>- <SelectContent>- {cronJobs.map(({ label, value }) => (- <SelectItem- key={value}- value={value}- disabled={!limit.includes(value)}- >- {label}- </SelectItem>- ))}- </SelectContent>- </Select>- <FormDescription>- Frequency of how often your endpoint will be pinged.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="regions"- render={({ field }) => (- <FormItem className="sm:col-span-3 sm:self-baseline">- <FormLabel>Regions</FormLabel>- <Popover>- <PopoverTrigger asChild>- <FormControl>- <Button- variant="outline"- role="combobox"- className={cn(- "h-10 w-full justify-between",- !field.value && "text-muted-foreground",- )}- >- {/* This is a hotfix */}- {field.value?.length === 1 && field.value[0].length > 0- ? regionsDict[- field.value[0] as keyof typeof regionsDict- ].location- : "Select region"}- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />- </Button>- </FormControl>- </PopoverTrigger>- <PopoverContent className="w-full p-0">- <Command>- <CommandInput placeholder="Select a region..." />- <CommandEmpty>No regions found.</CommandEmpty>- <CommandGroup className="max-h-[150px] overflow-y-scroll">- {Object.keys(regionsDict).map((region) => {- const { code, location } =- regionsDict[region as keyof typeof regionsDict];- const isSelected = field.value?.includes(code);- return (- <CommandItem- value={code}- key={code}- onSelect={() => {- form.setValue("regions", [code]); // TODO: allow more than one to be selected in the future+ <div className="grid gap-6 sm:col-span-2 sm:grid-cols-4">+ <FormField+ control={form.control}+ name="method"+ render={({ field }) => (+ <FormItem className="sm:col-span-1 sm:self-baseline">+ <FormLabel>Method</FormLabel>+ <Select+ onValueChange={(value) => {+ field.onChange(methodsEnum.parse(value));+ form.resetField("body", { defaultValue: "" });}}+ defaultValue={field.value}>- <Check- className={cn(- "mr-2 h-4 w-4",- isSelected ? "opacity-100" : "opacity-0",+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {methods.map((method) => (+ <SelectItem key={method} value={method}>+ {method}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ <div className="space-y-2 sm:col-span-full">+ <FormLabel>Request Header</FormLabel>+ {fields.map((field, index) => (+ <div key={field.id} className="grid grid-cols-6 gap-6">+ <FormField+ control={form.control}+ name={`headers.${index}.key`}+ render={({ field }) => (+ <FormItem className="col-span-2">+ <FormControl>+ <Input placeholder="key" {...field} />+ </FormControl>+ </FormItem>+ )}+ />+ <div className="col-span-4 flex items-center space-x-2">+ <FormField+ control={form.control}+ name={`headers.${index}.value`}+ render={({ field }) => (+ <FormItem className="w-full">+ <FormControl>+ <Input placeholder="value" {...field} />+ </FormControl>+ </FormItem>)}/>- {location}- </CommandItem>- );- })}- </CommandGroup>- </Command>- </PopoverContent>- </Popover>- <FormDescription>- Select your region. Leave blank for random picked regions.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="active"- render={({ field }) => (- <FormItem className="flex flex-row items-center justify-between sm:col-span-4">- <div className="space-y-0.5">- <FormLabel>Active</FormLabel>- <FormDescription>- This will start ping your endpoint on based on the selected- frequence.- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value || false}- onCheckedChange={(value) => field.onChange(value)}- />- </FormControl>- <FormMessage />- </FormItem>- )}+ <Button+ size="icon"+ variant="ghost"+ type="button"+ onClick={() => remove(Number(field.id))}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ </div>+ ))}+ <div>+ <Button+ type="button"+ variant="outline"+ onClick={() => append({ key: "", value: "" })}+ >+ Add Custom Header+ </Button>+ </div>+ </div>+ {watchMethod === "POST" && (+ <div className="sm:col-span-full">+ <FormField+ control={form.control}+ name="body"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-end justify-between">+ <FormLabel>Body</FormLabel>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={onPrettifyJSON}+ >+ <Wand2 className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Prettify JSON</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ <FormControl>+ <Textarea+ rows={8}+ placeholder='{ "hello": "world" }'+ {...field}+ />+ </FormControl>+ <FormDescription>+ Write your json payload.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ )}+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ <AccordionItem value="advanced-settings">+ <AccordionTrigger>Advanced Settings</AccordionTrigger>+ <AccordionContent>+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">+ More Configurations+ </p>+ <p className="text-muted-foreground text-sm">+ Make it your own. Contact us if you wish for more and we+ will implement it!+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2 sm:grid-cols-2">+ <FormField+ control={form.control}+ name="periodicity"+ render={({ field }) => (+ <FormItem className="sm:col-span-1 sm:self-baseline">+ <FormLabel>Frequency</FormLabel>+ <Select+ onValueChange={(value) =>+ field.onChange(periodicityEnum.parse(value))+ }+ defaultValue={field.value}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="How often should it check your endpoint?" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {cronJobs.map(({ label, value }) => (+ <SelectItem+ key={value}+ value={value}+ disabled={!limit.includes(value)}+ >+ {label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ Frequency of how often your endpoint will be pinged.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="regions"+ render={({ field }) => (+ <FormItem className="sm:col-span-1 sm:self-baseline">+ <FormLabel>Regions</FormLabel>+ <Popover>+ <PopoverTrigger asChild>+ <FormControl>+ <Button+ variant="outline"+ role="combobox"+ className={cn(+ "h-10 w-full justify-between",+ !field.value && "text-muted-foreground",+ )}+ >+ {/* This is a hotfix */}+ {field.value?.length === 1 &&+ field.value[0].length > 0+ ? regionsDict[+ field+ .value[0] as keyof typeof regionsDict+ ].location+ : "Select region"}+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />+ </Button>+ </FormControl>+ </PopoverTrigger>+ <PopoverContent className="w-full p-0">+ <Command>+ <CommandInput placeholder="Select a region..." />+ <CommandEmpty>No regions found.</CommandEmpty>+ <CommandGroup className="max-h-[150px] overflow-y-scroll">+ {Object.keys(regionsDict).map((region) => {+ const { code, location } =+ regionsDict[+ region as keyof typeof regionsDict+ ];+ const isSelected =+ field.value?.includes(code);+ return (+ <CommandItem+ value={code}+ key={code}+ onSelect={() => {+ form.setValue("regions", [code]); // TODO: allow more than one to be selected in the future+ }}+ >+ <Check+ className={cn(+ "mr-2 h-4 w-4",+ isSelected+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ {location}+ </CommandItem>+ );+ })}+ </CommandGroup>+ </Command>+ </PopoverContent>+ </Popover>+ <FormDescription>+ Select your region. Leave blank for random picked+ regions.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem className="sm:col-span-2">+ <FormLabel>Description</FormLabel>+ <FormControl>+ <Input+ placeholder="Determines the api health of our services."+ {...field}+ />+ </FormControl>+ <FormDescription>+ Provide your users with information about it.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="active"+ render={({ field }) => (+ <FormItem className="flex flex-row items-center justify-between sm:col-span-full">+ <div className="space-y-0.5">+ <FormLabel>Active</FormLabel>+ <FormDescription>+ This will start ping your endpoint on based on the+ selected frequence.+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value || false}+ onCheckedChange={(value) => field.onChange(value)}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ <AccordionItem value="notification-settings">+ <AccordionTrigger>Notification Settings</AccordionTrigger>+ <AccordionContent>+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">Alerts</p>+ <p className="text-muted-foreground text-sm">+ How do you want to get informed if things break?+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2">+ <FormField+ control={form.control}+ name="notifications"+ render={() => (+ <FormItem>+ <div className="mb-4">+ <FormLabel className="text-base">+ Notifications+ </FormLabel>+ <FormDescription>+ Select the notification channels you want to be+ informed.+ </FormDescription>+ </div>+ {notifications?.map((item) => (+ <FormField+ key={item.id}+ control={form.control}+ name="notifications"+ render={({ field }) => {+ return (+ <FormItem+ key={item.id}+ className="flex flex-row items-start space-x-3 space-y-0"+ >+ <FormControl>+ <Checkbox+ 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,+ ),+ );+ }}+ />+ </FormControl>+ <div className="space-y-1 leading-none">+ <FormLabel className="font-normal">+ {item.name}+ </FormLabel>+ <FormDescription>+ {item.provider}+ </FormDescription>+ </div>+ </FormItem>+ );+ }}+ />+ ))}+ <FormMessage />+ <div className="sm:col-span-2 sm:col-start-1">+ <DialogTrigger asChild>+ <Button variant="outline">+ Add Notifications+ </Button>+ </DialogTrigger>+ </div>+ </FormItem>+ )}+ />+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ <div className="flex flex-col gap-6 sm:col-span-full sm:flex-row sm:justify-end">+ <Button+ type="button"+ variant="secondary"+ className="w-full sm:w-auto"+ size="lg"+ onClick={sendTestPing}+ >+ {!isTestPending ? (+ "Test Request"+ ) : (+ <LoadingAnimation variant="inverse" />+ )}+ </Button>+ <Button className="w-full sm:w-auto" size="lg" disabled={isPending}>+ {!isPending ? "Confirm" : <LoadingAnimation />}+ </Button>+ </div>+ </form>+ </Form>+ <DialogContent className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle>Add Notification</DialogTitle>+ <DialogDescription>+ Get alerted when your endpoint is down.+ </DialogDescription>+ </DialogHeader>+ <NotificationForm+ onSubmit={() => setOpenDialog(false)}+ {...{ workspaceSlug }}/>- <div className="sm:col-span-full">- {/*- * We could think of having a 'double confirmation' one,- * to check if the endpoint works and approve afterwards- * and confirm anyways even if endpoint failed- */}- <Button className="w-full sm:w-auto" size="lg" disabled={isPending}>- {!isPending ? "Confirm" : <LoadingAnimation />}- </Button>- </div>- </form>- </Form>+ </DialogContent>+ </Dialog>);}diff --git a/apps/web/src/components/forms/notification-form.tsx b/apps/web/src/components/forms/notification-form.tsxnew file mode 100644index 000000000..854667e4c--- /dev/null+++ b/apps/web/src/components/forms/notification-form.tsx@@ -0,0 +1,190 @@+"use client";++import { useTransition } from "react";+import { useRouter } from "next/navigation";+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";++import type { Notification } from "@openstatus/db/src/schema";+import {+ insertNotificationSchema,+ providerEnum,+ providerName,+} from "@openstatus/db/src/schema";+import {+ Button,+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@openstatus/ui";++import { LoadingAnimation } from "@/components/loading-animation";+import { useToastAction } from "@/hooks/use-toast-action";+import { api } from "@/trpc/client";++/**+ * TODO: based on the providers `data` structure, create dynamic form inputs+ * e.g. Provider: Email will need an `email` input field and+ * we store it like `data: { email: "" }`+ * But Provider: Slack will maybe require `webhook` and `channel` and+ * we store it like `data: { webhook: "", channel: "" }`+ */++interface Props {+ defaultValues?: Notification;+ workspaceSlug: string;+ onSubmit?: () => void;+}++export function NotificationForm({+ workspaceSlug,+ defaultValues,+ onSubmit: onExternalSubmit,+}: Props) {+ const [isPending, startTransition] = useTransition();+ const { toast } = useToastAction();+ const router = useRouter();+ const form = useForm<Notification>({+ resolver: zodResolver(insertNotificationSchema),+ defaultValues: {+ ...defaultValues,+ data:+ defaultValues?.provider === "email"+ ? JSON.parse(defaultValues?.data).email+ : "",+ },+ });++ async function onSubmit({ provider, data, ...rest }: Notification) {+ startTransition(async () => {+ try {+ if (defaultValues) {+ await api.notification.updateNotification.mutate({+ provider: "email",+ data: JSON.stringify({ email: data }),+ ...rest,+ });+ } else {+ await api.notification.createNotification.mutate({+ workspaceSlug,+ provider: "email",+ data: JSON.stringify({ email: data }),+ ...rest,+ });+ }+ router.refresh();+ toast("saved");+ } catch {+ toast("error");+ } finally {+ onExternalSubmit?.();+ }+ });+ }++ return (+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="grid w-full gap-6"+ >+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold 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="provider"+ render={({ field }) => (+ <FormItem className="sm:col-span-1 sm:self-baseline">+ <FormLabel>Provider</FormLabel>+ <Select+ onValueChange={(value) =>+ field.onChange(providerEnum.parse(value))+ }+ defaultValue={field.value}+ >+ <FormControl>+ <SelectTrigger className="capitalize">+ <SelectValue placeholder="Select Provider" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {providerName.map((provider) => (+ <SelectItem+ key={provider}+ value={provider}+ disabled={provider !== "email"} // only allow email for now+ className="capitalize"+ >+ {provider}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ What channel/provider to send a notification.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <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>+ )}+ />+ <FormField+ control={form.control}+ name="data"+ render={({ field }) => (+ <FormItem className="sm:col-span-full">+ <FormLabel>Email</FormLabel>+ <FormControl>+ <Input+ type="email"+ placeholder="[email protected]"+ {...field}+ />+ </FormControl>+ <FormDescription>The data required.</FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </div>+ <div className="flex sm:justify-end">+ <Button 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/skeleton-form.tsx b/apps/web/src/components/forms/skeleton-form.tsxindex aa12520ef..f68f8265d 100644--- a/apps/web/src/components/forms/skeleton-form.tsx+++ b/apps/web/src/components/forms/skeleton-form.tsx@@ -2,24 +2,33 @@ import { Skeleton } from "@openstatus/ui";export function SkeletonForm() {return (- <div className="grid w-full grid-cols-1 items-center space-y-6 sm:grid-cols-6">- <div className="space-y-2 sm:col-span-4">- <Skeleton className="h-6 w-24" />- <Skeleton className="h-9 w-full" />- <Skeleton className="h-5 w-64" />+ <div className="grid w-full gap-6">+ <div className="col-span-full grid gap-4 sm:grid-cols-3">+ <div className="flex flex-col gap-2">+ <Skeleton className="h-6 w-24" />+ <Skeleton className="h-6 w-40" />+ </div>+ <div className="grid w-full gap-6 sm:col-span-2">+ <div className="space-y-2">+ <Skeleton className="h-6 w-24" />+ <Skeleton className="h-9 w-full" />+ <Skeleton className="h-5 w-64" />+ </div>+ <div className="space-y-2">+ <Skeleton className="h-6 w-24" />+ <Skeleton className="h-9 w-full" />+ <Skeleton className="h-5 w-64" />+ </div>+ <div className="space-y-2">+ <Skeleton className="h-6 w-24" />+ <Skeleton className="h-9 w-full" />+ <Skeleton className="h-5 w-64" />+ </div>+ </div></div>- <div className="space-y-2 sm:col-span-5">- <Skeleton className="h-6 w-24" />- <Skeleton className="h-9 w-full" />- <Skeleton className="h-5 w-64" />- </div>- <div className="space-y-2 sm:col-span-3">- <Skeleton className="h-6 w-24" />- <Skeleton className="h-9 w-full" />- <Skeleton className="h-5 w-64" />- </div>- <div className="space-y-2 sm:col-span-full">- <Skeleton className="h-9 w-20" />+ <Skeleton className="h-9 w-full" />+ <div className="flex space-y-2 sm:col-span-full sm:justify-end">+ <Skeleton className="h-9 w-full sm:w-28" /></div></div>);diff --git a/apps/web/src/components/forms/status-page-form.tsx b/apps/web/src/components/forms/status-page-form.tsxindex 3d6cecb8c..79e2516c8 100644--- a/apps/web/src/components/forms/status-page-form.tsx+++ b/apps/web/src/components/forms/status-page-form.tsx@@ -12,6 +12,10 @@ import type * as z from "zod";import type { allMonitorsExtendedSchema } from "@openstatus/db/src/schema";import { insertPageSchemaWithMonitors } from "@openstatus/db/src/schema";import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,Button,Checkbox,Form,@@ -185,159 +189,193 @@ export function StatusPageForm({}}}}- className="grid w-full grid-cols-1 items-center gap-6 sm:grid-cols-6"+ className="grid w-full gap-6">- <FormField- control={form.control}- name="title"- render={({ field }) => (- <FormItem className="sm:col-span-4">- <FormLabel>Title</FormLabel>- <FormControl>- <Input placeholder="Documenso Status" {...field} />- </FormControl>- <FormDescription>The title of your page.</FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="description"- render={({ field }) => (- <FormItem className="sm:col-span-5">- <FormLabel>Description</FormLabel>- <FormControl>- <Input- placeholder="Stay informed about our api and website health."- {...field}- />- </FormControl>- <FormDescription>- Provide your users informations about it.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="slug"- render={({ field }) => (- <FormItem className="sm:col-span-3">- <FormLabel>Slug</FormLabel>- <FormControl>- <InputWithAddons- placeholder="documenso"- trailing={".openstatus.dev"}- {...field}- />- </FormControl>- <FormDescription>- The subdomain for your status page. At least 3 chars.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="icon"- render={({ field }) => (- <FormItem className="sm:col-span-3">- <FormLabel>Favicon</FormLabel>- <FormControl>- <>- {!field.value && (- <Input- type="file"- accept="image/x-icon,image/png"- ref={inputFileRef}- onChange={(e) => handleChange(e.target.files)}+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">Endpoint Check</p>+ <p className="text-muted-foreground text-sm">+ The easiest way to get started.+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2">+ <FormField+ control={form.control}+ name="title"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Title</FormLabel>+ <FormControl>+ <Input placeholder="Documenso Status" {...field} />+ </FormControl>+ <FormDescription>The title of your page.</FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="slug"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Slug</FormLabel>+ <FormControl>+ <InputWithAddons+ placeholder="documenso"+ trailing={".openstatus.dev"}+ {...field}/>- )}- {field.value && (- <div className="flex items-center">- <div className="border-border h-10 w-10 rounded-sm border p-1">- <Image- src={field.value}- width={64}- height={64}- alt="Favicon"- />- </div>- <Button- variant="link"- onClick={() => {- form.setValue("icon", "");- }}- >- Remove- </Button>- </div>- )}- </>- </FormControl>- <FormDescription>Your status page favicon</FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="monitors"- render={() => (- <FormItem className="sm:col-span-full">- <div className="mb-4">- <FormLabel className="text-base">Monitor</FormLabel>- <FormDescription>- Select the monitors you want to display.- </FormDescription>- </div>- {allMonitors?.map((item) => (- <FormField- key={item.id}- control={form.control}- name="monitors"- render={({ field }) => {- return (- <FormItem- key={item.id}- className="flex flex-row items-start space-x-3 space-y-0"- >+ </FormControl>+ <FormDescription>+ The subdomain for your status page. At least 3 chars.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="monitors"+ render={() => (+ <FormItem>+ <div className="mb-4">+ <FormLabel className="text-base">Monitor</FormLabel>+ <FormDescription>+ Select the monitors you want to display.+ </FormDescription>+ </div>+ {allMonitors?.map((item) => (+ <FormField+ key={item.id}+ control={form.control}+ name="monitors"+ render={({ field }) => {+ return (+ <FormItem+ key={item.id}+ className="flex flex-row items-start space-x-3 space-y-0"+ >+ <FormControl>+ <Checkbox+ 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,+ ),+ );+ }}+ />+ </FormControl>+ <div className="space-y-1 leading-none">+ <FormLabel className="font-normal">+ {item.name}+ </FormLabel>+ <FormDescription className="truncate">+ {item.url}+ </FormDescription>+ </div>+ </FormItem>+ );+ }}+ />+ ))}+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </div>+ <Accordion type="single" collapsible>+ <AccordionItem value="advanced-settings">+ <AccordionTrigger>Advanced Settings</AccordionTrigger>+ <AccordionContent>+ <div className="grid gap-4 sm:grid-cols-3">+ <div className="my-1.5 flex flex-col gap-2">+ <p className="text-sm font-semibold leading-none">+ More Configurations+ </p>+ <p className="text-muted-foreground text-sm">+ Make it your own. Contact us if you wish for more and we+ will implement it!+ </p>+ </div>+ <div className="grid gap-6 sm:col-span-2 sm:grid-cols-2">+ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem className="sm:col-span-full">+ <FormLabel>Description</FormLabel><FormControl>- <Checkbox- 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,- ),- );- }}+ <Input+ placeholder="Stay informed about our api and website health."+ {...field}/></FormControl>- <div className="space-y-1 leading-none">- <FormLabel className="font-normal">- {item.name}- </FormLabel>- <FormDescription>{item.url}</FormDescription>- </div>+ <FormDescription>+ Provide your users informations about it.+ </FormDescription>+ <FormMessage /></FormItem>- );- }}- />- ))}- <FormMessage />- </FormItem>- )}- />- <div className="sm:col-span-full">+ )}+ />+ <FormField+ control={form.control}+ name="icon"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Favicon</FormLabel>+ <FormControl>+ <>+ {!field.value && (+ <Input+ type="file"+ accept="image/x-icon,image/png"+ ref={inputFileRef}+ onChange={(e) => handleChange(e.target.files)}+ />+ )}+ {field.value && (+ <div className="flex items-center">+ <div className="border-border h-10 w-10 rounded-sm border p-1">+ <Image+ src={field.value}+ width={64}+ height={64}+ alt="Favicon"+ />+ </div>+ <Button+ variant="link"+ onClick={() => {+ form.setValue("icon", "");+ }}+ >+ Remove+ </Button>+ </div>+ )}+ </>+ </FormControl>+ <FormDescription>+ Your status page favicon+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ <div className="flex sm:justify-end"><Button className="w-full sm:w-auto" size="lg">{!isPending ? "Confirm" : <LoadingAnimation />}</Button>diff --git a/apps/web/src/components/modals/notification-dialog.tsx b/apps/web/src/components/modals/notification-dialog.tsxnew file mode 100644index 000000000..4aff971e5--- /dev/null+++ b/apps/web/src/components/modals/notification-dialog.tsx@@ -0,0 +1,44 @@+"use client";++import { useState } from "react";++import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@openstatus/ui";++import { NotificationForm } from "@/components/forms/notification-form";++export const NotificationDialog = ({+ workspaceSlug,+}: {+ workspaceSlug: string;+}) => {+ const [open, setOpen] = useState(false);+ return (+ <Dialog open={open} onOpenChange={(val) => setOpen(val)}>+ <DialogTrigger asChild>+ <Button variant="default" size="sm">+ Add Notifications+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle>Add Notification</DialogTitle>+ <DialogDescription>+ Get alerted when your endpoint is down.+ </DialogDescription>+ </DialogHeader>+ <NotificationForm+ onSubmit={() => setOpen(false)}+ {...{ workspaceSlug }}+ />+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/web/src/config/pages.ts b/apps/web/src/config/pages.tsindex 45699dadd..a01d7a514 100644--- a/apps/web/src/config/pages.ts+++ b/apps/web/src/config/pages.ts@@ -22,6 +22,12 @@ export const pagesConfig: Page[] = [href: "/status-pages",icon: "panel-top",},+ {+ title: "Notifications",+ description: "Where you can see all the notifications.",+ href: "/notifications",+ icon: "bell",+ },{title: "Incidents",description: "War room where you handle the incidents.",diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.tsindex 4da56f544..f8e9129c5 100644--- a/packages/api/src/edge.ts+++ b/packages/api/src/edge.ts@@ -2,7 +2,9 @@ import { domainRouter } from "./router/domain";import { incidentRouter } from "./router/incident";import { integrationRouter } from "./router/integration";import { monitorRouter } from "./router/monitor";+import { notificationRouter } from "./router/notification";import { pageRouter } from "./router/page";+import { userRouter } from "./router/user";import { workspaceRouter } from "./router/workspace";import { createTRPCRouter } from "./trpc";@@ -14,4 +16,6 @@ export const edgeRouter = createTRPCRouter({incident: incidentRouter,domain: domainRouter,integration: integrationRouter,+ user: userRouter,+ notification: notificationRouter,});diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.tsindex df760d7ba..eabf8e1ad 100644--- a/packages/api/src/router/monitor.ts+++ b/packages/api/src/router/monitor.ts@@ -2,15 +2,18 @@ import { TRPCError } from "@trpc/server";import { z } from "zod";import { analytics, trackAnalytics } from "@openstatus/analytics";-import { and, eq, sql } from "@openstatus/db";+import { and, eq, inArray, sql } from "@openstatus/db";import {allMonitorsExtendedSchema,insertMonitorSchema,METHODS,monitor,monitorsToPages,+ notification,+ notificationsToMonitors,periodicityEnum,selectMonitorExtendedSchema,+ selectNotificationSchema,} from "@openstatus/db/src/schema";import { allPlans } from "@openstatus/plans";@@ -56,7 +59,7 @@ export const monitorRouter = createTRPCRouter({});}// FIXME: this is a hotfix- const { regions, headers, ...data } = opts.input.data;+ const { regions, headers, notifications, ...data } = opts.input.data;const newMonitor = await opts.ctx.db.insert(monitor)@@ -69,6 +72,17 @@ export const monitorRouter = createTRPCRouter({.returning().get();+ if (notifications && notifications.length > 0) {+ const allNotifications = await opts.ctx.db.query.notification.findMany({+ where: inArray(notification.id, notifications),+ });+ const values = allNotifications.map((notification) => ({+ monitorId: newMonitor.id,+ notificationId: notification.id,+ }));+ await opts.ctx.db.insert(notificationsToMonitors).values(values).run();+ }+// TODO: check, do we have to await for the two calls? Will slow down user response for our analyticsawait analytics.identify(result.user.id, {userId: result.user.id,@@ -94,33 +108,9 @@ export const monitorRouter = createTRPCRouter({if (!result) return;const _monitor = selectMonitorExtendedSchema.parse(result.monitor);- _monitor.headers;return _monitor;}),- // TODO: delete- updateMonitorDescription: protectedProcedure- .input(- z.object({- id: z.number(),- description: z.string(),- }),- )- .mutation(async (opts) => {- // We make sure user as access to this workspace and the monitor- if (!opts.input.id) return;- const result = await hasUserAccessToMonitor({- monitorId: opts.input.id,- ctx: opts.ctx,- });- if (!result) return;-- await opts.ctx.db- .update(monitor)- .set({ description: opts.input.description })- .where(eq(monitor.id, opts.input.id))- .run();- }),updateMonitor: protectedProcedure.input(insertMonitorSchema).mutation(async (opts) => {@@ -145,8 +135,8 @@ export const monitorRouter = createTRPCRouter({message: "You reached your cron job limits.",});}- const { regions, headers, ...data } = opts.input;- await opts.ctx.db+ const { regions, headers, notifications, ...data } = opts.input;+ const currentMonitor = await opts.ctx.db.update(monitor).set({...data,@@ -157,30 +147,49 @@ export const monitorRouter = createTRPCRouter({.where(eq(monitor.id, opts.input.id)).returning().get();- }),- // TODO: delete- updateMonitorPeriodicity: protectedProcedure- .input(- z.object({- id: z.number(),- data: insertMonitorSchema.pick({ periodicity: true }),- }),- )- .mutation(async (opts) => {- const result = await hasUserAccessToMonitor({- monitorId: opts.input.id,- ctx: opts.ctx,- });- if (!result) return;- await opts.ctx.db- .update(monitor)- .set({- periodicity: opts.input.data.periodicity,- updatedAt: new Date(),- })- .where(eq(monitor.id, opts.input.id))- .run();+ // TODO: optimize!+ const currentMonitorNotifications = await opts.ctx.db+ .select()+ .from(notificationsToMonitors)+ .where(eq(notificationsToMonitors.monitorId, currentMonitor.id))+ .all();++ const currentMonitorNotificationsIds = currentMonitorNotifications.map(+ ({ notificationId }) => notificationId,+ );++ const removedNotifications = currentMonitorNotificationsIds.filter(+ (x) => !notifications?.includes(x),+ );++ const addedNotifications = notifications?.filter(+ (x) => !currentMonitorNotificationsIds?.includes(x),+ );++ if (addedNotifications && addedNotifications.length > 0) {+ const values = addedNotifications.map((notificationId) => ({+ monitorId: currentMonitor.id,+ notificationId,+ }));++ await opts.ctx.db.insert(notificationsToMonitors).values(values).run();+ }++ if (removedNotifications && removedNotifications.length > 0) {+ await opts.ctx.db+ .delete(notificationsToMonitors)+ .where(+ and(+ eq(notificationsToMonitors.monitorId, currentMonitor.id),+ inArray(+ notificationsToMonitors.notificationId,+ removedNotifications,+ ),+ ),+ )+ .run();+ }}),deleteMonitor: protectedProcedure@@ -196,6 +205,7 @@ export const monitorRouter = createTRPCRouter({.where(eq(monitor.id, result.monitor.id)).run();}),+getMonitorsByWorkspace: protectedProcedure.input(z.object({ workspaceSlug: z.string() })).query(async (opts) => {@@ -290,4 +300,28 @@ export const monitorRouter = createTRPCRouter({if (monitors.length === 0) return 0;return monitors[0].count;}),++ // TODO: return the notifications inside of the `getMonitorByID` like we do for the monitors on a status page+ getAllNotificationsForMonitor: protectedProcedure+ .input(z.object({ id: z.number() }))+ // .output(selectMonitorSchema)+ .query(async (opts) => {+ if (!opts.input.id) return;+ const result = await hasUserAccessToMonitor({+ monitorId: opts.input.id,+ ctx: opts.ctx,+ });+ if (!result) return null;++ const data = await opts.ctx.db+ .select()+ .from(notificationsToMonitors)+ .innerJoin(+ notification,+ eq(notificationsToMonitors.notificationId, notification.id),+ )+ .where(eq(notificationsToMonitors.monitorId, opts.input.id))+ .all();+ return data.map((d) => selectNotificationSchema.parse(d.notification));+ }),});diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.tsnew file mode 100644index 000000000..91cfb87b3--- /dev/null+++ b/packages/api/src/router/notification.ts@@ -0,0 +1,118 @@+import { z } from "zod";++import { and, eq } from "@openstatus/db";+import {+ allNotifications,+ insertNotificationSchema,+ notification,+ notificationsToMonitors,+ selectNotificationSchema,+} from "@openstatus/db/src/schema";++import { createTRPCRouter, protectedProcedure } from "../trpc";+import { hasUserAccessToNotification, hasUserAccessToWorkspace } from "./utils";++export const notificationRouter = createTRPCRouter({+ createNotification: protectedProcedure+ .input(+ insertNotificationSchema.extend({+ workspaceSlug: z.string(),+ }),+ )+ .mutation(async (opts) => {+ const { workspaceSlug, ...data } = opts.input;++ const result = await hasUserAccessToWorkspace({+ workspaceSlug,+ ctx: opts.ctx,+ });+ if (!result) return;++ const _notification = await opts.ctx.db+ .insert(notification)+ .values({ ...data, workspaceId: result.workspace.id })+ .returning()+ .get();++ return _notification;+ }),++ updateNotification: protectedProcedure+ .input(insertNotificationSchema)+ .mutation(async (opts) => {+ if (!opts.input.id) return;+ const result = await hasUserAccessToNotification({+ notificationId: opts.input.id,+ ctx: opts.ctx,+ });+ if (!result) return;++ const { ...data } = opts.input;+ return await opts.ctx.db+ .update(notification)+ .set({ ...data, updatedAt: new Date() })+ .where(eq(notification.id, opts.input.id))+ .returning()+ .get();+ }),++ deleteNotification: protectedProcedure+ .input(z.object({ id: z.number() }))+ .mutation(async (opts) => {+ console.log({ id: opts.input.id });+ const result = await hasUserAccessToNotification({+ notificationId: opts.input.id,+ ctx: opts.ctx,+ });+ if (!result) return;++ await opts.ctx.db+ .delete(notification)+ .where(eq(notification.id, result.notification.id))+ .run();+ }),++ getNotificationById: protectedProcedure+ .input(z.object({ id: z.number() }))+ .query(async (opts) => {+ // if (!opts.input.id) return;+ // const result = await hasUserAccessToMonitor({+ // monitorId: opts.input.id,+ // ctx: opts.ctx,+ // });+ // if (!result) return;++ const _notification = await opts.ctx.db+ .select()+ .from(notification)+ .where(eq(notification.id, opts.input.id))+ .get();++ return selectNotificationSchema.parse(_notification);+ }),++ getNotificationsByWorkspace: protectedProcedure+ .input(z.object({ workspaceSlug: z.string() }))+ .query(async (opts) => {+ // Check if user has access to workspace+ const data = await hasUserAccessToWorkspace({+ workspaceSlug: opts.input.workspaceSlug,+ ctx: opts.ctx,+ });++ if (!data) return;++ const notifications = await opts.ctx.db+ .select()+ .from(notification)+ .where(eq(notification.workspaceId, data.workspace.id))+ .all();++ try {+ return allNotifications.parse(notifications);+ } catch (e) {+ console.log(e);+ }+ return;+ }),+});diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.tsindex 9e37a0777..111e9b233 100644--- a/packages/api/src/router/page.ts+++ b/packages/api/src/router/page.ts@@ -56,6 +56,7 @@ export const pageRouter = createTRPCRouter({.values({ workspaceId: data.workspace.id, ...pageInput }).returning().get();+if (monitors && monitors.length > 0) {// We should make sure the user has access to the monitorsconst allMonitors = await opts.ctx.db.query.monitor.findMany({diff --git a/packages/api/src/router/user.ts b/packages/api/src/router/user.tsnew file mode 100644index 000000000..d9ddc871f--- /dev/null+++ b/packages/api/src/router/user.ts@@ -0,0 +1,15 @@+import { eq } from "@openstatus/db";+import { user } from "@openstatus/db/src/schema";++import { createTRPCRouter, protectedProcedure } from "../trpc";++export const userRouter = createTRPCRouter({+ getCurrentUser: protectedProcedure.query(async (opts) => {+ const currentUser = await opts.ctx.db+ .select()+ .from(user)+ .where(eq(user.tenantId, opts.ctx.auth.userId))+ .get();+ return currentUser;+ }),+});diff --git a/packages/api/src/router/utils.ts b/packages/api/src/router/utils.tsindex 67f7d1e26..a8a9863f5 100644--- a/packages/api/src/router/utils.ts+++ b/packages/api/src/router/utils.ts@@ -1,6 +1,7 @@import { eq } from "@openstatus/db";import {monitor,+ notification,user,usersToWorkspaces,workspace,@@ -97,3 +98,47 @@ export const hasUserAccessToMonitor = async ({monitor: currentMonitor,};};++export const hasUserAccessToNotification = async ({+ notificationId,+ ctx,+}: {+ notificationId: number;+ ctx: Context;+}) => {+ if (!ctx.auth?.userId) return;++ const currentNotification = await ctx.db+ .select()+ .from(notification)+ .where(eq(notification.id, notificationId))+ .get();+ if (!currentNotification || !currentNotification.workspaceId) return;++ // TODO: we should use hasUserAccess and pass `workspaceId` instead of `workspaceSlug`+ const currentUser = ctx.db+ .select()+ .from(user)+ .where(eq(user.tenantId, ctx.auth.userId))+ .as("currentUser");++ const result = await ctx.db+ .select()+ .from(usersToWorkspaces)+ .where(eq(usersToWorkspaces.workspaceId, currentNotification.workspaceId))+ .innerJoin(currentUser, eq(usersToWorkspaces.userId, currentUser.id))+ .get();++ if (!result || !result.users_to_workspaces) return;++ const currentWorkspace = await ctx.db.query.workspace.findFirst({+ where: eq(workspace.id, result.users_to_workspaces.workspaceId),+ });++ if (!currentWorkspace) return;+ return {+ workspace: currentWorkspace,+ user: result.currentUser,+ notification: currentNotification,+ };+};diff --git a/packages/db/drizzle/0008_overjoyed_sunset_bain.sql b/packages/db/drizzle/0008_overjoyed_sunset_bain.sqlnew file mode 100644index 000000000..fd0bc1e21--- /dev/null+++ b/packages/db/drizzle/0008_overjoyed_sunset_bain.sql@@ -0,0 +1,22 @@+CREATE TABLE `notification` (+ `id` integer PRIMARY KEY NOT NULL,+ `name` text NOT NULL,+ `provider` text NOT NULL,+ `data` text DEFAULT '{}',+ `workspace_id` integer,+ `created_at` integer DEFAULT (strftime('%s', 'now')),+ `updated_at` integer DEFAULT (strftime('%s', 'now')),+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE no action+);+--> statement-breakpoint+CREATE TABLE `notifications_to_monitors` (+ `monitor_id` integer NOT NULL,+ `notification_id` integer NOT NULL,+ PRIMARY KEY(`monitor_id`, `notification_id`),+ FOREIGN KEY (`monitor_id`) REFERENCES `monitor`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`notification_id`) REFERENCES `notification`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+ALTER TABLE `monitor` DROP COLUMN `status`;+--> statement-breakpoint+ALTER TABLE `monitor` ADD COLUMN `status` text(2) DEFAULT 'active' NOT NULL;diff --git a/packages/db/drizzle/meta/0008_snapshot.json b/packages/db/drizzle/meta/0008_snapshot.jsonnew file mode 100644index 000000000..3c1309b44--- /dev/null+++ b/packages/db/drizzle/meta/0008_snapshot.json@@ -0,0 +1,959 @@+{+ "version": "5",+ "dialect": "sqlite",+ "id": "72f58965-4d96-43e5-9101-3ceb67dac648",+ "prevId": "23bfc90d-3bb1-4077-81d8-8f2e874f9c62",+ "tables": {+ "incident": {+ "name": "incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text(4)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "incident_workspace_id_workspace_id_fk": {+ "name": "incident_workspace_id_workspace_id_fk",+ "tableFrom": "incident",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "incident_update": {+ "name": "incident_update",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text(4)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "incident_id": {+ "name": "incident_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "incident_update_incident_id_incident_id_fk": {+ "name": "incident_update_incident_id_incident_id_fk",+ "tableFrom": "incident_update",+ "tableTo": "incident",+ "columnsFrom": [+ "incident_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "incidents_to_monitors": {+ "name": "incidents_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "incident_id": {+ "name": "incident_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "incidents_to_monitors_monitor_id_monitor_id_fk": {+ "name": "incidents_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "incidents_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "incidents_to_monitors_incident_id_incident_id_fk": {+ "name": "incidents_to_monitors_incident_id_incident_id_fk",+ "tableFrom": "incidents_to_monitors",+ "tableTo": "incident",+ "columnsFrom": [+ "incident_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "incidents_to_monitors_monitor_id_incident_id_pk": {+ "columns": [+ "incident_id",+ "monitor_id"+ ]+ }+ },+ "uniqueConstraints": {}+ },+ "integration": {+ "name": "integration",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "credential": {+ "name": "credential",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "integration_workspace_id_workspace_id_fk": {+ "name": "integration_workspace_id_workspace_id_fk",+ "tableFrom": "integration",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "page": {+ "name": "page",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "icon": {+ "name": "icon",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "slug": {+ "name": "slug",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "custom_domain": {+ "name": "custom_domain",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "published": {+ "name": "published",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_slug_unique": {+ "name": "page_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_workspace_id_workspace_id_fk": {+ "name": "page_workspace_id_workspace_id_fk",+ "tableFrom": "page",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "monitor": {+ "name": "monitor",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text(3)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "periodicity": {+ "name": "periodicity",+ "type": "text(6)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "status": {+ "name": "status",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "active": {+ "name": "active",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(512)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_workspace_id_workspace_id_fk": {+ "name": "monitor_workspace_id_workspace_id_fk",+ "tableFrom": "monitor",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "monitors_to_pages": {+ "name": "monitors_to_pages",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitors_to_pages_monitor_id_monitor_id_fk": {+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitors_to_pages_page_id_page_id_fk": {+ "name": "monitors_to_pages_page_id_page_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitors_to_pages_monitor_id_page_id_pk": {+ "columns": [+ "monitor_id",+ "page_id"+ ]+ }+ },+ "uniqueConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "last_name": {+ "name": "last_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "user_tenant_id_unique": {+ "name": "user_tenant_id_unique",+ "columns": [+ "tenant_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "users_to_workspaces": {+ "name": "users_to_workspaces",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "users_to_workspaces_user_id_user_id_fk": {+ "name": "users_to_workspaces_user_id_user_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "users_to_workspaces_workspace_id_workspace_id_fk": {+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_to_workspaces_user_id_workspace_id_pk": {+ "columns": [+ "user_id",+ "workspace_id"+ ]+ }+ },+ "uniqueConstraints": {}+ },+ "workspace": {+ "name": "workspace",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripe_id": {+ "name": "stripe_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "text(2)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_until": {+ "name": "paid_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "workspace_stripe_id_unique": {+ "name": "workspace_stripe_id_unique",+ "columns": [+ "stripe_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "notification": {+ "name": "notification",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'{}'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notification_workspace_id_workspace_id_fk": {+ "name": "notification_workspace_id_workspace_id_fk",+ "tableFrom": "notification",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {}+ },+ "notifications_to_monitors": {+ "name": "notifications_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notificationId": {+ "name": "notificationId",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notifications_to_monitors_monitor_id_monitor_id_fk": {+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "notifications_to_monitors_notificationId_notification_id_fk": {+ "name": "notifications_to_monitors_notificationId_notification_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "notification",+ "columnsFrom": [+ "notificationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "notifications_to_monitors_monitor_id_notificationId_pk": {+ "columns": [+ "monitor_id",+ "notificationId"+ ]+ }+ },+ "uniqueConstraints": {}+ }+ },+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex c514a6eed..249dd03d3 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -57,6 +57,13 @@"when": 1694362217174,"tag": "0007_complex_frog_thor","breakpoints": true+ },+ {+ "idx": 8,+ "version": "5",+ "when": 1695756345957,+ "tag": "0008_overjoyed_sunset_bain",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex ba9e25d4c..353af0fd4 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -5,3 +5,4 @@ export * from "./monitor";export * from "./user";export * from "./workspace";export * from "./shared";+export * from "./notification";diff --git a/packages/db/src/schema/monitor.ts b/packages/db/src/schema/monitor.tsindex d90b15ccf..52fc10e53 100644--- a/packages/db/src/schema/monitor.ts+++ b/packages/db/src/schema/monitor.ts@@ -9,6 +9,7 @@ import { createInsertSchema, createSelectSchema } from "drizzle-zod";import { z } from "zod";import { monitorsToIncidents } from "./incident";+import { notificationsToMonitors } from "./notification";import { page } from "./page";import { workspace } from "./workspace";@@ -36,7 +37,8 @@ export const availableRegions = [export const periodicity = ["1m", "5m", "10m", "30m", "1h", "other"] as const;export const METHODS = ["GET", "POST"] as const;-+export const status = ["active", "error"] as const;+export const statusSchema = z.enum(status);export const RegionEnum = z.enum(availableRegions);export const monitor = sqliteTable("monitor", {@@ -47,7 +49,7 @@ export const monitor = sqliteTable("monitor", {periodicity: text("periodicity", ["1m", "5m", "10m", "30m", "1h", "other"]).default("other").notNull(),- status: text("status", ["active", "inactive"]).default("inactive").notNull(),+ status: text("status", status).default("active").notNull(),active: integer("active", { mode: "boolean" }).default(false),regions: text("regions").default("").notNull(),@@ -77,6 +79,7 @@ export const monitorRelation = relations(monitor, ({ one, many }) => ({fields: [monitor.workspaceId],references: [workspace.id],}),+ monitorsToNotifications: many(notificationsToMonitors),}));export const monitorsToPages = sqliteTable(@@ -113,7 +116,7 @@ export const periodicityEnum = z.enum(periodicity);export const insertMonitorSchema = createInsertSchema(monitor, {periodicity: periodicityEnum,url: z.string().url(),- status: z.enum(["active", "inactive"]).default("inactive"),+ status: z.enum(status).default("active"),active: z.boolean().default(false),regions: z.array(RegionEnum).default([]).optional(),method: z.enum(METHODS).default("GET"),@@ -121,12 +124,16 @@ export const insertMonitorSchema = createInsertSchema(monitor, {headers: z.array(z.object({ key: z.string(), value: z.string() })).default([]),+}).extend({+ notifications: z.array(z.number()).optional(),});+export const basicMonitorSchema = createSelectSchema(monitor);+// Schema for selecting a Monitor - can be used to validate API responsesexport const selectMonitorSchema = createSelectSchema(monitor, {periodicity: periodicityEnum,- status: z.enum(["active", "inactive"]).default("inactive"),+ status: z.enum(status).default("active"),jobType: z.enum(["website", "cron", "other"]).default("other"),active: z.boolean().default(false),regions: zdiff --git a/packages/db/src/schema/notification.ts b/packages/db/src/schema/notification.tsnew file mode 100644index 000000000..75bef345b--- /dev/null+++ b/packages/db/src/schema/notification.ts@@ -0,0 +1,90 @@+import { relations, sql } from "drizzle-orm";+import {+ integer,+ primaryKey,+ sqliteTable,+ text,+} from "drizzle-orm/sqlite-core";+import { createInsertSchema, createSelectSchema } from "drizzle-zod";+import * as z from "zod";++import { monitor } from "./monitor";+import { workspace } from "./workspace";++export const providerName = ["email", "discord", "slack"] as const;++export const notification = sqliteTable("notification", {+ id: integer("id").primaryKey(),+ name: text("name").notNull(),+ provider: text("provider", { enum: providerName }).notNull(),+ data: text("data").default("{}"),+ workspaceId: integer("workspace_id").references(() => workspace.id),+ createdAt: integer("created_at", { mode: "timestamp" }).default(+ sql`(strftime('%s', 'now'))`,+ ),+ updatedAt: integer("updated_at", { mode: "timestamp" }).default(+ sql`(strftime('%s', 'now'))`,+ ),+});++export const notificationsToMonitors = sqliteTable(+ "notifications_to_monitors",+ {+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => monitor.id, { onDelete: "cascade" }),+ notificationId: integer("notification_id")+ .notNull()+ .references(() => notification.id, { onDelete: "cascade" }),+ },+ (t) => ({+ pk: primaryKey(t.monitorId, t.notificationId),+ }),+);++export const notificationsToMonitorsRelation = relations(+ notificationsToMonitors,+ ({ one }) => ({+ monitor: one(monitor, {+ fields: [notificationsToMonitors.monitorId],+ references: [monitor.id],+ }),+ notification: one(notification, {+ fields: [notificationsToMonitors.notificationId],+ references: [notification.id],+ }),+ }),+);++export const notificationRelations = relations(+ notification,+ ({ one, many }) => ({+ workspace: one(workspace, {+ fields: [notification.workspaceId],+ references: [workspace.id],+ }),+ monitor: many(notificationsToMonitors),+ }),+);++export const providerEnum = z.enum(providerName);++export const selectNotificationSchema = createSelectSchema(notification).extend(+ {+ data: z+ .preprocess((val) => {+ return String(val);+ }, z.string())+ .default(""),+ },+);++export const insertNotificationSchema = createInsertSchema(notification).extend(+ {+ data: z.string().default("").optional(),+ },+);++export const allNotifications = z.array(selectNotificationSchema);++export type Notification = z.infer<typeof selectNotificationSchema>;diff --git a/packages/emails/emails/alert.tsx b/packages/emails/emails/alert.tsxnew file mode 100644index 000000000..16c631bd5--- /dev/null+++ b/packages/emails/emails/alert.tsx@@ -0,0 +1,69 @@+"use client";++import {+ Body,+ Button,+ Column,+ Container,+ Head,+ Heading,+ Html,+ Preview,+ Row,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";+import { z } from "zod";++export const EmailDataSchema = z.object({+ monitorName: z.string(),+ monitorUrl: z.string().url(),+ recipientName: z.string(),+});++const Alert = ({ data }: { data: z.infer<typeof EmailDataSchema> }) => {+ return (+ <Html>+ <Head>+ <title>New incident detected 🚨</title>+ <Preview>New incident detected : {data.monitorName} 🚨</Preview>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-[40px] w-[465px] rounded border border-solid border-[#eaeaea] p-[20px]">+ <Heading className="mx-0 my-[30px] p-0 text-center text-[24px] font-normal text-black">+ New incident detected!+ </Heading>+ <Text className="text-[14px] leading-[24px] text-black">+ Hello {data.recipientName}, <br />+ We have detected a new incident.+ </Text>++ <Section className="my-[30px] rounded border border-solid border-gray-200 bg-gray-100 p-2">+ <Row>+ <Column className="text-lg">Monitor</Column>+ <Column>{data.monitorName}</Column>+ </Row>+ <Row className="mt-2">+ <Column className="text-lg">URL</Column>+ <Column>{data.monitorUrl}</Column>+ </Row>+ </Section>++ <Section className="mb-[32px] mt-[32px] text-center">+ <Button+ pX={20}+ pY={12}+ className="rounded bg-[#000000] text-center text-[14px] font-semibold text-white no-underline"+ href="https://www.openstatus.dev/app"+ >+ See incident+ </Button>+ </Section>+ </Container>+ </Body>+ </Head>+ </Html>+ );+};++export { Alert };diff --git a/packages/emails/index.ts b/packages/emails/index.tsindex a20d0ca1b..d14fe453a 100644--- a/packages/emails/index.ts+++ b/packages/emails/index.ts@@ -1,14 +1,21 @@import type { ReactElement } from "react";import { Resend } from "resend";+import { Alert, EmailDataSchema } from "./emails/alert";import { validateEmailNotDisposable } from "./emails/utils/utils";import WaitingList from "./emails/waiting-list";import WelcomeEmail from "./emails/welcome";import { env } from "./env";-export { WelcomeEmail, WaitingList, validateEmailNotDisposable };+export {+ WelcomeEmail,+ WaitingList,+ validateEmailNotDisposable,+ Alert,+ EmailDataSchema,+};-const resend = new Resend(env.RESEND_API_KEY);+export const resend = new Resend(env.RESEND_API_KEY);export interface Emails {react: ReactElement;diff --git a/packages/emails/package.json b/packages/emails/package.jsonindex c9be41c41..324218ba9 100644--- a/packages/emails/package.json+++ b/packages/emails/package.json@@ -17,7 +17,7 @@"@react-email/tailwind": "0.0.8","@t3-oss/env-core": "0.6.0","react-email": "1.9.4",- "resend": "0.15.3",+ "resend": "1.1.0","zod": "3.21.4"},"devDependencies": {diff --git a/packages/notifications/email/.env.example b/packages/notifications/email/.env.examplenew file mode 100644index 000000000..517a1e598--- /dev/null+++ b/packages/notifications/email/.env.example@@ -0,0 +1 @@+RESEND_API_KEY=1diff --git a/packages/notifications/email/README.md b/packages/notifications/email/README.mdnew file mode 100644index 000000000..792d60054--- /dev/null+++ b/packages/notifications/email/README.md@@ -0,0 +1 @@+#diff --git a/packages/notifications/email/env.ts b/packages/notifications/email/env.tsnew file mode 100644index 000000000..1af0229b2--- /dev/null+++ b/packages/notifications/email/env.ts@@ -0,0 +1,11 @@+import { createEnv } from "@t3-oss/env-core";+import { z } from "zod";++export const env = createEnv({+ server: {+ RESEND_API_KEY: z.string().min(1),+ },+ runtimeEnv: {+ RESEND_API_KEY: process.env.RESEND_API_KEY,+ },+});diff --git a/packages/notifications/email/package.json b/packages/notifications/email/package.jsonnew file mode 100644index 000000000..832553ade--- /dev/null+++ b/packages/notifications/email/package.json@@ -0,0 +1,24 @@+{+ "name": "@openstatus/notification-emails",+ "version": "0.0.0",+ "main": "src/index.ts",+ "description": "Log drains Vercel integration.",+ "dependencies": {+ "@openstatus/db": "workspace:^",+ "@openstatus/emails": "workspace:^",+ "@openstatus/tinybird": "workspace:*",+ "@react-email/components": "0.0.7",+ "@react-email/render": "^0.0.7",+ "@t3-oss/env-core": "0.6.0",+ "resend": "1.1.0",+ "zod": "3.21.4"+ },+ "devDependencies": {+ "@openstatus/tsconfig": "workspace:*",+ "@types/node": "20.3.1",+ "@types/react": "18.2.12",+ "@types/react-dom": "18.2.5",+ "next": "13.4.12",+ "typescript": "5.1.6"+ }+}diff --git a/packages/notifications/email/src/index.ts b/packages/notifications/email/src/index.tsnew file mode 100644index 000000000..f9761dd69--- /dev/null+++ b/packages/notifications/email/src/index.ts@@ -0,0 +1,41 @@+import type { z } from "zod";++import type {+ basicMonitorSchema,+ selectNotificationSchema,+} from "@openstatus/db/src/schema";++import { env } from "../env";+import { EmailConfigurationSchema } from "./schema/config";++export const send = async ({+ monitor,+ notification,+}: {+ monitor: z.infer<typeof basicMonitorSchema>;+ notification: z.infer<typeof selectNotificationSchema>;+}) => {+ const config = EmailConfigurationSchema.parse(notification.data);+ const { email } = config;++ const res = await fetch("https://api.resend.com/emails", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${env.RESEND_API_KEY}`,+ },+ body: JSON.stringify({+ to: email,+ from: "Notifications <[email protected]>",++ subject: `Your monitor ${monitor.name} is down 🚨`,+ html: `Hey, <br/> Your monitor ${monitor.name} is down. <br/> <br/> OpenStatus`,+ }),+ });++ if (res.ok) {+ const data = await res.json();+ console.log(data);+ // return NextResponse.json(data);+ }+};diff --git a/packages/notifications/email/src/schema/config.ts b/packages/notifications/email/src/schema/config.tsnew file mode 100644index 000000000..07914f852--- /dev/null+++ b/packages/notifications/email/src/schema/config.ts@@ -0,0 +1,5 @@+import { z } from "zod";++export const EmailConfigurationSchema = z.object({+ email: z.string().email(),+});diff --git a/packages/notifications/email/tsconfig.json b/packages/notifications/email/tsconfig.jsonnew file mode 100644index 000000000..a8a8c9309--- /dev/null+++ b/packages/notifications/email/tsconfig.json@@ -0,0 +1,4 @@+{+ "extends": "@openstatus/tsconfig/nextjs.json",+ "include": ["src", "*.ts"]+}diff --git a/packages/ui/src/components/date-time-picker.tsx b/packages/ui/src/components/date-time-picker.tsxindex c430b6338..80d71b3b1 100644--- a/packages/ui/src/components/date-time-picker.tsx+++ b/packages/ui/src/components/date-time-picker.tsx@@ -16,9 +16,14 @@ import { cn } from "../lib/utils";interface DateTimePickerProps {date: Date;setDate: (date: Date) => void;+ className?: string;}-export function DateTimePicker({ date, setDate }: DateTimePickerProps) {+export function DateTimePicker({+ date,+ setDate,+ className,+}: DateTimePickerProps) {const [selectedDateTime, setSelectedDateTime] = React.useState<DateTime>(DateTime.fromJSDate(date),);@@ -52,6 +57,7 @@ export function DateTimePicker({ date, setDate }: DateTimePickerProps) {className={cn("w-[280px] justify-start text-left font-normal",!date && "text-muted-foreground",+ className,)}suppressHydrationWarning // because timestamp is not same, server and client>diff --git a/packages/ui/src/components/multi-select.tsx b/packages/ui/src/components/multi-select.tsxnew file mode 100644index 000000000..abf2587c0--- /dev/null+++ b/packages/ui/src/components/multi-select.tsx@@ -0,0 +1,130 @@+"use client";++import * as React from "react";+import { Command as CommandPrimitive } from "cmdk";+import { X } from "lucide-react";++import { Badge } from "./badge";+import { Command, CommandGroup, CommandItem } from "./command";++type Option = Record<"value" | "label", string | number>;++export interface MultiSelectProps {+ options?: Option[];+ onChange?: (values: Option[]) => void;+ placeholder?: string;+}++export const MultiSelect = ({+ onChange,+ options = [],+ ...props+}: MultiSelectProps) => {+ const inputRef = React.useRef<HTMLInputElement>(null);+ const [open, setOpen] = React.useState(false);+ const [selected, setSelected] = React.useState<Option[]>([]);+ const [inputValue, setInputValue] = React.useState("");++ const handleUnselect = React.useCallback((option: Option) => {+ setSelected((prev) => prev.filter((s) => s.value !== option.value));+ }, []);++ const handleKeyDown = React.useCallback(+ (e: React.KeyboardEvent<HTMLDivElement>) => {+ const input = inputRef.current;+ if (input) {+ if (e.key === "Delete" || e.key === "Backspace") {+ if (input.value === "") {+ setSelected((prev) => {+ const newSelected = [...prev];+ newSelected.pop();+ return newSelected;+ });+ }+ }+ // This is not a default behaviour of the <input /> field+ if (e.key === "Escape") {+ input.blur();+ }+ }+ },+ [],+ );++ const selectables = options.filter((option) => !selected.includes(option));++ React.useEffect(() => {+ onChange?.(selected);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selected]);++ return (+ <Command+ onKeyDown={handleKeyDown}+ className="overflow-visible bg-transparent"+ >+ <div className="border-input ring-offset-background focus-within:ring-ring group rounded-md border px-3 py-2 text-sm focus-within:ring-2 focus-within:ring-offset-2">+ <div className="flex flex-wrap gap-1">+ {selected.map((option) => {+ return (+ <Badge key={option.value} variant="secondary">+ {option.label}+ <button+ className="ring-offset-background focus:ring-ring ml-1 rounded-full outline-none focus:ring-2 focus:ring-offset-2"+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleUnselect(option);+ }+ }}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ onClick={() => handleUnselect(option)}+ >+ <X className="text-muted-foreground hover:text-foreground h-3 w-3" />+ </button>+ </Badge>+ );+ })}+ {/* Avoid having the "Search" Icon */}+ <CommandPrimitive.Input+ ref={inputRef}+ value={inputValue}+ onValueChange={setInputValue}+ onBlur={() => setOpen(false)}+ onFocus={() => setOpen(true)}+ className="placeholder:text-muted-foreground ml-2 flex-1 bg-transparent outline-none"+ {...props}+ />+ </div>+ </div>+ <div className="relative mt-2">+ {open && selectables.length > 0 ? (+ <div className="bg-popover text-popover-foreground animate-in absolute top-0 z-10 w-full rounded-md border shadow-md outline-none">+ <CommandGroup className="h-full overflow-auto">+ {selectables.map((option) => {+ return (+ <CommandItem+ key={option.value}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ onSelect={(value) => {+ setInputValue("");+ setSelected((prev) => [...prev, option]);+ }}+ className={"cursor-pointer"}+ >+ {option.label}+ </CommandItem>+ );+ })}+ </CommandGroup>+ </div>+ ) : null}+ </div>+ </Command>+ );+};diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsxindex e93dad342..3939ff1c4 100644--- a/packages/ui/src/index.tsx+++ b/packages/ui/src/index.tsx@@ -1,168 +1,37 @@-export {- Accordion,- AccordionItem,- AccordionTrigger,- AccordionContent,-} from "./components/accordion";-export { Avatar, AvatarImage, AvatarFallback } from "./components/avatar";-export {- AlertDialog,- AlertDialogTrigger,- AlertDialogContent,- AlertDialogHeader,- AlertDialogFooter,- AlertDialogTitle,- AlertDialogDescription,- AlertDialogAction,- AlertDialogCancel,-} from "./components/alert-dialog";-export { Alert, AlertTitle, AlertDescription } from "./components/alert";-export { Badge, badgeVariants } from "./components/badge";-export { ButtonWithDisableTooltip } from "./components/button-with-disable-tooltip";-export { Button, buttonVariants } from "./components/button";-export { Calendar } from "./components/calendar";-export {- Card,- CardHeader,- CardFooter,- CardTitle,- CardDescription,- CardContent,-} from "./components/card";-export { Checkbox } from "./components/checkbox";-export {- Command,- CommandDialog,- CommandInput,- CommandList,- CommandEmpty,- CommandGroup,- CommandItem,- CommandShortcut,- CommandSeparator,-} from "./components/command";--export {- ContextMenu,- ContextMenuTrigger,- ContextMenuContent,- ContextMenuItem,- ContextMenuCheckboxItem,- ContextMenuRadioItem,- ContextMenuLabel,- ContextMenuSeparator,- ContextMenuShortcut,- ContextMenuGroup,- ContextMenuPortal,- ContextMenuSub,- ContextMenuSubContent,- ContextMenuSubTrigger,- ContextMenuRadioGroup,-} from "./components/context-menu";--export { DatePicker } from "./components/date-picker";-export {- Dialog,- DialogTrigger,- DialogContent,- DialogHeader,- DialogFooter,- DialogTitle,- DialogDescription,-} from "./components/dialog";-export {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuCheckboxItem,- DropdownMenuRadioItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuShortcut,- DropdownMenuGroup,- DropdownMenuPortal,- DropdownMenuSub,- DropdownMenuSubContent,- DropdownMenuSubTrigger,- DropdownMenuRadioGroup,-} from "./components/dropdown-menu";--export {- useFormField,- Form,- FormItem,- FormLabel,- FormControl,- FormDescription,- FormMessage,- FormField,-} from "./components/form";-export {- HoverCard,- HoverCardTrigger,- HoverCardContent,-} from "./components/hover-card";-export { InputWithAddons } from "./components/input-with-addons";-export { Input } from "./components/input";-export { Label } from "./components/label";-export { Popover, PopoverTrigger, PopoverContent } from "./components/popover";-export { RadioGroup, RadioGroupItem } from "./components/radio-group";-export {- Select,- SelectGroup,- SelectValue,- SelectTrigger,- SelectContent,- SelectLabel,- SelectItem,- SelectSeparator,-} from "./components/select";-export { Separator } from "./components/separator";-export { Skeleton } from "./components/skeleton";-export { Switch } from "./components/switch";-export {- Table,- TableHeader,- TableBody,- TableFooter,- TableHead,- TableRow,- TableCell,- TableCaption,-} from "./components/table";--export { Textarea } from "./components/textarea";-export {- type ToastProps,- type ToastActionElement,- ToastProvider,- ToastViewport,- Toast,- ToastTitle,- ToastDescription,- ToastClose,- ToastAction,-} from "./components/toast";-export { Toaster } from "./components/toaster";-export { toast, useToast } from "./components/use-toast";-export {- Tooltip,- TooltipTrigger,- TooltipContent,- TooltipProvider,-} from "./components/tooltip";-export { Tabs, TabsList, TabsTrigger, TabsContent } from "./components/tabs";-export { DateTimePicker } from "./components/date-time-picker";-export {- Sheet,- SheetTrigger,- SheetClose,- SheetContent,- SheetHeader,- SheetFooter,- SheetTitle,- SheetDescription,-} from "./components/sheet";--export type { ToastType } from "./components/use-toast";+export * from "./components/accordion";+export * from "./components/avatar";+export * from "./components/alert-dialog";+export * from "./components/alert";+export * from "./components/badge";+export * from "./components/button-with-disable-tooltip";+export * from "./components/button";+export * from "./components/calendar";+export * from "./components/card";+export * from "./components/checkbox";+export * from "./components/command";+export * from "./components/context-menu";+export * from "./components/date-picker";+export * from "./components/dialog";+export * from "./components/dropdown-menu";+export * from "./components/form";+export * from "./components/hover-card";+export * from "./components/input-with-addons";+export * from "./components/input";+export * from "./components/label";+export * from "./components/popover";+export * from "./components/radio-group";+export * from "./components/select";+export * from "./components/separator";+export * from "./components/skeleton";+export * from "./components/switch";+export * from "./components/table";+export * from "./components/textarea";+export * from "./components/toast";+export * from "./components/toaster";+export * from "./components/use-toast";+export * from "./components/tooltip";+export * from "./components/tabs";+export * from "./components/date-time-picker";+export * from "./components/sheet";+export * from "./components/use-toast";+export * from "./components/multi-select";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 017e25499..ef777a216 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -115,6 +115,9 @@ importers:'@openstatus/emails':specifier: workspace:*version: link:../../packages/emails+ '@openstatus/notification-emails':+ specifier: workspace:*+ version: link:../../packages/notifications/email'@openstatus/plans':specifier: workspace:*version: link:../../packages/plans@@ -242,8 +245,8 @@ importers:specifier: 10.1.0version: 10.1.0resend:- specifier: 0.15.3- version: 0.15.3+ specifier: 1.1.0+ version: 1.1.0shiki:specifier: 0.14.3version: 0.14.3@@ -487,8 +490,8 @@ importers:specifier: 1.9.4version: 1.9.4resend:- specifier: 0.15.3- version: 0.15.3+ specifier: 1.1.0+ version: 1.1.0zod:specifier: 3.21.4version: 3.21.4@@ -546,6 +549,52 @@ importers:specifier: 5.1.6version: 5.1.6+ packages/notifications/email:+ dependencies:+ '@openstatus/db':+ specifier: workspace:^+ version: link:../../db+ '@openstatus/emails':+ specifier: workspace:^+ version: link:../../emails+ '@openstatus/tinybird':+ specifier: workspace:*+ version: link:../../tinybird+ '@react-email/components':+ specifier: 0.0.7+ version: 0.0.7+ '@react-email/render':+ specifier: ^0.0.7+ version: 0.0.7+ '@t3-oss/env-core':+ specifier: 0.6.0+ version: 0.6.0([email protected])([email protected])+ resend:+ specifier: 1.1.0+ version: 1.1.0+ zod:+ specifier: 3.21.4+ version: 3.21.4+ devDependencies:+ '@openstatus/tsconfig':+ specifier: workspace:*+ version: link:../../tsconfig+ '@types/node':+ specifier: 20.3.1+ version: 20.3.1+ '@types/react':+ specifier: 18.2.12+ version: 18.2.12+ '@types/react-dom':+ specifier: 18.2.5+ version: 18.2.5+ next:+ specifier: 13.4.12+ typescript:+ specifier: 5.1.6+ version: 5.1.6+packages/plans:dependencies:'@openstatus/db':@@ -5423,7 +5472,7 @@ packages:/@types/[email protected]:resolution: {integrity: sha512-sRQsOS/sCLnpQhR4DSKGTtWFE3FZjpQa86KPVbhUqdYMRZ9FEFcfAytKhR/vUG2rH1oFbOOej6cuD7MFSobDRQ==}dependencies:- '@types/react': 18.2.21+ '@types/react': 18.2.12dev: true/@types/[email protected]:@@ -5438,14 +5487,6 @@ packages:'@types/scheduler': 0.16.3csstype: 3.1.2- /@types/[email protected]:- resolution: {integrity: sha512-neFKG/sBAwGxHgXiIxnbm3/AAVQ/cMRS93hvBpg8xYRbeQSPVABp9U2bRnPf0iI4+Ucdv3plSxKK+3CW2ENJxA==}- dependencies:- '@types/prop-types': 15.7.6- '@types/scheduler': 0.16.3- csstype: 3.1.2- dev: true-/@types/[email protected]:resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}dev: false@@ -6072,16 +6113,6 @@ packages:engines: {node: '>=4'}dev: false- resolution: {integrity: sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==}- dependencies:- follow-redirects: 1.15.2- form-data: 4.0.0- proxy-from-env: 1.1.0- transitivePeerDependencies:- - debug- dev: false-resolution: {integrity: sha512-D4DdjDo5CY50Qms0qGQTTw6Q44jl7zRwY7bthds06pUGfChBCTcQs+N743eFWGEd6pRTMd6A+I87aWyFV5wiZQ==}dependencies:@@ -12889,13 +12920,12 @@ packages:resolution: {integrity: sha512-ab9EmR80F/zQTMNeneUr4cv+jSwPJgIlvEmVwLerwrWVbpLlBuls9XHzIeTFy4cegU2NHBp3va0LKOzU5qFEYQ==}dev: false- resolution: {integrity: sha512-dzXHBaOjOS3ufBGjqiJjMe7LnproEn/jiAyBjg6IBtp56MCfih0O4IS4JeBcfj3y2Afm+tZITfoZAylKWLEJOg==}+ resolution: {integrity: sha512-it8TIDVT+/gAiJsUlv2tdHuvzwCCv4Zwu+udDqIm/dIuByQwe68TtFDcPccxqpSVVrNCBxxXLzsdT1tsV+P3GA==}+ engines: {node: '>=18'}dependencies:'@react-email/render': 0.0.7- axios: 1.4.0- transitivePeerDependencies:- - debug+ type-fest: 3.13.0dev: false@@ -14180,6 +14210,11 @@ packages:engines: {node: '>=12.20'}dev: false+ resolution: {integrity: sha512-Gur3yQGM9qiLNs0KPP7LPgeRbio2QTt4xXouobMCarR0/wyW3F+F/+OWwshg3NG0Adon7uQfSZBpB46NfhoF1A==}+ engines: {node: '>=14.16'}+ dev: false+resolution: {integrity: sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==}engines: {node: '>=14.16'}