Skip to content

Open-source status page, incident response and uptime monitoring

feat: page-components [dashboard] [Part 3] (#1754)

Maximilian Kaskea4437f9e66d1
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx
index 3f16a2a64..3650a0c21 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx
@@ -3,7 +3,14 @@
import { NavBreadcrumb } from "@/components/nav/nav-breadcrumb";
import { useTRPC } from "@/lib/trpc/client";
import { useQuery } from "@tanstack/react-query";
-import { Cog, Hammer, Megaphone, PanelTop, Users } from "lucide-react";
+import {
+ Cog,
+ Hammer,
+ LayoutTemplate,
+ Megaphone,
+ PanelTop,
+ Users,
+} from "lucide-react";
import { useParams } from "next/navigation";
export function Breadcrumb() {
@@ -35,6 +42,7 @@ export function Breadcrumb() {
},
{ value: "maintenances", label: "Maintenances", icon: Hammer },
{ value: "subscribers", label: "Subscribers", icon: Users },
+ { value: "components", label: "Components", icon: LayoutTemplate },
{ value: "edit", label: "Settings", icon: Cog },
],
},
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsx
new file mode 100644
index 000000000..31746935a
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/layout.tsx
@@ -0,0 +1,35 @@
+import { SidebarProvider } from "@/components/ui/sidebar";
+import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";
+import { Sidebar } from "../sidebar";
+
+export default async function Layout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ const queryClient = getQueryClient();
+
+ await Promise.all([
+ queryClient.prefetchQuery(
+ trpc.page.get.queryOptions({ id: Number.parseInt(id) }),
+ ),
+ queryClient.prefetchQuery(trpc.monitor.list.queryOptions()),
+ queryClient.prefetchQuery(
+ trpc.pageComponent.list.queryOptions({ pageId: Number.parseInt(id) }),
+ ),
+ ]);
+
+ return (
+ <HydrateClient>
+ <SidebarProvider defaultOpen={false}>
+ <div className="w-full flex-1">{children}</div>
+ <div className="hidden lg:block">
+ <Sidebar />
+ </div>
+ </SidebarProvider>
+ </HydrateClient>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/page.tsx
new file mode 100644
index 000000000..66782cd8e
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/components/page.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import {
+ Section,
+ SectionDescription,
+ SectionGroup,
+ SectionHeader,
+ SectionTitle,
+} from "@/components/content/section";
+import { FormComponentsUpdate } from "@/components/forms/components/update";
+import { useTRPC } from "@/lib/trpc/client";
+import { useQuery } from "@tanstack/react-query";
+import { useParams } from "next/navigation";
+
+export default function Page() {
+ const { id } = useParams<{ id: string }>();
+ const trpc = useTRPC();
+ const { data: statusPage } = useQuery(
+ trpc.page.get.queryOptions({ id: Number.parseInt(id) }),
+ );
+
+ if (!statusPage) return null;
+
+ return (
+ <SectionGroup>
+ <Section>
+ <SectionHeader>
+ <SectionTitle>{statusPage.title}</SectionTitle>
+ <SectionDescription>
+ Configure your page components.
+ </SectionDescription>
+ </SectionHeader>
+ <FormComponentsUpdate />
+ </Section>
+ </SectionGroup>
+ );
+}
diff --git a/apps/dashboard/src/components/data-table/page-components/columns.tsx b/apps/dashboard/src/components/data-table/page-components/columns.tsx
new file mode 100644
index 000000000..ccc6fbfaf
--- /dev/null
+++ b/apps/dashboard/src/components/data-table/page-components/columns.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import { DataTableColumnHeader } from "@/components/ui/data-table/data-table-column-header";
+import type { RouterOutputs } from "@openstatus/api";
+import type { ColumnDef } from "@tanstack/react-table";
+import { DataTableRowActions } from "./data-table-row-actions";
+
+type PageComponent = RouterOutputs["pageComponent"]["list"][number];
+
+export const columns: ColumnDef<PageComponent>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ enableSorting: false,
+ enableHiding: false,
+ },
+ {
+ accessorKey: "description",
+ header: "Description",
+ enableSorting: false,
+ cell: ({ row }) => {
+ const value = row.getValue("description");
+ return (
+ <span className="max-w-[200px] truncate text-muted-foreground">
+ {value ? String(value) : "-"}
+ </span>
+ );
+ },
+ },
+ {
+ accessorKey: "type",
+ header: ({ column }) => (
+ <DataTableColumnHeader column={column} title="Type" />
+ ),
+ cell: ({ row }) => {
+ const value = row.getValue("type");
+ return <span className="capitalize">{String(value)}</span>;
+ },
+ },
+ {
+ accessorKey: "order",
+ header: ({ column }) => (
+ <DataTableColumnHeader column={column} title="Order" />
+ ),
+ cell: ({ row }) => {
+ const value = row.getValue("order");
+ return <span>{value != null ? String(value) : "-"}</span>;
+ },
+ },
+ {
+ id: "actions",
+ cell: ({ row }) => <DataTableRowActions row={row} />,
+ meta: {
+ cellClassName: "w-8",
+ },
+ },
+];
diff --git a/apps/dashboard/src/components/data-table/page-components/data-table-row-actions.tsx b/apps/dashboard/src/components/data-table/page-components/data-table-row-actions.tsx
new file mode 100644
index 000000000..e1e794fbf
--- /dev/null
+++ b/apps/dashboard/src/components/data-table/page-components/data-table-row-actions.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import { QuickActions } from "@/components/dropdowns/quick-actions";
+import { getActions } from "@/data/page-components.client";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@openstatus/api";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { Row } from "@tanstack/react-table";
+
+type PageComponent = RouterOutputs["pageComponent"]["list"][number];
+
+interface DataTableRowActionsProps {
+ row: Row<PageComponent>;
+}
+
+export function DataTableRowActions({ row }: DataTableRowActionsProps) {
+ const trpc = useTRPC();
+ const actions = getActions({});
+ const queryClient = useQueryClient();
+
+ const deletePageComponentMutation = useMutation(
+ trpc.pageComponent.delete.mutationOptions({
+ onSuccess: () => {
+ queryClient.refetchQueries({
+ queryKey: trpc.pageComponent.list.queryKey({
+ pageId: row.original.pageId ?? undefined,
+ }),
+ });
+ },
+ }),
+ );
+
+ return (
+ <QuickActions
+ actions={actions}
+ deleteAction={{
+ confirmationValue: row.original.name ?? "component",
+ submitAction: async () => {
+ await deletePageComponentMutation.mutateAsync({
+ id: row.original.id,
+ });
+ },
+ }}
+ />
+ );
+}
diff --git a/apps/dashboard/src/components/forms/components/form-components.tsx b/apps/dashboard/src/components/forms/components/form-components.tsx
new file mode 100644
index 000000000..a146351d5
--- /dev/null
+++ b/apps/dashboard/src/components/forms/components/form-components.tsx
@@ -0,0 +1,1175 @@
+"use client";
+
+import { Link } from "@/components/common/link";
+import {
+ EmptyStateContainer,
+ EmptyStateTitle,
+} from "@/components/content/empty-state";
+import {
+ FormCard,
+ FormCardContent,
+ FormCardDescription,
+ FormCardFooter,
+ FormCardFooterInfo,
+ FormCardHeader,
+ FormCardSeparator,
+ FormCardTitle,
+} from "@/components/forms/form-card";
+import { STATUS } from "@/components/nav/nav-monitors";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Sortable,
+ SortableContent,
+ SortableItem,
+ SortableItemHandle,
+ SortableOverlay,
+} from "@/components/ui/sortable";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import type { UniqueIdentifier } from "@dnd-kit/core";
+import { zodResolver } from "@hookform/resolvers/zod";
+import type { RouterOutputs } from "@openstatus/api";
+import { isTRPCClientError } from "@trpc/client";
+import {
+ Check,
+ Eye,
+ EyeOff,
+ GripVertical,
+ Link2,
+ Link2Off,
+ Plus,
+ Trash2,
+} from "lucide-react";
+import { useCallback, useEffect, useState, useTransition } from "react";
+import { type UseFormReturn, useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+type PageComponent = RouterOutputs["pageComponent"]["list"][number];
+type Monitor = RouterOutputs["monitor"]["list"][number];
+
+type ComponentGroup = {
+ id: number;
+ name: string;
+ components: PageComponent[];
+};
+
+const componentSchema = z.object({
+ id: z.number(),
+ monitorId: z.number().nullish(),
+ order: z.number(),
+ name: z.string().min(1, { message: "Name is required" }),
+ description: z.string().optional(),
+ type: z.enum(["monitor", "external"]),
+});
+
+const schema = z.object({
+ components: z.array(componentSchema),
+ groups: z.array(
+ z.object({
+ id: z.number(),
+ order: z.number(),
+ name: z.string(),
+ components: z.array(componentSchema).min(1, {
+ message: "At least one component is required",
+ }),
+ }),
+ ),
+});
+
+const getSortedComponents = (
+ components: PageComponent[],
+ componentData: {
+ id: number;
+ order: number;
+ name?: string;
+ type?: "monitor" | "external";
+ monitorId?: number | null;
+ }[],
+ monitors: Monitor[],
+) => {
+ const orderMap = new Map(componentData?.map((c) => [c.id, c.order]) ?? []);
+
+ // Create a map of existing components
+ const componentMap = new Map(components.map((c) => [c.id, c]));
+
+ // Create a map of monitors for lookup
+ const monitorMap = new Map(monitors.map((m) => [m.id, m]));
+
+ // Create synthetic components for any in componentData that don't exist in components
+ componentData.forEach((c) => {
+ if (!componentMap.has(c.id)) {
+ // Look up monitor data if this is a monitor component
+ const monitor = c.monitorId ? monitorMap.get(c.monitorId) : null;
+
+ // Create synthetic PageComponent
+ componentMap.set(c.id, {
+ id: c.id,
+ name: c.name ?? "",
+ type: c.type ?? "external",
+ monitorId: c.monitorId ?? null,
+ monitor: monitor ?? null,
+ groupId: null,
+ groupOrder: null,
+ order: c.order,
+ } as PageComponent);
+ }
+ });
+
+ return Array.from(componentMap.values())
+ .filter((component) => orderMap.has(component.id))
+ .sort((a, b) => {
+ const aOrder = orderMap.get(a.id) ?? 0;
+ const bOrder = orderMap.get(b.id) ?? 0;
+ return aOrder - bOrder;
+ });
+};
+
+const getSortedItems = (
+ components: PageComponent[],
+ componentData: {
+ id: number;
+ order: number;
+ name?: string;
+ type?: "monitor" | "external";
+ monitorId?: number | null;
+ }[],
+ groups: Array<{
+ id: number;
+ order: number;
+ name: string;
+ components: Array<{
+ id: number;
+ order: number;
+ name?: string;
+ type?: "monitor" | "external";
+ monitorId?: number | null;
+ }>;
+ }>,
+ monitors: Monitor[],
+): (PageComponent | ComponentGroup)[] => {
+ // Create map of component orders
+ const componentOrderMap = new Map(componentData.map((c) => [c.id, c.order]));
+
+ // Create a map of existing components
+ const componentMap = new Map(components.map((c) => [c.id, c]));
+
+ // Create a map of monitors for lookup
+ const monitorMap = new Map(monitors.map((m) => [m.id, m]));
+
+ // Create synthetic components for any in componentData that don't exist in components
+ componentData.forEach((c) => {
+ if (!componentMap.has(c.id)) {
+ // Look up monitor data if this is a monitor component
+ const monitor = c.monitorId ? monitorMap.get(c.monitorId) : null;
+
+ // Create synthetic PageComponent
+ componentMap.set(c.id, {
+ id: c.id,
+ name: c.name ?? "",
+ type: c.type ?? "external",
+ monitorId: c.monitorId ?? null,
+ monitor: monitor ?? null,
+ groupId: null,
+ groupOrder: null,
+ order: c.order,
+ } as PageComponent);
+ }
+ });
+
+ // Get all enhanced components (including synthetic ones)
+ const enhancedComponents = Array.from(componentMap.values());
+
+ // Create array of components with their orders
+ const componentsWithOrder = enhancedComponents
+ .filter((component) => componentOrderMap.has(component.id))
+ .map((component) => ({
+ item: component,
+ order: componentOrderMap.get(component.id) ?? 0,
+ }));
+
+ // Create array of groups with their orders
+ const groupsWithOrder = groups.map((group) => ({
+ item: {
+ id: group.id,
+ name: group.name,
+ components: getSortedComponents(
+ enhancedComponents,
+ group.components,
+ monitors,
+ ),
+ } as ComponentGroup,
+ order: group.order,
+ }));
+
+ // Combine and sort by order
+ return [...componentsWithOrder, ...groupsWithOrder]
+ .sort((a, b) => a.order - b.order)
+ .map((entry) => entry.item);
+};
+
+type FormValues = z.infer<typeof schema>;
+
+export function FormComponents({
+ defaultValues,
+ onSubmit,
+ pageComponents,
+ allPageComponents,
+ monitors,
+ legacy,
+ ...props
+}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
+ defaultValues?: FormValues;
+ /** Page components available for selection (standalone, not in groups) */
+ pageComponents: PageComponent[];
+ /** All page components for the page (including those in groups) */
+ allPageComponents: PageComponent[];
+ /** Monitors available for selection */
+ monitors: Monitor[];
+ /**
+ * Whether the status page is legacy or new
+ */
+ legacy: boolean;
+ onSubmit: (values: FormValues) => Promise<void>;
+}) {
+ const form = useForm<FormValues>({
+ resolver: zodResolver(schema),
+ defaultValues: defaultValues ?? { components: [], groups: [] },
+ });
+ const [isPending, startTransition] = useTransition();
+ const watchComponents = form.watch("components");
+ const watchGroups = form.watch("groups");
+ const [data, setData] = useState<(PageComponent | ComponentGroup)[]>(
+ getSortedItems(
+ allPageComponents,
+ defaultValues?.components ?? [],
+ defaultValues?.groups ?? [],
+ monitors,
+ ),
+ );
+
+ // Get all monitor IDs that are already used (in standalone components or groups)
+ const usedMonitorIds = new Set([
+ ...(watchComponents ?? [])
+ .filter((c) => c.monitorId)
+ .map((c) => c.monitorId),
+ ...(watchGroups ?? [])
+ .flatMap((g) => g.components)
+ .filter((c) => c.monitorId)
+ .map((c) => c.monitorId),
+ ]);
+
+ useEffect(() => {
+ const sortedItems = getSortedItems(
+ allPageComponents,
+ watchComponents,
+ watchGroups ?? [],
+ monitors,
+ );
+ setData(sortedItems);
+ }, [watchComponents, watchGroups, allPageComponents, monitors]);
+
+ const onValueChange = useCallback(
+ (newItems: (PageComponent | ComponentGroup)[]) => {
+ setData(newItems);
+
+ // Update components with their position in the overall list
+ const existingComponents = form.getValues("components") ?? [];
+ const components = newItems
+ .map((item, index) => ({ item, index }))
+ .filter(
+ (entry): entry is { item: PageComponent; index: number } =>
+ "type" in entry.item,
+ )
+ .map(({ item, index }) => {
+ const existingComponent = existingComponents.find(
+ (c) => c.id === item.id,
+ );
+ return {
+ id: item.id,
+ monitorId: item.monitorId,
+ order: index,
+ name: existingComponent?.name ?? item.name,
+ description: existingComponent?.description ?? "",
+ type: item.type,
+ };
+ });
+ form.setValue("components", components);
+
+ // Update groups with their position in the overall list
+ const existingGroups = form.getValues("groups") ?? [];
+ const groups = newItems
+ .map((item, index) => ({ item, index }))
+ .filter(
+ (entry): entry is { item: ComponentGroup; index: number } =>
+ "components" in entry.item && !("type" in entry.item),
+ )
+ .map(({ item, index }) => {
+ const existingGroup = existingGroups.find((g) => g.id === item.id);
+ return existingGroup
+ ? {
+ ...existingGroup,
+ order: index,
+ }
+ : {
+ id: item.id,
+ order: index,
+ name: item.name,
+ components: [],
+ };
+ });
+ form.setValue("groups", groups);
+ },
+ [form],
+ );
+
+ const getItemValue = useCallback(
+ (item: PageComponent | ComponentGroup) => item.id,
+ [],
+ );
+
+ const handleAddGroup = useCallback(() => {
+ const newGroupId = Date.now();
+ const existingGroups = form.getValues("groups") ?? [];
+ const existingComponents = form.getValues("components") ?? [];
+ const order = existingGroups.length + existingComponents.length;
+ const newGroups = [
+ ...existingGroups,
+ { id: newGroupId, order, name: "", components: [] },
+ ];
+ form.setValue("groups", newGroups);
+ setData((prev) => [...prev, { id: newGroupId, name: "", components: [] }]);
+ }, [form]);
+
+ const handleDeleteGroup = useCallback(
+ (groupId: number) => {
+ const existingGroups = form.getValues("groups") ?? [];
+ form.setValue(
+ "groups",
+ existingGroups.filter((g) => g.id !== groupId),
+ );
+ setData((prev) => prev.filter((item) => item.id !== groupId));
+ },
+ [form],
+ );
+
+ const handleDeleteComponent = useCallback(
+ (componentId: number) => {
+ const existingComponents = form.getValues("components") ?? [];
+ form.setValue(
+ "components",
+ existingComponents.filter((c) => c.id !== componentId),
+ );
+ setData((prev) => prev.filter((item) => item.id !== componentId));
+ },
+ [form],
+ );
+
+ const renderOverlay = useCallback(
+ ({ value }: { value: UniqueIdentifier }) => {
+ const index = data.findIndex((item) => item.id === value);
+ if (index === -1) return null;
+ const item = data[index];
+
+ if ("type" in item) {
+ return (
+ <ComponentRow
+ component={item}
+ form={form}
+ className="border-transparent border-x px-2"
+ onDelete={handleDeleteComponent}
+ // FIXME: this is used to show an input instead of the name when dragging a component
+ // fieldNamePrefix={`components.${index}`}
+ />
+ );
+ }
+
+ const groups = form.getValues("groups") ?? [];
+ const groupIndex = groups.findIndex((g) => g.id === item.id);
+ return (
+ <ComponentGroupRow
+ group={item}
+ groupIndex={groupIndex}
+ onDeleteGroup={handleDeleteGroup}
+ form={form}
+ allPageComponents={allPageComponents}
+ monitors={monitors}
+ />
+ );
+ },
+ [
+ data,
+ handleDeleteGroup,
+ form,
+ allPageComponents,
+ monitors,
+ handleDeleteComponent,
+ ],
+ );
+
+ function submitAction(values: FormValues) {
+ if (isPending) return;
+
+ startTransition(async () => {
+ try {
+ const promise = onSubmit(values);
+ toast.promise(promise, {
+ loading: "Saving...",
+ success: "Saved",
+ error: (error) => {
+ if (isTRPCClientError(error)) {
+ return error.message;
+ }
+ return "Failed to save";
+ },
+ });
+ await promise;
+ } catch (error) {
+ console.error(error);
+ }
+ });
+ }
+
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(submitAction)} {...props}>
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>Components</FormCardTitle>
+ <FormCardDescription>
+ Manage your page components
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardContent className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
+ <FormField
+ control={form.control}
+ name="components"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel className="sr-only">Components</FormLabel>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" className="w-full">
+ <Plus />
+ Add Component
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-[var(--radix-dropdown-menu-trigger-width)]"
+ >
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ disabled
+ onClick={() => {
+ form.setValue("components", [
+ ...field.value,
+ {
+ id: Date.now(),
+ monitorId: null,
+ order: watchComponents.length,
+ name: "",
+ description: "",
+ type: "external" as const,
+ },
+ ]);
+ }}
+ >
+ <Link2Off className="text-muted-foreground" />
+ Add External (soon)
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0">
+ <Link2 className="text-muted-foreground" />
+ Add Monitor
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="p-0">
+ <Command>
+ <CommandInput
+ placeholder="Search monitors..."
+ className="h-9"
+ />
+ <CommandList>
+ <CommandEmpty>No monitors found.</CommandEmpty>
+ <CommandGroup>
+ {monitors.map((monitor) => {
+ const isUsed = usedMonitorIds.has(
+ monitor.id,
+ );
+ const isSelected = field.value.some(
+ (c) => c.monitorId === monitor.id,
+ );
+ return (
+ <CommandItem
+ value={monitor.name}
+ key={monitor.id}
+ disabled={isUsed}
+ onSelect={() => {
+ if (isSelected) {
+ form.setValue(
+ "components",
+ field.value.filter(
+ (c) =>
+ c.monitorId !== monitor.id,
+ ),
+ );
+ } else {
+ form.setValue("components", [
+ ...field.value,
+ {
+ id: Date.now(),
+ monitorId: monitor.id,
+ order: watchComponents.length,
+ name: monitor.name,
+ description:
+ monitor.description,
+ type: "monitor" as const,
+ },
+ ]);
+ }
+ }}
+ >
+ {monitor.name}
+ <Check
+ className={cn(
+ "ml-auto",
+ isSelected
+ ? "opacity-100"
+ : "opacity-0",
+ )}
+ />
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button
+ variant="outline"
+ type="button"
+ className="w-full"
+ onClick={handleAddGroup}
+ >
+ <Plus />
+ Add Component Group
+ </Button>
+ </FormCardContent>
+ <FormCardSeparator />
+ <FormCardContent>
+ <Sortable
+ value={data}
+ onValueChange={onValueChange}
+ getItemValue={getItemValue}
+ orientation="vertical"
+ >
+ {data.length ? (
+ <SortableContent className="grid gap-2">
+ {data.map((item) => {
+ if ("type" in item) {
+ const components = form.getValues("components") ?? [];
+ const componentIndex = components.findIndex(
+ (c) => c.id === item.id,
+ );
+ return (
+ <ComponentRow
+ key={`${item.id}-component`}
+ className="border-transparent border-x px-2"
+ component={item}
+ form={form}
+ onDelete={handleDeleteComponent}
+ fieldNamePrefix={
+ componentIndex >= 0
+ ? `components.${componentIndex}`
+ : undefined
+ }
+ />
+ );
+ }
+ const groups = form.getValues("groups") ?? [];
+ const groupIndex = groups.findIndex(
+ (g) => g.id === item.id,
+ );
+ return (
+ <ComponentGroupRow
+ key={`${item.id}-group`}
+ group={item}
+ groupIndex={groupIndex}
+ onDeleteGroup={handleDeleteGroup}
+ form={form}
+ allPageComponents={allPageComponents}
+ monitors={monitors}
+ />
+ );
+ })}
+ <SortableOverlay>{renderOverlay}</SortableOverlay>
+ </SortableContent>
+ ) : (
+ <EmptyStateContainer>
+ <EmptyStateTitle>No components selected</EmptyStateTitle>
+ </EmptyStateContainer>
+ )}
+ </Sortable>
+ </FormCardContent>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ Learn more about{" "}
+ <Link href="https://docs.openstatus.dev/reference/status-page/#page-components">
+ page components
+ </Link>
+ .
+ </FormCardFooterInfo>
+ <Button type="submit" disabled={isPending}>
+ {isPending ? "Submitting..." : "Submit"}
+ </Button>
+ </FormCardFooter>
+ </FormCard>
+ </form>
+ </Form>
+ );
+}
+
+interface ComponentRowProps
+ extends Omit<React.ComponentPropsWithoutRef<typeof SortableItem>, "value"> {
+ component: PageComponent;
+ form: UseFormReturn<FormValues>;
+ onDelete: (componentId: number) => void;
+ /** The form field name prefix, e.g. "components.0" or "groups.0.components.1" */
+ fieldNamePrefix?: string;
+}
+
+function ComponentRow({
+ component,
+ className,
+ onDelete,
+ form,
+ fieldNamePrefix,
+ ...props
+}: ComponentRowProps) {
+ return (
+ <SortableItem
+ value={component.id}
+ asChild
+ className={cn("rounded-md", className)}
+ {...props}
+ >
+ <div className="grid h-9 grid-cols-4 gap-2">
+ <div className="flex flex-row items-center gap-1 self-center">
+ <SortableItemHandle>
+ <GripVertical
+ size={16}
+ aria-hidden="true"
+ className="text-muted-foreground"
+ />
+ </SortableItemHandle>
+ {fieldNamePrefix ? (
+ <FormField
+ control={form.control}
+ name={`${fieldNamePrefix}.name` as "components.0.name"}
+ render={({ field }) => (
+ <FormItem className="w-full">
+ <FormLabel className="sr-only">Component name</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="Name"
+ className="w-full bg-background"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : (
+ <span className="truncate rounded-md border border-transparent px-3 py-1 text-sm">
+ {component.name}
+ </span>
+ )}
+ </div>
+ <div className="flex flex-row items-center gap-1 self-center">
+ {fieldNamePrefix ? (
+ <FormField
+ control={form.control}
+ name={
+ `${fieldNamePrefix}.description` as "components.0.description"
+ }
+ render={({ field }) => (
+ <FormItem className="w-full">
+ <FormLabel className="sr-only">
+ Component description
+ </FormLabel>
+ <FormControl>
+ <Input
+ placeholder="Description"
+ className="w-full bg-background"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : (
+ <span className="truncate rounded-md border border-transparent px-3 py-1 text-sm">
+ {component.description}
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2 self-center text-muted-foreground text-sm">
+ {component.monitor && component.type === "monitor" ? (
+ <Link
+ href={`/monitors/${component.monitorId}/overview`}
+ onClick={(e) => e.stopPropagation()}
+ className="flex w-full items-center gap-2 truncate text-sm"
+ >
+ <Link2 className="size-4 shrink-0" />{" "}
+ <span className="truncate">{component.monitor.name}</span>
+ </Link>
+ ) : (
+ <span className="flex items-center gap-2 text-muted-foreground text-sm">
+ <Link2Off className="size-4 shrink-0" />{" "}
+ <span className="truncate">External Component</span>
+ </span>
+ )}
+ </div>
+ <div className="flex justify-between">
+ <div className="flex flex-1 items-center gap-2.5">
+ {component.monitor && component.type === "monitor" ? (
+ <div className="flex items-center gap-2">
+ <TooltipProvider delayDuration={0}>
+ {component.monitor.public ? (
+ <Tooltip>
+ <TooltipTrigger>
+ <Eye className="size-4 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>Public</TooltipContent>
+ </Tooltip>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger>
+ <EyeOff className="size-4 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>Private</TooltipContent>
+ </Tooltip>
+ )}
+ </TooltipProvider>
+ </div>
+ ) : null}
+ {component.monitor && component.type === "monitor" ? (
+ <div
+ className={cn(
+ "size-2 rounded-full",
+ STATUS[
+ component.monitor.active
+ ? component.monitor.status
+ : "inactive"
+ ],
+ )}
+ />
+ ) : null}
+ </div>
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive dark:hover:bg-destructive/20 [&_svg]:size-4 [&_svg]:text-destructive"
+ >
+ <Trash2 />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Are you sure?</AlertDialogTitle>
+ <AlertDialogDescription>
+ You are about to delete this component.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40"
+ onClick={() => onDelete(component.id)}
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ </div>
+ </SortableItem>
+ );
+}
+
+interface ComponentGroupRowProps
+ extends Omit<React.ComponentPropsWithoutRef<typeof SortableItem>, "value"> {
+ group: ComponentGroup;
+ groupIndex: number;
+ onDeleteGroup: (groupId: number) => void;
+ form: UseFormReturn<FormValues>;
+ allPageComponents: PageComponent[];
+ monitors: Monitor[];
+}
+
+function ComponentGroupRow({
+ group,
+ groupIndex,
+ onDeleteGroup,
+ form,
+ allPageComponents,
+ monitors,
+}: ComponentGroupRowProps) {
+ const watchGroup = form.watch(`groups.${groupIndex}`);
+ const watchComponents = form.watch("components");
+ const watchGroups = form.watch("groups");
+ const [data, setData] = useState<PageComponent[]>(group.components);
+
+ // Calculate taken monitor IDs (in main list or other groups)
+ const takenMonitorIds = new Set([
+ ...watchComponents.filter((c) => c.monitorId).map((c) => c.monitorId),
+ ...watchGroups
+ .filter((g) => g.id !== group.id)
+ .flatMap((g) =>
+ g.components.filter((c) => c.monitorId).map((c) => c.monitorId),
+ ),
+ ]);
+
+ // FIXME: order is not being updated in the form
+ const onValueChange = useCallback(
+ (newComponents: PageComponent[]) => {
+ setData(newComponents);
+ // Update the form with the new component order
+ const existingComponents =
+ form.getValues(`groups.${groupIndex}.components`) ?? [];
+ form.setValue(
+ `groups.${groupIndex}.components`,
+ newComponents.map((c, index) => {
+ const existingComponent = existingComponents.find(
+ (ec) => ec.id === c.id,
+ );
+ return {
+ id: c.id,
+ monitorId: c.monitorId,
+ order: index,
+ name: existingComponent?.name ?? c.name,
+ description: existingComponent?.description ?? "",
+ type: c.type,
+ };
+ }),
+ );
+ },
+ [form, groupIndex],
+ );
+
+ useEffect(() => {
+ setData(
+ getSortedComponents(allPageComponents, watchGroup.components, monitors),
+ );
+ }, [watchGroup.components, allPageComponents, monitors]);
+
+ const getItemValue = useCallback((item: PageComponent) => item.id, []);
+
+ const handleDeleteComponent = useCallback(
+ (componentId: number) => {
+ const existingComponents =
+ form.getValues(`groups.${groupIndex}.components`) ?? [];
+ form.setValue(
+ `groups.${groupIndex}.components`,
+ existingComponents.filter((c) => c.id !== componentId),
+ );
+ setData((prev) => prev.filter((item) => item.id !== componentId));
+ },
+ [form, groupIndex],
+ );
+
+ const renderOverlay = useCallback(
+ ({ value }: { value: UniqueIdentifier }) => {
+ const component = data.find((item) => item.id === value);
+ if (!component) return null;
+
+ return (
+ <ComponentRow
+ component={component}
+ form={form}
+ onDelete={handleDeleteComponent}
+ />
+ );
+ },
+ [data, form, handleDeleteComponent],
+ );
+
+ return (
+ <SortableItem value={group.id} className="rounded-md border bg-muted">
+ <div className="grid grid-cols-4 gap-2 px-2 pt-2">
+ <div className="flex flex-row items-center gap-1 self-center">
+ <SortableItemHandle>
+ <GripVertical
+ size={16}
+ aria-hidden="true"
+ className="text-muted-foreground"
+ />
+ </SortableItemHandle>
+ <FormField
+ key={`${group.id}-name-${groupIndex}`}
+ control={form.control}
+ name={`groups.${groupIndex}.name` as const}
+ render={({ field }) => (
+ <FormItem className="w-full">
+ <FormLabel className="sr-only">Group name</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="Group Name"
+ className="w-full bg-background"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ <FormField
+ key={`${group.id}-components-${groupIndex}`}
+ control={form.control}
+ name={`groups.${groupIndex}.components` as const}
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel className="sr-only">Components</FormLabel>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" className="w-full">
+ <Plus />
+ Add Component
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-[var(--radix-dropdown-menu-trigger-width)]"
+ >
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ disabled
+ onClick={() => {
+ const current = field.value ?? [];
+ form.setValue(`groups.${groupIndex}.components`, [
+ ...current,
+ {
+ id: Date.now(),
+ monitorId: null,
+ order: current.length,
+ name: "",
+ description: "",
+ type: "external" as const,
+ },
+ ]);
+ }}
+ >
+ <Link2Off className="text-muted-foreground" />
+ Add External (soon)
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0">
+ <Link2 className="text-muted-foreground" />
+ Add Monitor
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="p-0">
+ <Command>
+ <CommandInput
+ placeholder="Search monitors..."
+ className="h-9"
+ />
+ <CommandList>
+ <CommandEmpty>No monitors found.</CommandEmpty>
+ <CommandGroup>
+ {monitors.map((monitor) => {
+ const current = field.value ?? [];
+ const isTaken = takenMonitorIds.has(monitor.id);
+ const isSelected = current.some(
+ (c) => c.monitorId === monitor.id,
+ );
+ return (
+ <CommandItem
+ value={monitor.name}
+ key={monitor.id}
+ disabled={isTaken}
+ onSelect={() => {
+ if (isSelected) {
+ form.setValue(
+ `groups.${groupIndex}.components`,
+ current.filter(
+ (c) => c.monitorId !== monitor.id,
+ ),
+ );
+ } else {
+ form.setValue(
+ `groups.${groupIndex}.components`,
+ [
+ ...current,
+ {
+ id: Date.now(),
+ monitorId: monitor.id,
+ order: current.length,
+ name: monitor.name,
+ description: monitor.description,
+ type: "monitor" as const,
+ },
+ ],
+ );
+ }
+ }}
+ >
+ {monitor.name}
+ <Check
+ className={cn(
+ "ml-auto",
+ isSelected
+ ? "opacity-100"
+ : "opacity-0",
+ )}
+ />
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <div />
+ <div className="flex justify-end">
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive dark:hover:bg-destructive/20 [&_svg]:size-4 [&_svg]:text-destructive"
+ // NOTE: delete directly if no components are in the group
+ {...(data.length === 0
+ ? { onClick: () => onDeleteGroup(group.id) }
+ : {})}
+ >
+ <Trash2 />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Are you sure?</AlertDialogTitle>
+ <AlertDialogDescription>
+ You are about to delete this group and all its components.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40"
+ onClick={() => onDeleteGroup(group.id)}
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ </div>
+ <div className="mt-2 border-t px-2 pt-2 pb-2">
+ <Sortable
+ value={data}
+ onValueChange={onValueChange}
+ getItemValue={getItemValue}
+ orientation="vertical"
+ >
+ {data.length ? (
+ <SortableContent className="grid gap-2">
+ {data.map((item, _index) => {
+ const groupComponents =
+ form.getValues(`groups.${groupIndex}.components`) ?? [];
+ const componentIndex = groupComponents.findIndex(
+ (c) => c.id === item.id,
+ );
+ return (
+ <ComponentRow
+ key={`${item.id}-component`}
+ component={item}
+ form={form}
+ onDelete={handleDeleteComponent}
+ fieldNamePrefix={
+ componentIndex >= 0
+ ? `groups.${groupIndex}.components.${componentIndex}`
+ : undefined
+ }
+ />
+ );
+ })}
+ <SortableOverlay>{renderOverlay}</SortableOverlay>
+ </SortableContent>
+ ) : (
+ <EmptyStateContainer>
+ <EmptyStateTitle>No components selected</EmptyStateTitle>
+ </EmptyStateContainer>
+ )}
+ </Sortable>
+ </div>
+ </SortableItem>
+ );
+}
diff --git a/apps/dashboard/src/components/forms/components/update.tsx b/apps/dashboard/src/components/forms/components/update.tsx
new file mode 100644
index 000000000..72cf6f41b
--- /dev/null
+++ b/apps/dashboard/src/components/forms/components/update.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { FormComponents } from "@/components/forms/components/form-components";
+import { useTRPC } from "@/lib/trpc/client";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { useParams } from "next/navigation";
+import { FormCardGroup } from "../form-card";
+
+export function FormComponentsUpdate() {
+ const { id } = useParams<{ id: string }>();
+ const trpc = useTRPC();
+ const { data: statusPage, refetch } = useQuery(
+ trpc.page.get.queryOptions({ id: Number.parseInt(id) }),
+ );
+ const { data: pageComponents, refetch: refetchComponents } = useQuery(
+ trpc.pageComponent.list.queryOptions({ pageId: Number.parseInt(id) }),
+ );
+ const { data: monitors } = useQuery(trpc.monitor.list.queryOptions());
+
+ const updateComponentsMutation = useMutation(
+ trpc.pageComponent.updateOrder.mutationOptions({
+ onSuccess: () => {
+ refetch();
+ refetchComponents();
+ },
+ }),
+ );
+
+ if (!statusPage || !pageComponents || !monitors) return null;
+
+ // Separate standalone components from grouped components
+ const standaloneComponents = pageComponents.filter((c) => !c.groupId);
+ const groupedComponents = pageComponents.filter((c) => c.groupId);
+
+ // Build groups from pageComponentGroups
+ const groups = statusPage.pageComponentGroups.map((group) => {
+ const componentsInGroup = groupedComponents.filter(
+ (c) => c.groupId === group.id,
+ );
+ // Find the order of the group (use the first component's order)
+ const firstComponent = componentsInGroup[0];
+ return {
+ id: group.id,
+ order: firstComponent?.order ?? 0,
+ name: group.name,
+ components: componentsInGroup.map((c) => ({
+ id: c.id,
+ monitorId: c.monitorId,
+ order: c.groupOrder ?? 0,
+ name: c.name,
+ description: c.description ?? "",
+ type: c.type,
+ })),
+ };
+ });
+
+ // Build default values for the form
+ const defaultValues = {
+ components: standaloneComponents.map((c) => ({
+ id: c.id,
+ monitorId: c.monitorId,
+ order: c.order ?? 0,
+ name: c.name,
+ description: c.description ?? "",
+ type: c.type,
+ })),
+ groups,
+ };
+
+ return (
+ <FormCardGroup>
+ <FormComponents
+ pageComponents={standaloneComponents}
+ monitors={monitors}
+ allPageComponents={pageComponents}
+ defaultValues={defaultValues}
+ legacy={statusPage.legacyPage}
+ onSubmit={async (values) => {
+ await updateComponentsMutation.mutateAsync({
+ pageId: Number.parseInt(id),
+ components: values.components.map(({ id, ...rest }) => rest),
+ groups: values.groups.map(({ id, components, ...rest }) => ({
+ ...rest,
+ components: components.map(({ id, ...c }) => c),
+ })),
+ });
+ }}
+ />
+ </FormCardGroup>
+ );
+}
diff --git a/apps/dashboard/src/components/forms/monitor/update.tsx b/apps/dashboard/src/components/forms/monitor/update.tsx
index f18bb990b..3bdc2733b 100644
--- a/apps/dashboard/src/components/forms/monitor/update.tsx
+++ b/apps/dashboard/src/components/forms/monitor/update.tsx
@@ -16,7 +16,6 @@ import { FormOtel } from "./form-otel";
import { FormResponseTime } from "./form-response-time";
import { FormRetry, RETRY_DEFAULT } from "./form-retry";
import { FormSchedulingRegions } from "./form-scheduling-regions";
-import { FormStatusPages } from "./form-status-pages";
import { FormTags } from "./form-tags";
import { FormVisibility } from "./form-visibility";
@@ -88,12 +87,6 @@ export function FormMonitorUpdate() {
}),
);
- const updateStatusPagesMutation = useMutation(
- trpc.monitor.updateStatusPages.mutationOptions({
- onSuccess: () => refetch(),
- }),
- );
-
const updateNotifiersMutation = useMutation(
trpc.monitor.updateNotifiers.mutationOptions({
onSuccess: () => refetch(),
@@ -194,22 +187,6 @@ export function FormMonitorUpdate() {
});
}}
/>
- <FormStatusPages
- statusPages={statusPages}
- defaultValues={{
- statusPages: monitor.pages.map(({ id }) => id),
- description: monitor.description,
- externalName: monitor.externalName ?? "",
- }}
- onSubmit={async (values) => {
- await updateStatusPagesMutation.mutateAsync({
- id: Number.parseInt(id),
- statusPages: values.statusPages,
- description: values.description,
- externalName: values.externalName,
- });
- }}
- />
<FormNotifiers
notifiers={notifications}
defaultValues={{
diff --git a/apps/dashboard/src/components/forms/status-page/update.tsx b/apps/dashboard/src/components/forms/status-page/update.tsx
index 81cf5fc55..680d1d7ad 100644
--- a/apps/dashboard/src/components/forms/status-page/update.tsx
+++ b/apps/dashboard/src/components/forms/status-page/update.tsx
@@ -11,7 +11,6 @@ import { FormCustomDomain } from "./form-custom-domain";
import { FormDangerZone } from "./form-danger-zone";
import { FormGeneral } from "./form-general";
import { FormLinks } from "./form-links";
-import { FormMonitors } from "./form-monitors";
import { FormPageAccess } from "./form-page-access";
export function FormStatusPageUpdate() {
@@ -42,12 +41,6 @@ export function FormStatusPageUpdate() {
}),
);
- const updateMonitorsMutation = useMutation(
- trpc.page.updateMonitors.mutationOptions({
- onSuccess: () => refetch(),
- }),
- );
-
const updateCustomDomainMutation = useMutation(
trpc.page.updateCustomDomain.mutationOptions({
onSuccess: () => refetch(),
@@ -96,18 +89,12 @@ export function FormStatusPageUpdate() {
return (
<FormCardGroup>
- <Note color="info">
+ <Note color="warning">
<Info />
<p className="text-sm">
- We've enabled the new version of the status page. Read more about the{" "}
- <Link
- href="https://docs.openstatus.dev/tutorial/how-to-configure-status-page/"
- rel="noreferrer"
- target="_blank"
- >
- configuration
- </Link>
- .
+ Looking to connect monitors to your status page? The setup now has a
+ separate components page{" "}
+ <Link href={`/status-pages/${id}/components`}>components</Link>.
</p>
</Note>
<FormGeneral
@@ -127,43 +114,6 @@ export function FormStatusPageUpdate() {
});
}}
/>
- <FormMonitors
- monitors={monitors ?? []}
- defaultValues={{
- monitors: statusPage.monitors
- .filter((m) => !m.groupId)
- .map((monitor) => ({
- id: monitor.id,
- order: monitor.order,
- active: monitor.active ?? null,
- })),
- groups: statusPage.monitorGroups.map((group) => {
- const order =
- statusPage.monitors.find((m) => m.groupId === group.id)?.order ??
- 0;
- return {
- id: -1 * group.id, // negative id to avoid conflicts with monitors
- order,
- name: group.name,
- monitors: statusPage.monitors
- .filter((m) => m.groupId === group.id)
- .map((monitor) => ({
- id: monitor.id,
- order: monitor.groupOrder,
- active: monitor.active ?? null,
- })),
- };
- }),
- }}
- legacy={statusPage.legacyPage}
- onSubmit={async (values) => {
- await updateMonitorsMutation.mutateAsync({
- id: Number.parseInt(id),
- monitors: values.monitors,
- groups: values.groups,
- });
- }}
- />
<FormCustomDomain
locked={workspace.limits["custom-domain"] === false}
defaultValues={{
diff --git a/apps/dashboard/src/components/nav/nav-monitors.tsx b/apps/dashboard/src/components/nav/nav-monitors.tsx
index 09a310bc0..6b1e5b30c 100644
--- a/apps/dashboard/src/components/nav/nav-monitors.tsx
+++ b/apps/dashboard/src/components/nav/nav-monitors.tsx
@@ -33,7 +33,7 @@ import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { toast } from "sonner";
-const STATUS = {
+export const STATUS = {
degraded: "bg-warning border border-warning",
error: "bg-destructive border border-destructive",
inactive: "bg-muted-foreground/70 border border-muted-foreground/70",
diff --git a/apps/dashboard/src/data/page-components.client.ts b/apps/dashboard/src/data/page-components.client.ts
new file mode 100644
index 000000000..ff6f46922
--- /dev/null
+++ b/apps/dashboard/src/data/page-components.client.ts
@@ -0,0 +1,21 @@
+import { Trash2 } from "lucide-react";
+
+export const actions = [
+ {
+ id: "delete",
+ label: "Delete",
+ icon: Trash2,
+ variant: "destructive" as const,
+ },
+] as const;
+
+export type PageComponentAction = (typeof actions)[number];
+
+export const getActions = (
+ props: Partial<Record<PageComponentAction["id"], () => Promise<void> | void>>,
+): (PageComponentAction & { onClick?: () => Promise<void> | void })[] => {
+ return actions.map((action) => ({
+ ...action,
+ onClick: props[action.id as keyof typeof props],
+ }));
+};
diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.ts
index 11650fc0a..1c5d1e2e8 100644
--- a/packages/api/src/edge.ts
+++ b/packages/api/src/edge.ts
@@ -11,6 +11,7 @@ import { monitorRouter } from "./router/monitor";
import { monitorTagRouter } from "./router/monitorTag";
import { notificationRouter } from "./router/notification";
import { pageRouter } from "./router/page";
+import { pageComponentRouter } from "./router/pageComponent";
import { pageSubscriberRouter } from "./router/pageSubscriber";
import { privateLocationRouter } from "./router/privateLocation";
import { statusPageRouter } from "./router/statusPage";
@@ -25,6 +26,7 @@ export const edgeRouter = createTRPCRouter({
workspace: workspaceRouter,
monitor: monitorRouter,
page: pageRouter,
+ pageComponent: pageComponentRouter,
statusReport: statusReportRouter,
domain: domainRouter,
integration: integrationRouter,
diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.ts
index 63b52c819..39dedaf4a 100644
--- a/packages/api/src/router/page.ts
+++ b/packages/api/src/router/page.ts
@@ -12,8 +12,8 @@ import {
syncMonitorGroupDeleteMany,
syncMonitorGroupInsert,
syncMonitorsToPageDelete,
- syncMonitorsToPageInsertMany,
syncMonitorsToPageUpsertMany,
+ syncPageComponentToMonitorsToPageInsertMany,
} from "@openstatus/db";
import {
incidentTable,
@@ -25,9 +25,11 @@ import {
monitorsToPages,
page,
pageAccessTypes,
+ pageComponent,
selectMaintenanceSchema,
selectMonitorGroupSchema,
selectMonitorSchema,
+ selectPageComponentGroupSchema,
selectPageComponentSchema,
selectPageSchema,
statusReport,
@@ -122,11 +124,12 @@ export const pageRouter = createTRPCRouter({
.get();
if (monitorIds.length) {
- // We should make sure the user has access to the monitors
+ // We should make sure the user has access to the monitors AND they are active
const allMonitors = await opts.ctx.db.query.monitor.findMany({
where: and(
inArray(monitor.id, monitorIds),
eq(monitor.workspaceId, opts.ctx.workspace.id),
+ eq(monitor.active, true), // Only allow active monitors
isNull(monitor.deletedAt),
),
});
@@ -134,19 +137,50 @@ export const pageRouter = createTRPCRouter({
if (allMonitors.length !== monitorIds.length) {
throw new TRPCError({
code: "FORBIDDEN",
- message: "You don't have access to all the monitors.",
+ message:
+ "You don't have access to all the monitors or some monitors are inactive.",
});
}
- const values = monitors.map(({ monitorId }, index) => ({
+ // Build a map for quick lookup
+ const monitorMap = new Map(allMonitors.map((m) => [m.id, m]));
+
+ // Build pageComponent values (primary table)
+ const pageComponentValues = monitors
+ .map(({ monitorId }, index) => {
+ const m = monitorMap.get(monitorId);
+ if (!m || !m.workspaceId) return null;
+ return {
+ workspaceId: m.workspaceId,
+ pageId: newPage.id,
+ type: "monitor" as const,
+ monitorId,
+ name: m.externalName || m.name,
+ order: index,
+ groupId: null,
+ groupOrder: 0,
+ };
+ })
+ .filter((v): v is NonNullable<typeof v> => v !== null);
+
+ // Insert into pageComponents (primary table)
+ await opts.ctx.db
+ .insert(pageComponent)
+ .values(pageComponentValues)
+ .run();
+
+ // Build values for reverse sync to monitorsToPages
+ const monitorsToPageValues = monitors.map(({ monitorId }, index) => ({
pageId: newPage.id,
order: index,
monitorId,
}));
- await opts.ctx.db.insert(monitorsToPages).values(values).run();
- // Sync to page components
- await syncMonitorsToPageInsertMany(opts.ctx.db, values);
+ // Reverse sync to monitorsToPages (for backwards compatibility)
+ await syncPageComponentToMonitorsToPageInsertMany(
+ opts.ctx.db,
+ monitorsToPageValues,
+ );
}
return newPage;
@@ -353,6 +387,7 @@ export const pageRouter = createTRPCRouter({
monitorsToPages: { with: { monitor: true, monitorGroup: true } },
maintenances: true,
pageComponents: true,
+ pageComponentGroups: true,
},
});
@@ -368,6 +403,9 @@ export const pageRouter = createTRPCRouter({
)
.prefault([]),
monitorGroups: z.array(selectMonitorGroupSchema).prefault([]),
+ pageComponentGroups: z
+ .array(selectPageComponentGroupSchema)
+ .prefault([]),
maintenances: z.array(selectMaintenanceSchema).prefault([]),
pageComponents: z.array(selectPageComponentSchema).prefault([]),
})
@@ -386,6 +424,7 @@ export const pageRouter = createTRPCRouter({
.map((m) => [m.monitorGroup?.id, m.monitorGroup]),
).values(),
),
+ pageComponentGroups: data?.pageComponentGroups ?? [],
maintenances: data?.maintenances,
pageComponents: data?.pageComponents,
});
diff --git a/packages/api/src/router/pageComponent.ts b/packages/api/src/router/pageComponent.ts
new file mode 100644
index 000000000..7b7431b48
--- /dev/null
+++ b/packages/api/src/router/pageComponent.ts
@@ -0,0 +1,423 @@
+import { z } from "zod";
+
+import { type SQL, and, asc, desc, eq, inArray, sql } from "@openstatus/db";
+import {
+ page,
+ pageComponent,
+ pageComponentGroup,
+} from "@openstatus/db/src/schema";
+
+import { TRPCError } from "@trpc/server";
+import { createTRPCRouter, protectedProcedure } from "../trpc";
+
+export const pageComponentRouter = createTRPCRouter({
+ list: protectedProcedure
+ .input(
+ z
+ .object({
+ pageId: z.number().optional(),
+ order: z.enum(["asc", "desc"]).optional(),
+ })
+ .optional(),
+ )
+ .query(async (opts) => {
+ const whereConditions: SQL[] = [
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ ];
+
+ if (opts.input?.pageId) {
+ whereConditions.push(eq(pageComponent.pageId, opts.input.pageId));
+ }
+
+ const query = opts.ctx.db.query.pageComponent.findMany({
+ where: and(...whereConditions),
+ orderBy:
+ opts.input?.order === "desc"
+ ? desc(pageComponent.order)
+ : asc(pageComponent.order),
+ with: {
+ monitor: true,
+ group: true,
+ },
+ });
+
+ const result = await query;
+
+ return result;
+ }),
+
+ delete: protectedProcedure
+ .input(z.object({ id: z.number() }))
+ .mutation(async (opts) => {
+ return await opts.ctx.db
+ .delete(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.id, opts.input.id),
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ ),
+ )
+ .returning();
+ }),
+
+ new: protectedProcedure
+ .input(
+ z.object({
+ pageId: z.number(),
+ name: z.string().min(1),
+ description: z.string().optional(),
+ type: z.enum(["external", "monitor"]).default("monitor"),
+ monitorId: z.number().optional(),
+ order: z.number().optional(),
+ groupId: z.number().optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ const _page = await opts.ctx.db.query.page.findFirst({
+ where: and(
+ eq(page.id, opts.input.pageId),
+ eq(page.workspaceId, opts.ctx.workspace.id),
+ ),
+ });
+
+ if (!_page) {
+ throw new TRPCError({ code: "NOT_FOUND", message: "Page not found" });
+ }
+
+ const newPageComponent = await opts.ctx.db
+ .insert(pageComponent)
+ .values({
+ pageId: opts.input.pageId,
+ workspaceId: opts.ctx.workspace.id,
+ name: opts.input.name,
+ description: opts.input.description,
+ type: opts.input.type,
+ monitorId: opts.input.monitorId,
+ order: opts.input.order,
+ groupId: opts.input.groupId,
+ })
+ .returning()
+ .get();
+
+ return newPageComponent;
+ }),
+
+ update: protectedProcedure
+ .input(
+ z.object({
+ id: z.number(),
+ name: z.string().min(1),
+ description: z.string().optional(),
+ type: z.enum(["external", "monitor"]).optional(),
+ monitorId: z.number().optional(),
+ order: z.number().optional(),
+ groupId: z.number().optional(),
+ }),
+ )
+ .mutation(async (opts) => {
+ const whereConditions: SQL[] = [
+ eq(pageComponent.id, opts.input.id),
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ ];
+
+ const _pageComponent = await opts.ctx.db
+ .update(pageComponent)
+ .set({
+ name: opts.input.name,
+ description: opts.input.description,
+ type: opts.input.type,
+ monitorId: opts.input.monitorId,
+ order: opts.input.order,
+ groupId: opts.input.groupId,
+ updatedAt: new Date(),
+ })
+ .where(and(...whereConditions))
+ .returning()
+ .get();
+
+ return _pageComponent;
+ }),
+
+ updateOrder: protectedProcedure
+ .input(
+ z.object({
+ pageId: z.number(),
+ components: z.array(
+ z.object({
+ id: z.number().optional(), // Optional for new components
+ monitorId: z.number().nullish(),
+ order: z.number(),
+ name: z.string(),
+ description: z.string().nullish(),
+ type: z.enum(["monitor", "external"]),
+ }),
+ ),
+ groups: z.array(
+ z.object({
+ order: z.number(),
+ name: z.string(),
+ components: z.array(
+ z.object({
+ id: z.number().optional(), // Optional for new components
+ monitorId: z.number().nullish(),
+ order: z.number(),
+ name: z.string(),
+ description: z.string().nullish(),
+ type: z.enum(["monitor", "external"]),
+ }),
+ ),
+ }),
+ ),
+ }),
+ )
+ .mutation(async (opts) => {
+ await opts.ctx.db.transaction(async (tx) => {
+ // Get existing state
+ const existingComponents = await tx
+ .select()
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, opts.input.pageId),
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ ),
+ )
+ .all();
+
+ const existingGroups = await tx
+ .select()
+ .from(pageComponentGroup)
+ .where(
+ and(
+ eq(pageComponentGroup.pageId, opts.input.pageId),
+ eq(pageComponentGroup.workspaceId, opts.ctx.workspace.id),
+ ),
+ )
+ .all();
+
+ const existingGroupIds = existingGroups.map((g) => g.id);
+
+ // Collect all monitorIds from input (for monitor-type components)
+ const inputMonitorIds = [
+ ...opts.input.components
+ .filter((c) => c.type === "monitor" && c.monitorId)
+ .map((c) => c.monitorId),
+ ...opts.input.groups.flatMap((g) =>
+ g.components
+ .filter((c) => c.type === "monitor" && c.monitorId)
+ .map((c) => c.monitorId),
+ ),
+ ] as number[];
+
+ // Collect IDs for external components that have IDs in input
+ const inputExternalComponentIds = [
+ ...opts.input.components
+ .filter((c) => c.type === "external" && c.id)
+ .map((c) => c.id),
+ ...opts.input.groups.flatMap((g) =>
+ g.components
+ .filter((c) => c.type === "external" && c.id)
+ .map((c) => c.id),
+ ),
+ ] as number[];
+
+ // Find components that are being removed
+ // For monitor components: those with monitorIds not in the input
+ // For external components with IDs: those with IDs not in the input
+ // For external components without IDs in input: delete all existing external components
+ const removedMonitorComponents = existingComponents.filter(
+ (c) =>
+ c.type === "monitor" &&
+ c.monitorId &&
+ !inputMonitorIds.includes(c.monitorId),
+ );
+
+ const hasExternalComponentsInInput =
+ opts.input.components.some((c) => c.type === "external") ||
+ opts.input.groups.some((g) =>
+ g.components.some((c) => c.type === "external"),
+ );
+
+ // If input has external components but they don't have IDs, we need to delete old ones
+ // If input has external components with IDs, only delete those not in input
+ const removedExternalComponents = existingComponents.filter((c) => {
+ if (c.type !== "external") return false;
+ // If we have external components in input
+ if (hasExternalComponentsInInput) {
+ // If the input has IDs, only remove those not in the list
+ if (inputExternalComponentIds.length > 0) {
+ return !inputExternalComponentIds.includes(c.id);
+ }
+ // If input doesn't have IDs, remove all existing external components
+ return true;
+ }
+ // If no external components in input at all, remove existing ones
+ return true;
+ });
+
+ const removedComponentIds = [
+ ...removedMonitorComponents.map((c) => c.id),
+ ...removedExternalComponents.map((c) => c.id),
+ ];
+
+ // Delete removed components
+ if (removedComponentIds.length > 0) {
+ await tx
+ .delete(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, opts.input.pageId),
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ inArray(pageComponent.id, removedComponentIds),
+ ),
+ );
+ }
+
+ // Clear groupId from all components before deleting groups
+ // This prevents foreign key constraint errors
+ if (existingGroupIds.length > 0) {
+ await tx
+ .update(pageComponent)
+ .set({ groupId: null })
+ .where(
+ and(
+ eq(pageComponent.pageId, opts.input.pageId),
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ inArray(pageComponent.groupId, existingGroupIds),
+ ),
+ );
+ }
+
+ // Delete old groups and create new ones
+ if (existingGroupIds.length > 0) {
+ await tx
+ .delete(pageComponentGroup)
+ .where(
+ and(
+ eq(pageComponentGroup.pageId, opts.input.pageId),
+ eq(pageComponentGroup.workspaceId, opts.ctx.workspace.id),
+ ),
+ );
+ }
+
+ // Create new groups
+ const newGroups: Array<{ id: number; name: string }> = [];
+ if (opts.input.groups.length > 0) {
+ const createdGroups = await tx
+ .insert(pageComponentGroup)
+ .values(
+ opts.input.groups.map((g) => ({
+ pageId: opts.input.pageId,
+ workspaceId: opts.ctx.workspace.id,
+ name: g.name,
+ })),
+ )
+ .returning();
+ newGroups.push(...createdGroups);
+ }
+
+ // Prepare values for upsert - both grouped and ungrouped components
+ const groupComponentValues = opts.input.groups.flatMap((g, i) =>
+ g.components.map((c) => ({
+ id: c.id, // Will be undefined for new components
+ pageId: opts.input.pageId,
+ workspaceId: opts.ctx.workspace.id,
+ name: c.name,
+ description: c.description,
+ type: c.type,
+ monitorId: c.monitorId,
+ order: g.order,
+ groupId: newGroups[i].id,
+ groupOrder: c.order,
+ })),
+ );
+
+ const standaloneComponentValues = opts.input.components.map((c) => ({
+ id: c.id, // Will be undefined for new components
+ pageId: opts.input.pageId,
+ workspaceId: opts.ctx.workspace.id,
+ name: c.name,
+ description: c.description,
+ type: c.type,
+ monitorId: c.monitorId,
+ order: c.order,
+ groupId: null as number | null,
+ groupOrder: null as number | null,
+ }));
+
+ const allComponentValues = [
+ ...groupComponentValues,
+ ...standaloneComponentValues,
+ ];
+
+ // Separate monitor and external components for different upsert strategies
+ const monitorComponents = allComponentValues.filter(
+ (c) => c.type === "monitor" && c.monitorId,
+ );
+ const externalComponents = allComponentValues.filter(
+ (c) => c.type === "external",
+ );
+
+ // Upsert monitor components using SQL-level conflict resolution
+ // This uses the (pageId, monitorId) unique constraint to preserve component IDs
+ if (monitorComponents.length > 0) {
+ await tx
+ .insert(pageComponent)
+ .values(monitorComponents)
+ .onConflictDoUpdate({
+ target: [pageComponent.pageId, pageComponent.monitorId],
+ set: {
+ name: sql.raw("excluded.`name`"),
+ description: sql.raw("excluded.`description`"),
+ order: sql.raw("excluded.`order`"),
+ groupId: sql.raw("excluded.`group_id`"),
+ groupOrder: sql.raw("excluded.`group_order`"),
+ updatedAt: sql`(strftime('%s', 'now'))`,
+ },
+ });
+ }
+
+ // Handle external components
+ // If they have IDs, update them; otherwise insert new ones
+ for (const componentValue of externalComponents) {
+ if (componentValue.id) {
+ // Update existing external component (preserves ID and relationships)
+ await tx
+ .update(pageComponent)
+ .set({
+ name: componentValue.name,
+ description: componentValue.description,
+ type: componentValue.type,
+ monitorId: componentValue.monitorId,
+ order: componentValue.order,
+ groupId: componentValue.groupId,
+ groupOrder: componentValue.groupOrder,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(pageComponent.id, componentValue.id),
+ eq(pageComponent.pageId, opts.input.pageId),
+ eq(pageComponent.workspaceId, opts.ctx.workspace.id),
+ ),
+ );
+ } else {
+ // Insert new external component
+ await tx.insert(pageComponent).values({
+ pageId: componentValue.pageId,
+ workspaceId: componentValue.workspaceId,
+ name: componentValue.name,
+ description: componentValue.description,
+ type: componentValue.type,
+ monitorId: componentValue.monitorId,
+ order: componentValue.order,
+ groupId: componentValue.groupId,
+ groupOrder: componentValue.groupOrder,
+ });
+ }
+ }
+ });
+
+ return { success: true };
+ }),
+});
diff --git a/packages/api/src/router/sync.test.ts b/packages/api/src/router/sync.test.ts
index 25039baf4..207ce66ed 100644
--- a/packages/api/src/router/sync.test.ts
+++ b/packages/api/src/router/sync.test.ts
@@ -105,7 +105,7 @@ beforeAll(async () => {
.get();
testPageId = testPage.id;
- // Create test monitor using tRPC
+ // Create test monitor using tRPC (must be active for sync to work)
const ctx = getTestContext();
const caller = appRouter.createCaller(ctx);
const createdMonitor = await caller.monitor.new({
@@ -115,7 +115,7 @@ beforeAll(async () => {
method: monitorData.method,
headers: [],
assertions: [],
- active: false,
+ active: true, // Changed to true - sync functions only sync active monitors
skipCheck: true,
});
testMonitorId = createdMonitor.id;
@@ -594,7 +594,7 @@ describe("Sync: monitor deletion cascades to page_component tables", () => {
const ctx = getTestContext();
const caller = appRouter.createCaller(ctx);
- // Create a monitor specifically for deletion tests
+ // Create a monitor specifically for deletion tests (must be active for sync)
const deletableMonitor = await caller.monitor.new({
name: `${TEST_PREFIX}-deletable-monitor`,
url: "https://delete-test.example.com",
@@ -602,7 +602,7 @@ describe("Sync: monitor deletion cascades to page_component tables", () => {
method: "GET" as const,
headers: [],
assertions: [],
- active: false,
+ active: true, // Changed to true - sync functions only sync active monitors
skipCheck: true,
});
deletableMonitorId = deletableMonitor.id;
diff --git a/packages/db/src/sync.ts b/packages/db/src/sync.ts
index b60a83e72..e9c3d2cd6 100644
--- a/packages/db/src/sync.ts
+++ b/packages/db/src/sync.ts
@@ -6,6 +6,7 @@ import {
maintenancesToMonitors,
maintenancesToPageComponents,
monitor,
+ monitorsToPages,
monitorsToStatusReport,
pageComponent,
pageComponentGroup,
@@ -90,19 +91,21 @@ export async function syncMonitorsToPageInsert(
groupOrder?: number;
},
) {
- // Get monitor data for name and workspace_id
+ // Get monitor data for name and workspace_id (only active monitors)
const monitorData = await db
.select({
id: monitor.id,
name: monitor.name,
externalName: monitor.externalName,
workspaceId: monitor.workspaceId,
+ active: monitor.active,
})
.from(monitor)
.where(eq(monitor.id, data.monitorId))
.get();
- if (!monitorData || !monitorData.workspaceId) return;
+ // Skip if monitor doesn't exist, has no workspace, or is inactive
+ if (!monitorData || !monitorData.workspaceId || !monitorData.active) return;
await db
.insert(pageComponent)
@@ -134,7 +137,7 @@ export async function syncMonitorsToPageInsertMany(
) {
if (items.length === 0) return;
- // Get all monitor data in one query
+ // Get all monitor data in one query (only active monitors)
const monitorIds = [...new Set(items.map((item) => item.monitorId))];
const monitors = await db
.select({
@@ -142,16 +145,18 @@ export async function syncMonitorsToPageInsertMany(
name: monitor.name,
externalName: monitor.externalName,
workspaceId: monitor.workspaceId,
+ active: monitor.active,
})
.from(monitor)
- .where(inArray(monitor.id, monitorIds));
+ .where(and(inArray(monitor.id, monitorIds), eq(monitor.active, true)));
const monitorMap = new Map(monitors.map((m) => [m.id, m]));
const values = items
.map((item) => {
const m = monitorMap.get(item.monitorId);
- if (!m || !m.workspaceId) return null;
+ // Skip if monitor doesn't exist, has no workspace, or is inactive
+ if (!m || !m.workspaceId || !m.active) return null;
return {
workspaceId: m.workspaceId,
pageId: item.pageId,
@@ -186,7 +191,7 @@ export async function syncMonitorsToPageUpsertMany(
) {
if (items.length === 0) return;
- // Get all monitor data in one query
+ // Get all monitor data in one query (only active monitors)
const monitorIds = [...new Set(items.map((item) => item.monitorId))];
const monitors = await db
.select({
@@ -194,16 +199,18 @@ export async function syncMonitorsToPageUpsertMany(
name: monitor.name,
externalName: monitor.externalName,
workspaceId: monitor.workspaceId,
+ active: monitor.active,
})
.from(monitor)
- .where(inArray(monitor.id, monitorIds));
+ .where(and(inArray(monitor.id, monitorIds), eq(monitor.active, true)));
const monitorMap = new Map(monitors.map((m) => [m.id, m]));
const values = items
.map((item) => {
const m = monitorMap.get(item.monitorId);
- if (!m || !m.workspaceId) return null;
+ // Skip if monitor doesn't exist, has no workspace, or is inactive
+ if (!m || !m.workspaceId || !m.active) return null;
return {
workspaceId: m.workspaceId,
pageId: item.pageId,
@@ -278,6 +285,36 @@ export async function syncMonitorsToPageDeleteByMonitors(
.where(inArray(pageComponent.monitorId, monitorIds));
}
+/**
+ * REVERSE SYNC: Syncs page_component inserts to monitors_to_pages
+ * Used when pageComponents is the primary table and monitorsToPages is kept for backwards compatibility
+ */
+export async function syncPageComponentToMonitorsToPageInsertMany(
+ db: DB | Transaction,
+ items: Array<{
+ monitorId: number;
+ pageId: number;
+ order?: number;
+ monitorGroupId?: number | null;
+ groupOrder?: number;
+ }>,
+) {
+ if (items.length === 0) return;
+
+ await db
+ .insert(monitorsToPages)
+ .values(
+ items.map((item) => ({
+ monitorId: item.monitorId,
+ pageId: item.pageId,
+ order: item.order ?? 0,
+ monitorGroupId: item.monitorGroupId ?? null,
+ groupOrder: item.groupOrder ?? 0,
+ })),
+ )
+ .onConflictDoNothing();
+}
+
// ============================================================================
// Status Report to Monitors <-> Status Report to Page Components Sync
// ============================================================================