Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: add data table to subscribers including accept and delete action (#684)
Maximilian Kaske3a5f7087518a
diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/loading.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/loading.tsxindex b269200de..ae51d6a5b 100644--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/loading.tsx+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/loading.tsx@@ -1,5 +1,5 @@-import { SkeletonForm } from "@/components/forms/skeleton-form";+import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton";export default function Loading() {- return <SkeletonForm />;+ return <DataTableSkeleton />;}diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/page.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/page.tsxindex cc5d52a15..b17e54c63 100644--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/page.tsx+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/status-pages/[id]/subscribers/page.tsx@@ -3,6 +3,8 @@ import { notFound } from "next/navigation";import { allPlans } from "@openstatus/plans";import { ProFeatureAlert } from "@/components/billing/pro-feature-alert";+import { columns } from "@/components/data-table/page-subscriber/columns";+import { DataTable } from "@/components/data-table/page-subscriber/data-table";import { api } from "@/trpc/server";export default async function CustomDomainPage({@@ -14,17 +16,14 @@ export default async function CustomDomainPage({const page = await api.page.getPageById.query({ id });const workspace = await api.workspace.getWorkspace.query();- const isValid = allPlans[workspace.plan].limits["status-subscribers"];-if (!page) return notFound();+ const isValid = allPlans[workspace.plan].limits["status-subscribers"];if (!isValid) return <ProFeatureAlert feature={"Status page subscribers"} />;- // TODO: add page-subscribers trpc endpoint first- return (- <p className="text-muted-foreground text-sm">- Your users can subscribe to status report updates. A list with more- detailed informations coming soon.- </p>- );+ const data = await api.pageSubscriber.getPageSubscribersByPageId.query({+ id,+ });++ return <DataTable data={data} columns={columns} />;}diff --git a/apps/web/src/components/data-table/incident/columns.tsx b/apps/web/src/components/data-table/incident/columns.tsxindex 8d73d9367..f866b83a9 100644--- a/apps/web/src/components/data-table/incident/columns.tsx+++ b/apps/web/src/components/data-table/incident/columns.tsx@@ -5,6 +5,7 @@ import type { ColumnDef } from "@tanstack/react-table";import type { Incident } from "@openstatus/db/src/schema";+import { formatDateTime } from "@/lib/utils";import { DataTableRowActions } from "./data-table-row-actions";export const columns: ColumnDef<Incident>[] = [@@ -29,7 +30,7 @@ export const columns: ColumnDef<Incident>[] = [header: "Started At",cell: ({ row }) => {const { startedAt } = row.original;- const date = startedAt ? new Date(startedAt).toLocaleString() : "-";+ const date = startedAt ? formatDateTime(startedAt) : "-";return (<div className="flex"><span className="text-muted-foreground max-w-[150px] truncate sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">@@ -44,9 +45,7 @@ export const columns: ColumnDef<Incident>[] = [header: "Acknowledged At",cell: ({ row }) => {const { acknowledgedAt } = row.original;- const date = acknowledgedAt- ? new Date(acknowledgedAt).toLocaleString()- : "-";+ const date = acknowledgedAt ? formatDateTime(acknowledgedAt) : "-";return (<div className="flex"><span className="text-muted-foreground max-w-[150px] truncate sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">@@ -61,7 +60,7 @@ export const columns: ColumnDef<Incident>[] = [header: "Resolved At",cell: ({ row }) => {const { resolvedAt } = row.original;- const date = resolvedAt ? new Date(resolvedAt).toLocaleString() : "-";+ const date = resolvedAt ? formatDateTime(resolvedAt) : "-";return (<div className="flex"><span className="text-muted-foreground max-w-[150px] truncate sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">diff --git a/apps/web/src/components/data-table/page-subscriber/columns.tsx b/apps/web/src/components/data-table/page-subscriber/columns.tsxnew file mode 100644index 000000000..87da02862--- /dev/null+++ b/apps/web/src/components/data-table/page-subscriber/columns.tsx@@ -0,0 +1,46 @@+"use client";++import type { ColumnDef } from "@tanstack/react-table";++import type { PageSubscriber } from "@openstatus/db/src/schema";++import { formatDateTime } from "@/lib/utils";+import { DataTableRowActions } from "./data-table-row-actions";++export const columns: ColumnDef<PageSubscriber>[] = [+ {+ accessorKey: "email",+ header: "Email",+ cell: ({ row }) => {+ return <span>{row.getValue("email")}</span>;+ },+ },+ {+ accessorKey: "acceptedAt",+ header: "Accepted",+ cell: ({ row }) => {+ const { acceptedAt } = row.original;+ const date = acceptedAt ? formatDateTime(acceptedAt) : "-";+ return <span className="text-muted-foreground">{date}</span>;+ },+ },+ {+ accessorKey: "createdAt",+ header: "Created",+ cell: ({ row }) => {+ const { createdAt } = row.original;+ const date = createdAt ? formatDateTime(createdAt) : "-";+ return <span className="text-muted-foreground">{date}</span>;+ },+ },+ {+ id: "actions",+ cell: ({ row }) => {+ return (+ <div className="text-right">+ <DataTableRowActions row={row} />+ </div>+ );+ },+ },+];diff --git a/apps/web/src/components/data-table/page-subscriber/data-table-row-actions.tsx b/apps/web/src/components/data-table/page-subscriber/data-table-row-actions.tsxnew file mode 100644index 000000000..0a6a4e528--- /dev/null+++ b/apps/web/src/components/data-table/page-subscriber/data-table-row-actions.tsx@@ -0,0 +1,121 @@+"use client";++import * as React from "react";+import { useRouter } from "next/navigation";+import type { Row } from "@tanstack/react-table";+import { MoreHorizontal } from "lucide-react";++import { selectPageSubscriberSchema } 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 subscriber = selectPageSubscriberSchema.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 () => {+ try {+ if (!subscriber.id) return;+ await api.pageSubscriber.unsubscribeById.mutate({+ id: subscriber.id,+ });+ toast("deleted");+ router.refresh();+ setAlertOpen(false);+ } catch {+ toast("error");+ }+ });+ }++ async function onAccept() {+ startTransition(async () => {+ try {+ if (!subscriber.id) return;+ await api.pageSubscriber.acceptSubscriberById.mutate({+ id: subscriber.id,+ });+ toast("success");+ router.refresh();+ } 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">+ {!subscriber.acceptedAt ? (+ <DropdownMenuItem onClick={onAccept}>Accept</DropdownMenuItem>+ ) : null}+ <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>+ The user will not be able to receive the latest status reports. But+ will be able to subscribe again.+ </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/page-subscriber/data-table.tsx b/apps/web/src/components/data-table/page-subscriber/data-table.tsxnew file mode 100644index 000000000..bbe2814b4--- /dev/null+++ b/apps/web/src/components/data-table/page-subscriber/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/lib/utils.ts b/apps/web/src/lib/utils.tsindex 98f82a904..17036ab58 100644--- a/apps/web/src/lib/utils.ts+++ b/apps/web/src/lib/utils.ts@@ -15,6 +15,10 @@ export function formatDate(date: Date) {return format(date, "LLL dd, y");}+export function formatDateTime(date: Date) {+ return format(date, "LLL dd, y HH:mm:ss");+}+export function notEmpty<TValue>(value: TValue | null | undefined,): value is TValue {diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.tsindex f52cfb1f9..9948496a4 100644--- a/packages/api/src/edge.ts+++ b/packages/api/src/edge.ts@@ -5,6 +5,7 @@ import { invitationRouter } from "./router/invitation";import { monitorRouter } from "./router/monitor";import { notificationRouter } from "./router/notification";import { pageRouter } from "./router/page";+import { pageSubscriberRouter } from "./router/pageSubscriber";import { statusReportRouter } from "./router/statusReport";import { userRouter } from "./router/user";import { workspaceRouter } from "./router/workspace";@@ -22,4 +23,5 @@ export const edgeRouter = createTRPCRouter({notification: notificationRouter,invitation: invitationRouter,incident: incidentRouter,+ pageSubscriber: pageSubscriberRouter,});diff --git a/packages/api/src/router/pageSubscriber.ts b/packages/api/src/router/pageSubscriber.tsnew file mode 100644index 000000000..d370acce1--- /dev/null+++ b/packages/api/src/router/pageSubscriber.ts@@ -0,0 +1,101 @@+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import { and, eq } from "@openstatus/db";+import { page, pageSubscriber } from "@openstatus/db/src/schema";++import { createTRPCRouter, protectedProcedure } from "../trpc";++export const pageSubscriberRouter = createTRPCRouter({+ getPageSubscribersByPageId: protectedProcedure+ .input(z.object({ id: z.number() }))+ .query(async (opts) => {+ const _page = await opts.ctx.db.query.page.findFirst({+ where: and(+ eq(page.workspaceId, opts.ctx.workspace.id),+ eq(page.id, opts.input.id),+ ),+ });++ if (!_page) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Unauthorized to get subscribers",+ });+ }++ const data = await opts.ctx.db.query.pageSubscriber.findMany({+ where: and(eq(pageSubscriber.pageId, _page.id)),+ });+ return data;+ }),++ unsubscribeById: protectedProcedure+ .input(z.object({ id: z.number() }))+ .mutation(async (opts) => {+ const subscriber = await opts.ctx.db.query.pageSubscriber.findFirst({+ where: and(eq(pageSubscriber.id, opts.input.id)),+ });++ if (!subscriber) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Subscriber not found",+ });+ }++ const _page = await opts.ctx.db.query.page.findFirst({+ where: and(+ eq(page.id, subscriber!.pageId),+ eq(page.workspaceId, opts.ctx.workspace.id),+ ),+ });++ if (!_page) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Unauthorized to unsubscribe",+ });+ }++ return await opts.ctx.db+ .delete(pageSubscriber)+ .where(eq(pageSubscriber.id, subscriber.id));+ }),++ acceptSubscriberById: protectedProcedure+ .input(z.object({ id: z.number() }))+ .mutation(async (opts) => {+ const subscriber = await opts.ctx.db.query.pageSubscriber.findFirst({+ where: and(eq(pageSubscriber.id, opts.input.id)),+ });++ if (!subscriber) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Subscriber not found",+ });+ }++ const _page = await opts.ctx.db.query.page.findFirst({+ where: and(+ eq(page.id, subscriber!.pageId),+ eq(page.workspaceId, opts.ctx.workspace.id),+ ),+ });++ if (!_page) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Unauthorized to unsubscribe",+ });+ }++ return await opts.ctx.db+ .update(pageSubscriber)+ .set({+ acceptedAt: new Date(),+ })+ .where(eq(pageSubscriber.id, subscriber.id));+ }),+});