Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: subscriber button (#518)
Maximilian Kaske6f4b11f63d95
diff --git a/apps/web/src/app/status-page/[domain]/_components/actions.ts b/apps/web/src/app/status-page/[domain]/_components/actions.tsnew file mode 100644index 000000000..ead784bb5--- /dev/null+++ b/apps/web/src/app/status-page/[domain]/_components/actions.ts@@ -0,0 +1,79 @@+"use server";++import { z } from "zod";++import { and, eq } from "@openstatus/db";+import { db } from "@openstatus/db/src/db";+import { page, pageSubscriber } from "@openstatus/db/src/schema";+import { sendEmail, SubscribeEmail } from "@openstatus/emails";++import { wait } from "@/lib/utils";++const schema = z.object({+ email: z+ .string({+ invalid_type_error: "Invalid Email",+ })+ .email(),+ slug: z.string(),+});++export async function handleSubscribe(formData: FormData) {+ const validatedFields = schema.safeParse({+ email: formData.get("email"),+ slug: formData.get("slug"),+ });++ if (!validatedFields.success) {+ const fieldErrors = validatedFields.error.flatten().fieldErrors;+ throw new Error(fieldErrors?.email?.[0] || "Invalid form data");+ }++ const pageData = await db+ .select()+ .from(page)+ .where(eq(page.slug, validatedFields.data.slug))+ .get();++ if (!pageData) {+ throw new Error("Page not found");+ }++ const alreadySubscribed = await db+ .select()+ .from(pageSubscriber)+ .where(+ and(+ eq(pageSubscriber.email, validatedFields.data.email),+ eq(pageSubscriber.pageId, pageData.id),+ ),+ )+ .get();++ if (alreadySubscribed) {+ throw new Error("Already subscribed");+ }++ const token = crypto.randomUUID();++ await sendEmail({+ react: SubscribeEmail({+ domain: validatedFields.data.slug,+ token: token,+ page: pageData.title,+ }),+ from: "OpenStatus <[email protected]>",+ to: [validatedFields.data.email],+ subject: "Verify your subscription",+ });++ await db+ .insert(pageSubscriber)+ .values({+ email: validatedFields.data.email,+ token,+ pageId: pageData.id,+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),+ })+ .execute();+}diff --git a/apps/web/src/app/status-page/[domain]/_components/navigation-link.tsx b/apps/web/src/app/status-page/[domain]/_components/navigation-link.tsxindex e04e449c0..90f5010a1 100644--- a/apps/web/src/app/status-page/[domain]/_components/navigation-link.tsx+++ b/apps/web/src/app/status-page/[domain]/_components/navigation-link.tsx@@ -34,6 +34,7 @@ export default function NavigationLink({asChildvariant={isActive ? "secondary" : "ghost"}className={isActive ? "font-bold" : ""}+ size="sm"><Link href={href}>{children}</Link></Button>diff --git a/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsx b/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsxnew file mode 100644index 000000000..f90dae8a7--- /dev/null+++ b/apps/web/src/app/status-page/[domain]/_components/subscribe-button.tsx@@ -0,0 +1,87 @@+"use client";++import { Mail } from "lucide-react";+import { experimental_useFormStatus } from "react-dom";++import {+ Button,+ Input,+ Label,+ Popover,+ PopoverContent,+ PopoverTrigger,+ useToast,+} from "@openstatus/ui";++import { LoadingAnimation } from "@/components/loading-animation";+import { handleSubscribe } from "./actions";++interface Props {+ slug: string;+}++export function SubscribeButton({ slug }: Props) {+ const { toast } = useToast();++ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button size="sm" variant="outline">+ Get updates+ </Button>+ </PopoverTrigger>+ <PopoverContent>+ <div className="grid gap-4">+ <div className="space-y-2">+ <h4 className="flex items-center font-medium leading-none">+ <Mail className="mr-2 h-4 w-4" /> Subscribe to updates+ </h4>+ <p className="text-muted-foreground text-sm">+ Get email notifications whenever a report has been created or+ resolved.+ </p>+ </div>+ <form+ className="grid gap-2"+ action={async (formData) => {+ try {+ await handleSubscribe(formData);+ toast({+ title: "Success",+ description: "Please confirm your email.",+ });+ } catch (e) {+ if (e instanceof Error) {+ toast({+ title: "Something went wrong",+ description: e.message,+ variant: "destructive",+ });+ }+ }+ }}+ >+ <Label htmlFor="email">Email</Label>+ <Input+ id="email"+ name="email"+ type="email"+ placeholder="[email protected]"+ />+ <input type="hidden" name="slug" value={slug} />+ <SubmitButton />+ </form>+ </div>+ </PopoverContent>+ </Popover>+ );+}++function SubmitButton() {+ const { pending } = experimental_useFormStatus();+ return (+ <Button type="submit" disabled={pending}>+ {pending ? <LoadingAnimation /> : "Subscribe"}+ </Button>+ );+}diff --git a/apps/web/src/app/status-page/[domain]/layout.tsx b/apps/web/src/app/status-page/[domain]/layout.tsxindex e6dff43d5..ab5ac0057 100644--- a/apps/web/src/app/status-page/[domain]/layout.tsx+++ b/apps/web/src/app/status-page/[domain]/layout.tsx@@ -1,18 +1,34 @@+import { notFound } from "next/navigation";+import { Shell } from "@/components/dashboard/shell";import { ThemeToggle } from "@/components/theme-toggle";+import { api } from "@/trpc/server";import NavigationLink from "./_components/navigation-link";+import { SubscribeButton } from "./_components/subscribe-button";-export default function StatusPageLayout({- children,-}: {+type Props = {+ params: { domain: string };children: React.ReactNode;-}) {+};++export default async function StatusPageLayout({ children, params }: Props) {+ const page = await api.page.getPageBySlug.query({ slug: params.domain });+ if (!page) return notFound();+return (<div className="flex min-h-screen w-full flex-col space-y-6 p-4 md:p-8"><header className="mx-auto w-full max-w-xl">- <Shell className="mx-auto flex items-center justify-center gap-2 p-2 px-2 md:p-3">- <NavigationLink slug={null}>Status</NavigationLink>- <NavigationLink slug="incidents">Incidents</NavigationLink>+ <Shell className="mx-auto flex items-center justify-between gap-4 p-2 px-2 md:p-3">+ <div className="hidden w-[100px] md:block" />+ <div className="flex items-center gap-2">+ <NavigationLink slug={null}>Status</NavigationLink>+ <NavigationLink slug="incidents">Incidents</NavigationLink>+ </div>+ <div className="w-[100px] text-end">+ {page.workspacePlan !== "free" ? (+ <SubscribeButton slug={params.domain} />+ ) : null}+ </div></Shell></header><main className="flex h-full w-full flex-1 flex-col">diff --git a/apps/web/src/app/status-page/[domain]/page.tsx b/apps/web/src/app/status-page/[domain]/page.tsxindex e96bdb406..7d5244888 100644--- a/apps/web/src/app/status-page/[domain]/page.tsx+++ b/apps/web/src/app/status-page/[domain]/page.tsx@@ -27,14 +27,8 @@ type Props = {};export default async function Page({ params }: Props) {- // We should fetch the monitors and incident here- // also the page information- if (!params.domain) return notFound();const page = await api.page.getPageBySlug.query({ slug: params.domain });- if (!page) {- return notFound();- }-+ if (!page) return notFound();const isEmptyState = !(Boolean(page.monitors.length) || Boolean(page.statusReports.length));diff --git a/apps/web/src/app/status-page/[domain]/subscribe/route.ts b/apps/web/src/app/status-page/[domain]/subscribe/route.tsdeleted file mode 100644index 553879e3d..000000000--- a/apps/web/src/app/status-page/[domain]/subscribe/route.ts+++ /dev/null@@ -1,62 +0,0 @@-import { z } from "zod";--import { and, eq } from "@openstatus/db";-import { db } from "@openstatus/db/src/db";-import { page, pageSubscriber } from "@openstatus/db/src/schema";-import { sendEmail, SubscribeEmail } from "@openstatus/emails";--export async function POST(- req: Request,- { params }: { params: { domain: string } },-) {- //- const data = await req.json();- const result = z.object({ email: z.string().email() }).parse(data);-- const pageData = await db- .select()- .from(page)- .where(eq(page.slug, params.domain))- .get();- if (!pageData) {- return new Response("Not found", { status: 401 });- }-- const alreadySubscribed = await db- .select()- .from(pageSubscriber)- .where(- and(- eq(pageSubscriber.email, data.email),- eq(pageSubscriber.pageId, pageData?.id),- ),- )- .get();-- if (alreadySubscribed) {- return new Response("Not found", { status: 401 });- }-- const token = (Math.random() + 1).toString(36).substring(10);-- await sendEmail({- react: SubscribeEmail({- domain: params.domain,- token: token,- page: pageData.title,- }),- from: "OpenStatus <[email protected]>",- to: [result.email],- subject: "Verify your subscription",- });- await db- .insert(pageSubscriber)- .values({- pageId: pageData.id,- email: result.email,- token,- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),- })- .execute();- return Response.json({ message: "Hello world" });-}diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.tsindex 7c9757ae7..3c3c4e29f 100644--- a/packages/api/src/router/page.ts+++ b/packages/api/src/router/page.ts@@ -11,6 +11,7 @@ import {pagesToStatusReports,selectPublicPageSchemaWithRelation,statusReport,+ workspace,} from "@openstatus/db/src/schema";import { allPlans } from "@openstatus/plans";@@ -164,6 +165,12 @@ export const pageRouter = createTRPCRouter({return;}+ const workspaceResult = await opts.ctx.db+ .select()+ .from(workspace)+ .where(eq(workspace.id, result.workspaceId))+ .get();+// FIXME: There is probably a better way to do thisconst monitorsToPagesResult = await opts.ctx.db.select()@@ -234,6 +241,7 @@ export const pageRouter = createTRPCRouter({...result,monitors,statusReports,+ workspacePlan: workspaceResult?.plan,});}),diff --git a/packages/db/src/schema/shared.ts b/packages/db/src/schema/shared.tsindex fcd7bda9a..1ec16cd3b 100644--- a/packages/db/src/schema/shared.ts+++ b/packages/db/src/schema/shared.ts@@ -6,6 +6,7 @@ import {selectStatusReportSchema,selectStatusReportUpdateSchema,} from "./status_reports";+import { workspacePlanSchema } from "./workspaces";// FIXME: delete this file!@@ -33,6 +34,7 @@ export const selectPublicPageSchemaWithRelation = selectPageSchema.extend({monitors: z.array(selectPublicMonitorSchema),statusReports: selectStatusReportPageSchema,+ workspacePlan: workspacePlanSchema.default("free"),}).omit({workspaceId: true,