Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
chore: move workspace schema to trpc context (#424)
Maximilian Kaskeeee0bbbf9070
diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.tsindex fd36f9494..4f11a03dc 100644--- a/apps/web/next-env.d.ts+++ b/apps/web/next-env.d.ts@@ -1,6 +1,5 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-/// <reference types="next/navigation-types/compat/navigation" />// NOTE: This file should not be edited// see https://nextjs.org/docs/basic-features/typescript for more information.diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/edit/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/edit/page.tsxindex c1eca509d..416baa071 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/edit/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/edit/page.tsx@@ -26,7 +26,6 @@ export default async function EditPage({}const { id } = search.data;- const { workspaceSlug } = params;const incident = id? await api.incident.getIncidentById.query({@@ -34,25 +33,24 @@ export default async function EditPage({}): undefined;- const monitors = await api.monitor.getMonitorsByWorkspace.query({- workspaceSlug,- });+ const monitors = await api.monitor.getMonitorsByWorkspace.query();- const pages = await api.page.getPagesByWorkspace.query({ workspaceSlug });+ const pages = await api.page.getPagesByWorkspace.query();return (<div className="grid gap-6 md:grid-cols-2 md:gap-8"><Header title="Incident" description="Upsert your incident." /><div className="col-span-full"><IncidentForm- workspaceSlug={workspaceSlug}monitors={monitors}pages={pages}defaultValues={incident- ? {+ ? // TODO: we should move the mapping to the trpc layer+ // so we don't have to do this in the UI+ // it should be something like defaultValues={incident}+ {...incident,- workspaceSlug,monitors: incident?.monitorsToIncidents.map(({ monitorId }) => monitorId,),diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/page.tsxindex ec3a9e24d..2bd6b1e00 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/page.tsx@@ -21,9 +21,7 @@ export default async function IncidentPage({}: {params: { workspaceSlug: string };}) {- const incidents = await api.incident.getIncidentByWorkspace.query({- workspaceSlug: params.workspaceSlug,- });+ const incidents = await api.incident.getIncidentByWorkspace.query();return (<div className="grid min-h-full grid-cols-1 grid-rows-[auto,1fr,auto] gap-6 md:grid-cols-1 md:gap-8"><Header@@ -66,11 +64,7 @@ export default async function IncidentPage({New Update</Link></Button>,- <ActionButton- key="action-button"- id={incident.id}- workspaceSlug={params.workspaceSlug}- />,+ <ActionButton key="action-button" id={incident.id} />,]}><div className="grid gap-4">diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/update/edit/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/update/edit/page.tsxindex e86942412..0690d7833 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/update/edit/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/incidents/update/edit/page.tsx@@ -42,16 +42,8 @@ export default async function EditPage({/><div className="col-span-full"><IncidentUpdateForm- workspaceSlug={params.workspaceSlug}incidentId={incidentId}- defaultValues={- incidentUpdate- ? {- workspaceSlug: params.workspaceSlug,- ...incidentUpdate,- }- : undefined- }+ defaultValues={incidentUpdate || undefined}/></div></div>diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsxindex e43a86641..467e0c4fe 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/integrations/page.tsx@@ -1,21 +1,17 @@-"use client";-import * as React from "react";-import { Badge, Button } from "@openstatus/ui";+import { Button } from "@openstatus/ui";import { Container } from "@/components/dashboard/container";import { Header } from "@/components/dashboard/header";-import { api } from "@/trpc/client";+import { api } from "@/trpc/server";export default async function IncidentPage({params,}: {params: { workspaceSlug: string };}) {- const workspace = await api.workspace.getWorkspace.query({- slug: params.workspaceSlug,- });+ const workspace = await api.workspace.getWorkspace.query();return (<div className="grid gap-6 md:grid-cols-2 md:gap-8">diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsxindex e8b79093d..d0a40d111 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/layout.tsx@@ -15,9 +15,7 @@ export default async function AppLayout({children: React.ReactNode;params: { workspaceSlug: string };}) {- const workspace = await api.workspace.getWorkspace.query({- slug: params.workspaceSlug,- });+ const workspace = await api.workspace.getWorkspace.query();if (!workspace) return notFound(); // TODO: discuss if we should move to middlewarereturn (diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/[id]/data/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/[id]/data/page.tsxindex 66d21c647..0f9eb825d 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/[id]/data/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/[id]/data/page.tsx@@ -38,7 +38,7 @@ export default async function Page({const id = params.id;const search = searchParamsSchema.safeParse(searchParams);- const monitor = await api.monitor.getMonitorByID.query({+ const monitor = await api.monitor.getMonitorById.query({id: Number(id),});diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/_components/action-button.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/_components/action-button.tsxindex b35d9936c..e2ed3dbbf 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/_components/action-button.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/_components/action-button.tsx@@ -40,7 +40,7 @@ export function ActionButton(props: Schema & { workspaceSlug: string }) {startTransition(async () => {try {if (!props.id) return;- await api.monitor.deleteMonitor.mutate({ id: props.id });+ await api.monitor.delete.mutate({ id: props.id });toast("deleted");router.refresh();setAlertOpen(false);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 38bf7e05b..6e6f1aa55 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@@ -26,12 +26,11 @@ 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: workspaceSlug,- });+ const monitor = id+ ? await api.monitor.getMonitorById.query({ id })+ : undefined;+ const workspace = await api.workspace.getWorkspace.query();const monitorNotifications = id? await api.monitor.getAllNotificationsForMonitor.query({@@ -40,9 +39,7 @@ export default async function EditPage({: [];const notifications =- await api.notification.getNotificationsByWorkspace.query({- workspaceSlug,- });+ await api.notification.getNotificationsByWorkspace.query();return (<div className="grid gap-6 md:grid-cols-2 md:gap-8">@@ -61,7 +58,7 @@ export default async function EditPage({: undefined}plan={workspace?.plan}- {...{ workspaceSlug, notifications }}+ notifications={notifications}/></div></div>diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsxindex 48b65f970..cf56ac3e7 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx@@ -18,12 +18,8 @@ export default async function MonitorPage({}: {params: { workspaceSlug: string };}) {- const monitors = await api.monitor.getMonitorsByWorkspace.query({- workspaceSlug: params.workspaceSlug,- });- const workspace = await api.workspace.getWorkspace.query({- slug: params.workspaceSlug,- });+ const monitors = await api.monitor.getMonitorsByWorkspace.query();+ const workspace = await api.workspace.getWorkspace.query();const isLimit =(monitors?.length || 0) >=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.tsxindex 6b9be41d6..33c7ec8e6 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/edit/page.tsx@@ -27,8 +27,9 @@ export default async function EditPage({const { id } = search.data;- const notification =- id && (await api.notification.getNotificationById.query({ id }));+ const notification = id+ ? await api.notification.getNotificationById.query({ id })+ : undefined;return (<div className="grid gap-6 md:grid-cols-2 md:gap-8">@@ -41,10 +42,7 @@ export default async function EditPage({}/><div className="col-span-full">- <NotificationForm- workspaceSlug={params.workspaceSlug}- defaultValues={notification || undefined}- />+ <NotificationForm defaultValues={notification} /></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.tsxindex cf5e5ba7a..e527b79d8 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/notifications/page.tsx@@ -16,9 +16,7 @@ export default async function MonitorPage({params: { workspaceSlug: string };}) {const notifications =- await api.notification.getNotificationsByWorkspace.query({- workspaceSlug: params.workspaceSlug,- });+ await api.notification.getNotificationsByWorkspace.query();return (<div className="grid min-h-full grid-cols-1 grid-rows-[auto,1fr,auto] gap-6 md:grid-cols-2 md:gap-8">diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsxindex f488da395..3910a8d4f 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsx@@ -19,9 +19,7 @@ export default async function Page({}: {params: { workspaceSlug: string };}) {- const data = await api.workspace.getWorkspace.query({- slug: params.workspaceSlug,- });+ const data = await api.workspace.getWorkspace.query();if (!data) {return <>Workspace not found</>;diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/_components/action-button.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/_components/action-button.tsxindex 9b1bf2a00..ebb761017 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/_components/action-button.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/_components/action-button.tsx@@ -41,7 +41,7 @@ export function ActionButton({ page }: ActionButtonProps) {startTransition(async () => {try {if (!page.id) return;- await api.page.deletePage.mutate({ id: page.id });+ await api.page.delete.mutate({ id: page.id });toast("deleted");router.refresh();setAlertOpen(false);diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/edit/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/edit/page.tsxindex 86f1f0124..4a3a1330a 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/edit/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/edit/page.tsx@@ -30,16 +30,11 @@ export default async function EditPage({}const { id } = search.data;- const { workspaceSlug } = params;// TODO: too many requests to db- const page = id && (await api.page.getPageByID.query({ id }));- const monitors = await api.monitor.getMonitorsByWorkspace.query({- workspaceSlug,- });- const workspace = await api.workspace.getWorkspace.query({- slug: workspaceSlug,- });+ const page = id ? await api.page.getPageById.query({ id }) : undefined;+ const monitors = await api.monitor.getMonitorsByWorkspace.query();+ const workspace = await api.workspace.getWorkspace.query();const isProPlan = workspace?.plan === "pro";@@ -67,12 +62,10 @@ export default async function EditPage({<TabsContent value="settings" className="pt-3"><StatusPageFormallMonitors={monitors}- workspaceSlug={params.workspaceSlug}defaultValues={page? {...page,- workspaceSlug: params.workspaceSlug,monitors: page.monitorsToPages.map(({ monitor }) => monitor.id,),diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/page.tsxindex 80a57d834..bae99ec96 100644--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/page.tsx+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/status-pages/page.tsx@@ -20,16 +20,10 @@ export default async function Page({}: {params: { workspaceSlug: string };}) {- const pages = await api.page.getPagesByWorkspace.query({- workspaceSlug: params.workspaceSlug,- });- const monitors = await api.monitor.getMonitorsByWorkspace.query({- workspaceSlug: params.workspaceSlug,- });+ const pages = await api.page.getPagesByWorkspace.query();+ const monitors = await api.monitor.getMonitorsByWorkspace.query();- const workspace = await api.workspace.getWorkspace.query({- slug: params.workspaceSlug,- });+ const workspace = await api.workspace.getWorkspace.query();const isLimit =(pages?.length || 0) >=diff --git a/apps/web/src/app/app/(dashboard)/onboarding/page.tsx b/apps/web/src/app/app/(dashboard)/onboarding/page.tsxindex 68dab602f..07bf09974 100644--- a/apps/web/src/app/app/(dashboard)/onboarding/page.tsx+++ b/apps/web/src/app/app/(dashboard)/onboarding/page.tsx@@ -45,9 +45,7 @@ export default async function Onboarding({);}- const allMonitors = await api.monitor.getMonitorsByWorkspace.query({- workspaceSlug,- });+ const allMonitors = await api.monitor.getMonitorsByWorkspace.query();if (!monitorId) {return (@@ -63,7 +61,7 @@ export default async function Onboarding({/><div className="grid h-full w-full gap-6 md:grid-cols-3 md:gap-8"><div className="md:col-span-2">- <MonitorForm {...{ workspaceSlug }} />+ <MonitorForm /></div><div className="hidden h-full md:col-span-1 md:block"><Description step="monitor" />diff --git a/apps/web/src/components/data-table/monitor/data-table-row-actions.tsx b/apps/web/src/components/data-table/monitor/data-table-row-actions.tsxindex 577e2a139..562b8a544 100644--- a/apps/web/src/components/data-table/monitor/data-table-row-actions.tsx+++ b/apps/web/src/components/data-table/monitor/data-table-row-actions.tsx@@ -6,7 +6,7 @@ import { useRouter } from "next/navigation";import type { Row } from "@tanstack/react-table";import { MoreHorizontal } from "lucide-react";-import { insertMonitorSchema } from "@openstatus/db/src/schema";+import { selectMonitorSchema } from "@openstatus/db/src/schema";import {AlertDialog,AlertDialogAction,@@ -36,7 +36,7 @@ interface DataTableRowActionsProps<TData> {export function DataTableRowActions<TData>({row,}: DataTableRowActionsProps<TData>) {- const monitor = insertMonitorSchema.parse(row.original);+ const monitor = selectMonitorSchema.parse(row.original);const router = useRouter();const { toast } = useToastAction();const [alertOpen, setAlertOpen] = React.useState(false);@@ -46,7 +46,7 @@ export function DataTableRowActions<TData>({startTransition(async () => {try {if (!monitor.id) return;- await api.monitor.deleteMonitor.mutate({ id: monitor.id });+ await api.monitor.delete.mutate({ id: monitor.id });toast("deleted");router.refresh();setAlertOpen(false);@@ -61,7 +61,7 @@ export function DataTableRowActions<TData>({try {const { jobType, ...rest } = monitor;if (!monitor.id) return;- await api.monitor.updateMonitor.mutate({+ await api.monitor.update.mutate({...rest,active: !monitor.active,});diff --git a/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx b/apps/web/src/components/data-table/status-page/data-table-row-actions.tsxindex 0ec22df29..4cfb8e1d1 100644--- a/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx+++ b/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx@@ -45,7 +45,7 @@ export function DataTableRowActions<TData>({startTransition(async () => {try {if (!page.id) return;- await api.page.deletePage.mutate({ id: page.id });+ await api.page.delete.mutate({ id: page.id });toast("deleted");router.refresh();setAlertOpen(false);diff --git a/apps/web/src/components/forms/incident-form.tsx b/apps/web/src/components/forms/incident-form.tsxindex 2126f35fd..48f84a75b 100644--- a/apps/web/src/components/forms/incident-form.tsx+++ b/apps/web/src/components/forms/incident-form.tsx@@ -48,15 +48,9 @@ interface Props {defaultValues?: InsertIncident;monitors?: Monitor[];pages?: Page[];- workspaceSlug: string;}-export function IncidentForm({- defaultValues,- monitors,- pages,- workspaceSlug,-}: Props) {+export function IncidentForm({ defaultValues, monitors, pages }: Props) {const form = useForm<InsertIncident>({resolver: zodResolver(insertIncidentSchema),defaultValues: defaultValues@@ -66,7 +60,6 @@ export function IncidentForm({status: defaultValues.status,monitors: defaultValues.monitors,pages: defaultValues.pages,- workspaceSlug,// include update on creationmessage: defaultValues.message,date: defaultValues.date,@@ -74,7 +67,6 @@ export function IncidentForm({: {status: "investigating",date: new Date(),- workspaceSlug,},});const router = useRouter();@@ -88,9 +80,8 @@ export function IncidentForm({await api.incident.updateIncident.mutate({ ...props });} else {// or use createIncident to create automaticaaly an IncidentUpdate?- const { message, date, status, workspaceSlug, ...rest } = props;+ const { message, date, status, ...rest } = props;const incident = await api.incident.createIncident.mutate({- workspaceSlug,status,message,...rest,@@ -101,7 +92,6 @@ export function IncidentForm({message,date,status,- workspaceSlug,incidentId: incident.id,});}diff --git a/apps/web/src/components/forms/incident-update-form.tsx b/apps/web/src/components/forms/incident-update-form.tsxindex 6ef533455..d9d843271 100644--- a/apps/web/src/components/forms/incident-update-form.tsx+++ b/apps/web/src/components/forms/incident-update-form.tsx@@ -39,15 +39,10 @@ import { api } from "@/trpc/client";interface Props {defaultValues?: InsertIncidentUpdate;- workspaceSlug: string;incidentId: number;}-export function IncidentUpdateForm({- defaultValues,- workspaceSlug,- incidentId,-}: Props) {+export function IncidentUpdateForm({ defaultValues, incidentId }: Props) {const form = useForm<InsertIncidentUpdate>({resolver: zodResolver(insertIncidentUpdateSchema),defaultValues: {@@ -56,7 +51,6 @@ export function IncidentUpdateForm({message: defaultValues?.message,date: defaultValues?.date || new Date(),incidentId,- workspaceSlug,},});const router = useRouter();diff --git a/apps/web/src/components/forms/monitor-form.tsx b/apps/web/src/components/forms/monitor-form.tsxindex 04ca73188..fee802013 100644--- a/apps/web/src/components/forms/monitor-form.tsx+++ b/apps/web/src/components/forms/monitor-form.tsx@@ -81,14 +81,12 @@ const cronJobs = [interface Props {defaultValues?: InsertMonitor;- workspaceSlug: string;plan?: WorkspacePlan;notifications?: Notification[];}export function MonitorForm({defaultValues,- workspaceSlug,plan = "free",notifications,}: Props) {@@ -100,7 +98,7 @@ export function MonitorForm({description: defaultValues?.description || "",periodicity: defaultValues?.periodicity || "30m",active: defaultValues?.active ?? true,- id: defaultValues?.id || undefined,+ id: defaultValues?.id || 0,regions:defaultValues?.regions || (flyRegions as Writeable<typeof flyRegions>),headers: Boolean(defaultValues?.headers?.length)@@ -128,12 +126,9 @@ export function MonitorForm({const handleDataUpdateOrInsertion = async (props: InsertMonitor) => {try {if (defaultValues) {- await api.monitor.updateMonitor.mutate(props);+ await api.monitor.update.mutate(props);} else {- const monitor = await api.monitor.createMonitor.mutate({- data: props,- workspaceSlug,- });+ const monitor = await api.monitor.create.mutate(props);const id = monitor?.id || null;router.replace(`?${updateSearchParams({ id })}`);}@@ -707,10 +702,7 @@ export function MonitorForm({Get alerted when your endpoint is down.</DialogDescription></DialogHeader>- <NotificationForm- onSubmit={() => setOpenDialog(false)}- {...{ workspaceSlug }}- />+ <NotificationForm onSubmit={() => setOpenDialog(false)} /></DialogContent><FailedPingAlertConfirmationmonitor={form.getValues()}diff --git a/apps/web/src/components/forms/notification-form.tsx b/apps/web/src/components/forms/notification-form.tsxindex 7be6a419c..c549d2c02 100644--- a/apps/web/src/components/forms/notification-form.tsx+++ b/apps/web/src/components/forms/notification-form.tsx@@ -86,12 +86,10 @@ function getProviderMetaData(provider: NotificationProvider) {interface Props {defaultValues?: InsertNotification;- workspaceSlug: string;onSubmit?: () => void;}export function NotificationForm({- workspaceSlug,defaultValues,onSubmit: onExternalSubmit,}: Props) {@@ -118,14 +116,13 @@ export function NotificationForm({startTransition(async () => {try {if (defaultValues) {- await api.notification.updateNotification.mutate({+ await api.notification.update.mutate({provider,data: JSON.stringify(setProviderData(provider, data)),...rest,});} else {- await api.notification.createNotification.mutate({- workspaceSlug,+ await api.notification.create.mutate({provider,data: JSON.stringify(setProviderData(provider, data)),...rest,diff --git a/apps/web/src/components/forms/status-page-form.tsx b/apps/web/src/components/forms/status-page-form.tsxindex 4d7e3b868..7a94940f6 100644--- a/apps/web/src/components/forms/status-page-form.tsx+++ b/apps/web/src/components/forms/status-page-form.tsx@@ -36,11 +36,8 @@ import { slugify } from "@/lib/utils";import { api } from "@/trpc/client";import { LoadingAnimation } from "../loading-animation";-// REMINDER: only use the props you need!-interface Props {defaultValues?: InsertPage;- workspaceSlug: string;allMonitors?: Monitor[];/*** gives the possibility to check all the monitors@@ -54,7 +51,6 @@ interface Props {export function StatusPageForm({defaultValues,- workspaceSlug,allMonitors,checkAllMonitors,nextUrl,@@ -73,7 +69,6 @@ export function StatusPageForm({? allMonitors.map(({ id }) => id): defaultValues?.monitors ?? [],customDomain: defaultValues?.customDomain || "",- workspaceSlug: "",icon: defaultValues?.icon || "",},});@@ -121,18 +116,15 @@ export function StatusPageForm({const onSubmit = async ({ ...props }: InsertPage) => {startTransition(async () => {- // TODO: we could use an upsertPage function instead - insert if not exist otherwise updatetry {if (defaultValues) {- await api.page.updatePage.mutate(props);+ await api.page.update.mutate(props);} else {- const page = await api.page.createPage.mutate({- ...props,- workspaceSlug,- });+ const page = await api.page.create.mutate(props);const id = page?.id || null;router.replace(`?${updateSearchParams({ id })}`); // to stay on same page and enable 'Advanced' tab}+defaultToast({title: "Saved successfully.",description: "Your status page is ready to go.",diff --git a/apps/web/src/components/marketing/stats.tsx b/apps/web/src/components/marketing/stats.tsxindex 5642ae2ce..db5d0cbc0 100644--- a/apps/web/src/components/marketing/stats.tsx+++ b/apps/web/src/components/marketing/stats.tsx@@ -6,7 +6,7 @@ import { api } from "@/trpc/server";export async function Stats() {const tbTotalStats = await getHomeStatsData({});const tbLastHourStats = await getHomeStatsData({ period: "1h" });- // FIXME:+ // FIXME: is it time?// const totalActiveMonitors = await api.monitor.getTotalActiveMonitors.query(// {},// );diff --git a/apps/web/src/components/modals/notification-dialog.tsx b/apps/web/src/components/modals/notification-dialog.tsxindex 4aff971e5..21d35dfe6 100644--- a/apps/web/src/components/modals/notification-dialog.tsx+++ b/apps/web/src/components/modals/notification-dialog.tsx@@ -34,10 +34,7 @@ export const NotificationDialog = ({Get alerted when your endpoint is down.</DialogDescription></DialogHeader>- <NotificationForm- onSubmit={() => setOpen(false)}- {...{ workspaceSlug }}- />+ <NotificationForm onSubmit={() => setOpen(false)} /></DialogContent></Dialog>);diff --git a/packages/api/src/analytics.ts b/packages/api/src/analytics.tsnew file mode 100644index 000000000..974f00330--- /dev/null+++ b/packages/api/src/analytics.ts@@ -0,0 +1,47 @@+import { analytics, trackAnalytics } from "@openstatus/analytics";+import { User } from "@openstatus/db/src/schema";++export async function trackNewPage(user: User, config: { slug: string }) {+ await analytics.identify(user.id, {+ userId: user.id,+ email: user.email,+ });+ await trackAnalytics({+ event: "Page Created",+ ...config,+ });+}++export async function trackNewMonitor(+ user: User,+ config: { url: string; periodicity: string },+) {+ await analytics.identify(user.id, {+ userId: user.id,+ email: user.email,+ });+ await trackAnalytics({+ event: "Monitor Created",+ ...config,+ });+}++export async function trackNewUser() {}++export async function trackNewWorkspace() {}++export async function trackNewNotification(+ user: User,+ config: { provider: string },+) {+ await analytics.identify(user.id, {+ userId: user.id,+ email: user.email,+ });+ await trackAnalytics({+ event: "Notification Created",+ ...config,+ });+}++export async function trackNewIncident() {}diff --git a/packages/api/src/router/incident.ts b/packages/api/src/router/incident.tsindex 664f65092..1898af726 100644--- a/packages/api/src/router/incident.ts+++ b/packages/api/src/router/incident.ts@@ -12,56 +12,27 @@ import {selectIncidentSchema,selectIncidentUpdateSchema,selectMonitorSchema,- user,- usersToWorkspaces,- workspace,} from "@openstatus/db/src/schema";import { createTRPCRouter, protectedProcedure } from "../trpc";-import { hasUserAccessToWorkspace } from "./utils";export const incidentRouter = createTRPCRouter({createIncident: protectedProcedure.input(insertIncidentSchema).mutation(async (opts) => {- const result = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,- });- if (!result) return;-- const {- id,- workspaceSlug,- monitors,- pages,- date,- message,- ...incidentInput- } = opts.input;+ const { id, monitors, pages, date, message, ...incidentInput } =+ opts.input;const newIncident = await opts.ctx.db.insert(incident).values({- workspaceId: result.workspace.id,+ workspaceId: opts.ctx.workspace.id,...incidentInput,}).returning().get();- // if (monitors && monitors.length > 0) {- // // We should make sure the user has access to the monitors- // const allMonitors = await opts.ctx.db.query.monitor.findMany({- // where: inArray(monitor.id, monitors),- // });- // const values = allMonitors.map((monitor) => ({- // monitorId: monitor.id,- // incidentId: newIncident.id,- // }));- // await opts.ctx.db.insert(monitorsToIncidents).values(values).run();- // }-- if (monitors.length > 0) {+ if (Boolean(monitors.length)) {await opts.ctx.db.insert(monitorsToIncidents).values(@@ -74,7 +45,7 @@ export const incidentRouter = createTRPCRouter({.get();}- if (pages.length > 0) {+ if (Boolean(pages.length)) {await opts.ctx.db.insert(pagesToIncidents).values(@@ -93,22 +64,20 @@ export const incidentRouter = createTRPCRouter({createIncidentUpdate: protectedProcedure.input(insertIncidentUpdateSchema).mutation(async (opts) => {- // Check if user has access to workspace- const data = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,- });- if (!data) return;-// update parent incident with latest statusawait opts.ctx.db.update(incident).set({ status: opts.input.status, updatedAt: new Date() })- .where(eq(incident.id, opts.input.incidentId))+ .where(+ and(+ eq(incident.id, opts.input.incidentId),+ eq(incident.workspaceId, opts.ctx.workspace.id),+ ),+ ).returning().get();- const { workspaceSlug, id, ...incidentUpdateInput } = opts.input;+ const { id, ...incidentUpdateInput } = opts.input;return await opts.ctx.db.insert(incidentUpdate).values(incidentUpdateInput)@@ -119,13 +88,7 @@ export const incidentRouter = createTRPCRouter({updateIncident: protectedProcedure.input(insertIncidentSchema).mutation(async (opts) => {- const data = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,- });- if (!data) return;-- const { monitors, pages, workspaceSlug, ...incidentInput } = opts.input;+ const { monitors, pages, ...incidentInput } = opts.input;if (!incidentInput.id) return;@@ -134,7 +97,12 @@ export const incidentRouter = createTRPCRouter({const currentIncident = await opts.ctx.db.update(incident).set({ title, status, updatedAt: new Date() })- .where(eq(incident.id, incidentInput.id))+ .where(+ and(+ eq(incident.id, incidentInput.id),+ eq(incident.workspaceId, opts.ctx.workspace.id),+ ),+ ).returning().get();@@ -144,19 +112,14 @@ export const incidentRouter = createTRPCRouter({.where(eq(monitorsToIncidents.incidentId, currentIncident.id)).all();- const currentMonitorToIncidentsIds = currentMonitorToIncidents.map(- ({ monitorId }) => monitorId,- );-- const removedMonitors = currentMonitorToIncidentsIds.filter(- (x) => !monitors?.includes(x),+ const addedMonitors = monitors.filter(+ (x) =>+ !currentMonitorToIncidents+ .map(({ monitorId }) => monitorId)+ .includes(x),);- const addedMonitors = monitors?.filter(- (x) => !currentMonitorToIncidentsIds?.includes(x),- );-- if (addedMonitors && addedMonitors.length > 0) {+ if (Boolean(addedMonitors.length)) {const values = addedMonitors.map((monitorId) => ({monitorId: monitorId,incidentId: currentIncident.id,@@ -165,7 +128,11 @@ export const incidentRouter = createTRPCRouter({await opts.ctx.db.insert(monitorsToIncidents).values(values).run();}- if (removedMonitors && removedMonitors.length > 0) {+ const removedMonitors = currentMonitorToIncidents+ .map(({ monitorId }) => monitorId)+ .filter((x) => !monitors?.includes(x));++ if (Boolean(removedMonitors.length)) {await opts.ctx.db.delete(monitorsToIncidents).where(@@ -183,19 +150,12 @@ export const incidentRouter = createTRPCRouter({.where(eq(pagesToIncidents.incidentId, currentIncident.id)).all();- const currentPagesToIncidentsIds = currentPagesToIncidents.map(- ({ pageId }) => pageId,- );-- const removedPages = currentPagesToIncidentsIds.filter(- (x) => !pages?.includes(x),- );-const addedPages = pages?.filter(- (x) => !currentPagesToIncidentsIds?.includes(x),+ (x) =>+ !currentPagesToIncidents.map(({ pageId }) => pageId)?.includes(x),);- if (addedPages && addedPages.length > 0) {+ if (Boolean(addedPages.length)) {const values = addedPages.map((pageId) => ({pageId,incidentId: currentIncident.id,@@ -204,7 +164,11 @@ export const incidentRouter = createTRPCRouter({await opts.ctx.db.insert(pagesToIncidents).values(values).run();}- if (removedPages && removedPages.length > 0) {+ const removedPages = currentPagesToIncidents+ .map(({ pageId }) => pageId)+ .filter((x) => !pages?.includes(x));++ if (Boolean(removedPages.length)) {await opts.ctx.db.delete(pagesToIncidents).where(@@ -222,27 +186,7 @@ export const incidentRouter = createTRPCRouter({updateIncidentUpdate: protectedProcedure.input(insertIncidentUpdateSchema).mutation(async (opts) => {- const currentWorkspace = await opts.ctx.db- .select()- .from(workspace)- .where(eq(workspace.slug, opts.input.workspaceSlug))- .get();- if (!currentWorkspace) return;- const currentUser = opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .as("currentUser");- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.workspaceId, currentWorkspace.id))- .innerJoin(currentUser, eq(usersToWorkspaces.userId, currentUser.id))- .get();-- if (!result) return;-- const { workspaceSlug, ...incidentUpdateInput } = opts.input;+ const incidentUpdateInput = opts.input;if (!incidentUpdateInput.id) return;@@ -259,28 +203,13 @@ export const incidentRouter = createTRPCRouter({deleteIncident: protectedProcedure.input(z.object({ id: z.number() })).mutation(async (opts) => {- // TODO: this looks not very affective- const currentUser = await opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .get();- if (!currentUser) return;- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.userId, currentUser.id))- .all();-- const workspaceIds = result.map((workspace) => workspace.workspaceId);-const incidentToDelete = await opts.ctx.db.select().from(incident).where(and(eq(incident.id, opts.input.id),- inArray(incident.workspaceId, workspaceIds),+ eq(incident.workspaceId, opts.ctx.workspace.id),),).get();@@ -295,20 +224,6 @@ export const incidentRouter = createTRPCRouter({deleteIncidentUpdate: protectedProcedure.input(z.object({ id: z.number() })).mutation(async (opts) => {- const currentUser = await opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .get();- if (!currentUser) return;- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.userId, currentUser.id))- .all();-- const workspaceIds = result.map((workspace) => workspace.workspaceId);-const incidentUpdateToDelete = await opts.ctx.db.select().from(incidentUpdate)@@ -341,7 +256,10 @@ export const incidentRouter = createTRPCRouter({});const data = await opts.ctx.db.query.incident.findFirst({- where: eq(incident.id, opts.input.id),+ where: and(+ eq(incident.id, opts.input.id),+ eq(incident.workspaceId, opts.ctx.workspace.id),+ ),with: {monitorsToIncidents: true,pagesToIncidents: true,@@ -360,47 +278,40 @@ export const incidentRouter = createTRPCRouter({.input(z.object({ id: z.number() })).query(async (opts) => {const data = await opts.ctx.db.query.incidentUpdate.findFirst({- where: eq(incidentUpdate.id, opts.input.id),+ where: and(eq(incidentUpdate.id, opts.input.id)),});return selectIncidentUpdateSchema.parse(data);}),- getIncidentByWorkspace: protectedProcedure- .input(z.object({ workspaceSlug: z.string() }))- .query(async (opts) => {- const data = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,- });- if (!data) return;-- const selectIncidentSchemaWithRelation = selectIncidentSchema.extend({- status: incidentStatusSchema.default("investigating"), // TODO: remove!- monitorsToIncidents: z- .array(- z.object({- incidentId: z.number(),- monitorId: z.number(),- monitor: selectMonitorSchema,- }),- )- .default([]),- incidentUpdates: z.array(selectIncidentUpdateSchema),- });-- const result = await opts.ctx.db.query.incident.findMany({- where: eq(incident.workspaceId, data.workspace.id),- with: {- monitorsToIncidents: { with: { monitor: true } },- incidentUpdates: {- orderBy: (incidentUpdate, { desc }) => [- desc(incidentUpdate.createdAt),- ],- },+ getIncidentByWorkspace: protectedProcedure.query(async (opts) => {+ // FIXME: can we get rid of that?+ const selectIncidentSchemaWithRelation = selectIncidentSchema.extend({+ status: incidentStatusSchema.default("investigating"), // TODO: remove!+ monitorsToIncidents: z+ .array(+ z.object({+ incidentId: z.number(),+ monitorId: z.number(),+ monitor: selectMonitorSchema,+ }),+ )+ .default([]),+ incidentUpdates: z.array(selectIncidentUpdateSchema),+ });++ const result = await opts.ctx.db.query.incident.findMany({+ where: eq(incident.workspaceId, opts.ctx.workspace.id),+ with: {+ monitorsToIncidents: { with: { monitor: true } },+ incidentUpdates: {+ orderBy: (incidentUpdate, { desc }) => [+ desc(incidentUpdate.createdAt),+ ],},- orderBy: (incident, { desc }) => [desc(incident.updatedAt)],- });+ },+ orderBy: (incident, { desc }) => [desc(incident.updatedAt)],+ });- return z.array(selectIncidentSchemaWithRelation).parse(result);- }),+ return z.array(selectIncidentSchemaWithRelation).parse(result);+ }),});diff --git a/packages/api/src/router/integration.ts b/packages/api/src/router/integration.tsindex ec5e27907..7ed0434db 100644--- a/packages/api/src/router/integration.ts+++ b/packages/api/src/router/integration.ts@@ -1,13 +1,12 @@import { z } from "zod";-import { and, eq, inArray } from "@openstatus/db";+import { and, eq } from "@openstatus/db";import {insertIntegrationSchema,integration,} from "@openstatus/db/src/schema";import { createTRPCRouter, protectedProcedure } from "../trpc";-import { hasUserAccessToWorkspace } from "./utils";export const integrationRouter = createTRPCRouter({createIntegration: protectedProcedure@@ -15,18 +14,12 @@ export const integrationRouter = createTRPCRouter({z.object({ workspaceSlug: z.string(), input: insertIntegrationSchema }),).mutation(async (opts) => {- const result = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,- });- if (!result) return;-const exists = await opts.ctx.db.select().from(integration).where(and(- eq(integration.workspaceId, result.workspace.id),+ eq(integration.workspaceId, opts.ctx.workspace.id),eq(integration.externalId, opts.input.input.externalId),),)@@ -37,7 +30,7 @@ export const integrationRouter = createTRPCRouter({}await opts.ctx.db.insert(integration)- .values({ ...opts.input.input, workspaceId: result.workspace.id })+ .values({ ...opts.input.input, workspaceId: opts.ctx.workspace.id }).returning().get();}),diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.tsindex 101698eb7..49fd0c32e 100644--- a/packages/api/src/router/monitor.ts+++ b/packages/api/src/router/monitor.ts@@ -1,12 +1,10 @@import { TRPCError } from "@trpc/server";import { z } from "zod";-import { analytics, trackAnalytics } from "@openstatus/analytics";import { and, eq, inArray, sql } from "@openstatus/db";import {insertMonitorSchema,monitor,- monitorMethodsSchema,monitorPeriodicitySchema,monitorsToPages,notification,@@ -16,26 +14,21 @@ import {} from "@openstatus/db/src/schema";import { allPlans } from "@openstatus/plans";+import { trackNewMonitor } from "../analytics";import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";-import { hasUserAccessToMonitor, hasUserAccessToWorkspace } from "./utils";export const monitorRouter = createTRPCRouter({- createMonitor: protectedProcedure- .input(z.object({ data: insertMonitorSchema, workspaceSlug: z.string() }))+ create: protectedProcedure+ .input(insertMonitorSchema)+ .output(selectMonitorSchema).mutation(async (opts) => {- const result = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,- });-- if (!result) return;-- const monitorLimit = result.plan.limits.monitors;- const periodicityLimit = result.plan.limits.periodicity;+ const monitorLimit = allPlans[opts.ctx.workspace.plan].limits.monitors;+ const periodicityLimit =+ allPlans[opts.ctx.workspace.plan].limits.periodicity;const monitorNumbers = (await opts.ctx.db.query.monitor.findMany({- where: eq(monitor.workspaceId, result.workspace.id),+ where: eq(monitor.workspaceId, opts.ctx.workspace.id),})).length;@@ -49,80 +42,77 @@ export const monitorRouter = createTRPCRouter({// the user is not allowed to use the cron jobif (- opts.input.data?.periodicity &&- !periodicityLimit.includes(opts.input.data?.periodicity)+ opts.input.periodicity &&+ !periodicityLimit.includes(opts.input.periodicity)) {throw new TRPCError({code: "FORBIDDEN",message: "You reached your cron job limits.",});}+// FIXME: this is a hotfix- const { regions, headers, notifications, ...data } = opts.input.data;+ const { regions, headers, notifications, id, ...data } = opts.input;const newMonitor = await opts.ctx.db.insert(monitor).values({+ // REMINDER: We should explicitly pass the corresponding attributes+ // otherwise, unexpected attributes will be passed...data,- workspaceId: result.workspace.id,+ workspaceId: opts.ctx.workspace.id,regions: regions?.join(","),headers: headers ? JSON.stringify(headers) : undefined,}).returning().get();- if (notifications && notifications.length > 0) {+ if (Boolean(notifications.length)) {+ // We should make sure the user has access to the notificationsconst 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 analytics- await analytics.identify(result.user.id, {- userId: result.user.id,- email: result.user.email,- });- await trackAnalytics({- event: "Monitor Created",+ trackNewMonitor(opts.ctx.user, {url: newMonitor.url,periodicity: newMonitor.periodicity,});- return newMonitor;++ return selectMonitorSchema.parse(newMonitor);}),- getMonitorByID: protectedProcedure+ getMonitorById: protectedProcedure.input(z.object({ id: z.number() }))- // .output(selectMonitorSchema)+ .output(selectMonitorSchema) // REMINDER: use more!.query(async (opts) => {- if (!opts.input.id) return;- const result = await hasUserAccessToMonitor({- monitorId: opts.input.id,- ctx: opts.ctx,- });- if (!result) return;-- const _monitor = selectMonitorSchema.parse(result.monitor);- return _monitor;+ const currentMonitor = await opts.ctx.db+ .select()+ .from(monitor)+ .where(+ and(+ eq(monitor.id, opts.input.id),+ eq(monitor.workspaceId, opts.ctx.workspace.id),+ ),+ )+ .get();+ return selectMonitorSchema.parse(currentMonitor);}),- updateMonitor: protectedProcedure+ update: protectedProcedure.input(insertMonitorSchema).mutation(async (opts) => {if (!opts.input.id) return;- const result = await hasUserAccessToMonitor({- monitorId: opts.input.id,- ctx: opts.ctx,- });- if (!result) return;- const plan = (result.workspace?.plan || "free") as "free" | "pro";-- const periodicityLimit = allPlans[plan].limits.periodicity;+ const periodicityLimit =+ allPlans[opts.ctx.workspace.plan].limits.periodicity;// the user is not allowed to use the cron jobif (@@ -134,7 +124,9 @@ export const monitorRouter = createTRPCRouter({message: "You reached your cron job limits.",});}+const { regions, headers, notifications, ...data } = opts.input;+const currentMonitor = await opts.ctx.db.update(monitor).set({@@ -143,30 +135,29 @@ export const monitorRouter = createTRPCRouter({updatedAt: new Date(),headers: headers ? JSON.stringify(headers) : undefined,})- .where(eq(monitor.id, opts.input.id))+ .where(+ and(+ eq(monitor.id, opts.input.id),+ eq(monitor.workspaceId, opts.ctx.workspace.id),+ ),+ ).returning().get();- // 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),+ const addedNotifications = notifications.filter(+ (x) =>+ !currentMonitorNotifications+ .map(({ notificationId }) => notificationId)+ ?.includes(x),);- if (addedNotifications && addedNotifications.length > 0) {+ if (Boolean(addedNotifications.length)) {const values = addedNotifications.map((notificationId) => ({monitorId: currentMonitor.id,notificationId,@@ -175,7 +166,11 @@ export const monitorRouter = createTRPCRouter({await opts.ctx.db.insert(notificationsToMonitors).values(values).run();}- if (removedNotifications && removedNotifications.length > 0) {+ const removedNotifications = currentMonitorNotifications+ .map(({ notificationId }) => notificationId)+ .filter((x) => !notifications?.includes(x));++ if (Boolean(removedNotifications.length)) {await opts.ctx.db.delete(notificationsToMonitors).where(@@ -191,74 +186,37 @@ export const monitorRouter = createTRPCRouter({}}),- deleteMonitor: protectedProcedure+ delete: protectedProcedure.input(z.object({ id: z.number() })).mutation(async (opts) => {- const result = await hasUserAccessToMonitor({- monitorId: opts.input.id,- ctx: opts.ctx,- });- if (!result) return;+ const monitorToDelete = await opts.ctx.db+ .select()+ .from(monitor)+ .where(+ and(+ eq(monitor.id, opts.input.id),+ eq(monitor.workspaceId, opts.ctx.workspace.id),+ ),+ )+ .get();+ if (!monitorToDelete) return;+await opts.ctx.db.delete(monitor)- .where(eq(monitor.id, result.monitor.id))+ .where(eq(monitor.id, monitorToDelete.id)).run();}),getMonitorsByWorkspace: protectedProcedure- .input(z.object({ workspaceSlug: z.string() }))+ .output(z.array(selectMonitorSchema)).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 monitors = await opts.ctx.db.select().from(monitor)- .where(eq(monitor.workspaceId, data.workspace.id))+ .where(eq(monitor.workspaceId, opts.ctx.workspace.id)).all();- // const selectMonitorsArray = selectMonitorSchema.array();- try {- return z.array(selectMonitorSchema).parse(monitors);- } catch (e) {- console.log(e);- }- return;- }),-- updateMonitorAdvanced: protectedProcedure- .input(- z.object({- id: z.number(),- method: monitorMethodsSchema.default("GET"),- body: z.string().default("").optional(),- headers: z- .array(z.object({ key: z.string(), value: z.string() }))- .transform((val) => JSON.stringify(val))- .default([])- .optional(),- }),- )- .mutation(async (opts) => {- const result = await hasUserAccessToMonitor({- monitorId: opts.input.id,- ctx: opts.ctx,- });- if (!result) return;- await opts.ctx.db- .update(monitor)- .set({- method: opts.input.method,- body: opts.input.body,- headers: opts.input.headers,- })- .where(eq(monitor.id, opts.input.id))- .run();+ return z.array(selectMonitorSchema).parse(monitors);}),getMonitorsForPeriodicity: protectedProcedure@@ -288,36 +246,31 @@ export const monitorRouter = createTRPCRouter({return allPages;}),- getTotalActiveMonitors: publicProcedure- .input(z.object({}))- .query(async (opts) => {- const monitors = await opts.ctx.db- .select({ count: sql<number>`count(*)` })- .from(monitor)- .where(eq(monitor.active, true))- .all();- 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+ // rename to getActiveMonitorsCount+ getTotalActiveMonitors: publicProcedure.query(async (opts) => {+ const monitors = await opts.ctx.db+ .select({ count: sql<number>`count(*)` })+ .from(monitor)+ .where(eq(monitor.active, true))+ .all();+ 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 pagegetAllNotificationsForMonitor: 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),+ and(+ eq(notificationsToMonitors.notificationId, notification.id),+ eq(notification.workspaceId, opts.ctx.workspace.id),+ ),).where(eq(notificationsToMonitors.monitorId, opts.input.id)).all();diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.tsindex 2acb0d77d..38eecb79b 100644--- a/packages/api/src/router/notification.ts+++ b/packages/api/src/router/notification.ts@@ -1,65 +1,47 @@import { z } from "zod";-import { analytics, trackAnalytics } from "@openstatus/analytics";-import { eq } from "@openstatus/db";+import { and, eq } from "@openstatus/db";import {insertNotificationSchema,notification,selectNotificationSchema,} from "@openstatus/db/src/schema";+import { trackNewNotification } from "../analytics";import { createTRPCRouter, protectedProcedure } from "../trpc";-import { hasUserAccessToNotification, hasUserAccessToWorkspace } from "./utils";export const notificationRouter = createTRPCRouter({- createNotification: protectedProcedure- .input(- insertNotificationSchema.extend({- workspaceSlug: z.string(),- }),- )+ create: protectedProcedure+ .input(insertNotificationSchema).mutation(async (opts) => {- const { workspaceSlug, ...data } = opts.input;-- const result = await hasUserAccessToWorkspace({- workspaceSlug,- ctx: opts.ctx,- });- if (!result) return;+ const { ...data } = opts.input;const _notification = await opts.ctx.db.insert(notification)- .values({ ...data, workspaceId: result.workspace.id })+ .values({ ...data, workspaceId: opts.ctx.workspace.id }).returning().get();- await analytics.identify(result.user.id, {- userId: result.user.id,- email: result.user.email,- });- await trackAnalytics({- event: "Notification Created",- provider: _notification.provider,- });+ trackNewNotification(opts.ctx.user, { provider: _notification.provider });return _notification;}),- updateNotification: protectedProcedure+ update: 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))+ .where(+ and(+ eq(notification.id, opts.input.id),+ eq(notification.workspaceId, opts.ctx.workspace.id),+ ),+ ).returning().get();}),@@ -67,60 +49,41 @@ export const notificationRouter = createTRPCRouter({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))+ .where(+ and(+ eq(notification.id, opts.input.id),+ eq(notification.id, opts.input.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))+ .where(+ and(+ eq(notification.id, opts.input.id),+ 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,- });+ getNotificationsByWorkspace: protectedProcedure.query(async (opts) => {+ const notifications = await opts.ctx.db+ .select()+ .from(notification)+ .where(eq(notification.workspaceId, opts.ctx.workspace.id))+ .all();- if (!data) return;-- const notifications = await opts.ctx.db- .select()- .from(notification)- .where(eq(notification.workspaceId, data.workspace.id))- .all();-- try {- return z.array(selectNotificationSchema).parse(notifications);- } catch (e) {- console.log(e);- }- return;- }),+ return z.array(selectNotificationSchema).parse(notifications);+ }),});diff --git a/packages/api/src/router/page.test.ts b/packages/api/src/router/page.test.tsindex 85f987f77..a4bb48060 100644--- a/packages/api/src/router/page.test.ts+++ b/packages/api/src/router/page.test.ts@@ -8,14 +8,12 @@ test("Get Test Page", async () => {const ctx = createTRPCContext({// @ts-expect-errorreq: {},+ auth: {+ userId: "1",+ sessionId: "1",+ },});- // @ts-expect-error- ctx.auth = {- userId: "1",- sessionId: "1",- };-const caller = edgeRouter.createCaller(ctx);const result = await caller.page.getPageBySlug({ slug: "status" });expect(result).toMatchObject({@@ -50,14 +48,12 @@ test("No Page", async () => {const ctx = createTRPCContext({// @ts-expect-errorreq: {},+ auth: {+ userId: "1",+ sessionId: "1",+ },});- // @ts-expect-error- ctx.auth = {- userId: "1",- sessionId: "1",- };-const caller = edgeRouter.createCaller(ctx);const result = await caller.page.getPageBySlug({ slug: "Dont Exist" });expect(result).toBeUndefined();diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.tsindex 652d43ec1..547c9b25a 100644--- a/packages/api/src/router/page.ts+++ b/packages/api/src/router/page.ts@@ -1,7 +1,6 @@import { TRPCError } from "@trpc/server";import { z } from "zod";-import { analytics, trackAnalytics } from "@openstatus/analytics";import { and, eq, inArray, or, sql } from "@openstatus/db";import {incident,@@ -12,95 +11,66 @@ import {page,pagesToIncidents,selectPublicPageSchemaWithRelation,- user,- usersToWorkspaces,- workspace,} from "@openstatus/db/src/schema";+import { allPlans } from "@openstatus/plans";+import { trackNewPage } from "../analytics";import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";-import { hasUserAccessToWorkspace } from "./utils";-// TODO: deletePageById - updatePageByIdexport const pageRouter = createTRPCRouter({- createPage: protectedProcedure- .input(insertPageSchema)- .mutation(async (opts) => {- if (!opts.input.workspaceSlug) return;- const data = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.workspaceSlug,- ctx: opts.ctx,+ create: protectedProcedure.input(insertPageSchema).mutation(async (opts) => {+ const { monitors, workspaceId, id, ...pageProps } = opts.input;++ const pageNumbers = (+ await opts.ctx.db.query.page.findMany({+ where: eq(page.workspaceId, opts.ctx.workspace.id),+ })+ ).length;++ const limit = allPlans[opts.ctx.workspace.plan].limits["status-pages"];++ // the user has reached the limits+ if (pageNumbers >= limit) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You reached your status-page limits.",});- if (!data) return;-- const { monitors, workspaceId, workspaceSlug, id, ...pageInput } =- opts.input;-- const pageNumbers = (- await opts.ctx.db.query.page.findMany({- where: eq(page.workspaceId, data.workspace.id),- })- ).length;+ }- const limit = data.plan.limits["status-pages"];+ const newPage = await opts.ctx.db+ .insert(page)+ .values({ workspaceId: opts.ctx.workspace.id, ...pageProps })+ .returning()+ .get();- // the user has reached the limits- if (pageNumbers >= limit) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You reached your status-page limits.",- });- }+ if (Boolean(monitors.length)) {+ // We should make sure the user has access to the monitors+ const allMonitors = await opts.ctx.db.query.monitor.findMany({+ where: and(+ inArray(monitor.id, monitors),+ eq(monitor.workspaceId, opts.ctx.workspace.id),+ ),+ });- const newPage = await opts.ctx.db- .insert(page)- .values({ workspaceId: data.workspace.id, ...pageInput })- .returning()- .get();+ const values = allMonitors.map((monitor) => ({+ monitorId: monitor.id,+ pageId: newPage.id,+ }));- if (monitors && monitors.length > 0) {- // We should make sure the user has access to the monitors- const allMonitors = await opts.ctx.db.query.monitor.findMany({- where: inArray(monitor.id, monitors),- });- const values = allMonitors.map((monitor) => ({- monitorId: monitor.id,- pageId: newPage.id,- }));- await opts.ctx.db.insert(monitorsToPages).values(values).run();- }+ await opts.ctx.db.insert(monitorsToPages).values(values).run();+ }- // TODO: check, do we have to await for the two calls? Will slow down user response for our analytics- await analytics.identify(data.user.id, {- userId: data.user.id,- email: data.user.email,- });- await trackAnalytics({- event: "Page Created",- slug: newPage.slug,- });- return newPage;- }),+ trackNewPage(opts.ctx.user, { slug: newPage.slug });- getPageByID: protectedProcedure+ return newPage;+ }),+ getPageById: protectedProcedure.input(z.object({ id: z.number() })).query(async (opts) => {- const currentUser = await opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .get();- if (!currentUser) return;- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.userId, currentUser.id))- .all();- const workspaceIds = result.map((workspace) => workspace.workspaceId);-return await opts.ctx.db.query.page.findFirst({where: and(eq(page.id, opts.input.id),- inArray(page.workspaceId, workspaceIds),+ eq(page.workspaceId, opts.ctx.workspace.id),),with: {monitorsToPages: { with: { monitor: true } },@@ -108,151 +78,79 @@ export const pageRouter = createTRPCRouter({},});}),- updatePage: protectedProcedure- .input(insertPageSchema)- .mutation(async (opts) => {- if (!opts.input.id) return;- const currentUser = await opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .get();- if (!currentUser) return;- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.userId, currentUser.id))- .all();- const workspaceIds = result.map((workspace) => workspace.workspaceId);+ update: protectedProcedure.input(insertPageSchema).mutation(async (opts) => {+ const { monitors, ...pageInput } = opts.input;+ if (!pageInput.id) return;++ const currentPage = await opts.ctx.db+ .update(page)+ .set({ ...pageInput, updatedAt: new Date() })+ .where(+ and(+ eq(page.id, pageInput.id),+ eq(page.workspaceId, opts.ctx.workspace.id),+ ),+ )+ .returning()+ .get();- const pageToUpdate = await opts.ctx.db- .select()- .from(page)+ const currentMonitorsToPages = await opts.ctx.db+ .select()+ .from(monitorsToPages)+ .where(eq(monitorsToPages.pageId, currentPage.id))+ .all();++ const removedMonitors = currentMonitorsToPages+ .map(({ monitorId }) => monitorId)+ .filter((x) => !monitors?.includes(x));++ if (Boolean(removedMonitors.length)) {+ await opts.ctx.db+ .delete(monitorsToPages).where(and(- eq(page.id, opts.input.id),- inArray(page.workspaceId, workspaceIds),+ inArray(monitorsToPages.monitorId, removedMonitors),+ eq(monitorsToPages.pageId, currentPage.id),),- )- .get();- if (!pageToUpdate) return;-- const { monitors, workspaceSlug, ...pageInput } = opts.input;- if (!pageInput.id) return;- const currentPage = await opts.ctx.db- .update(page)- .set({ ...pageInput, updatedAt: new Date() })- .where(eq(page.id, pageInput.id))- .returning()- .get();-- // TODO: optimize!- const currentMonitorsToPages = await opts.ctx.db- .select()- .from(monitorsToPages)- .where(eq(monitorsToPages.pageId, currentPage.id))- .all();-- const currentMonitorsToPagesIds = currentMonitorsToPages.map(- ({ monitorId }) => monitorId,- );-- const removedMonitors = currentMonitorsToPagesIds.filter(- (x) => !monitors?.includes(x),- );-- const addedMonitors = monitors?.filter(- (x) => !currentMonitorsToPagesIds?.includes(x),- );-- if (addedMonitors && addedMonitors.length > 0) {- const values = addedMonitors.map((monitorId) => ({- monitorId: monitorId,- pageId: currentPage.id,- }));-- await opts.ctx.db.insert(monitorsToPages).values(values).run();- }-- if (removedMonitors && removedMonitors.length > 0) {- await opts.ctx.db- .delete(monitorsToPages)- .where(- and(- eq(monitorsToPages.pageId, currentPage.id),- inArray(monitorsToPages.monitorId, removedMonitors),- ),- )- .run();- }- }),- deletePage: protectedProcedure+ );+ }++ const addedMonitors = monitors.filter(+ (x) =>+ !currentMonitorsToPages.map(({ monitorId }) => monitorId)?.includes(x),+ );++ if (Boolean(addedMonitors.length)) {+ const values = addedMonitors.map((monitorId) => ({+ pageId: currentPage.id,+ monitorId,+ }));++ await opts.ctx.db.insert(monitorsToPages).values(values).run();+ }+ }),+ delete: protectedProcedure.input(z.object({ id: z.number() })).mutation(async (opts) => {- // TODO: this looks not very affective- const currentUser = await opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .get();- if (!currentUser) return;- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.userId, currentUser.id))- .all();- const workspaceIds = result.map((workspace) => workspace.workspaceId);- // two queries - can we reduce it?-- const pageToDelete = await opts.ctx.db- .select()- .from(page)+ await opts.ctx.db+ .delete(page).where(and(eq(page.id, opts.input.id),- inArray(page.workspaceId, workspaceIds),+ eq(page.workspaceId, opts.ctx.workspace.id),),)- .get();- if (!pageToDelete) return;-- await opts.ctx.db.delete(page).where(eq(page.id, pageToDelete.id)).run();- }),- getPagesByWorkspace: protectedProcedure- .input(z.object({ workspaceSlug: z.string() }))- .query(async (opts) => {- const currentUser = await opts.ctx.db- .select()- .from(user)- .where(eq(user.tenantId, opts.ctx.auth.userId))- .get();- if (!currentUser) return;- const currentWorkspace = await opts.ctx.db- .select()- .from(workspace)- .where(eq(workspace.slug, opts.input.workspaceSlug))- .get();- if (!currentWorkspace) return;- const result = await opts.ctx.db- .select()- .from(usersToWorkspaces)- .where(- and(- eq(usersToWorkspaces.userId, currentUser.id),- eq(usersToWorkspaces.workspaceId, currentWorkspace.id),- ),- )- .all();- if (!result) return;-- return opts.ctx.db.query.page.findMany({- where: and(eq(page.workspaceId, currentWorkspace.id)),- with: {- monitorsToPages: { with: { monitor: true } },- },- });+ .run();}),+ getPagesByWorkspace: protectedProcedure.query(async (opts) => {+ return opts.ctx.db.query.page.findMany({+ where: and(eq(page.workspaceId, opts.ctx.workspace.id)),+ with: {+ monitorsToPages: { with: { monitor: true } },+ },+ });+ }),// public if we use trpc hooks to get the page from the urlgetPageBySlug: publicProcedurediff --git a/packages/api/src/router/utils.ts b/packages/api/src/router/utils.tsdeleted file mode 100644index a8a9863f5..000000000--- a/packages/api/src/router/utils.ts+++ /dev/null@@ -1,144 +0,0 @@-import { eq } from "@openstatus/db";-import {- monitor,- notification,- user,- usersToWorkspaces,- workspace,-} from "@openstatus/db/src/schema";-import { allPlans } from "@openstatus/plans";--import { Context } from "../trpc";--/**- * Check if the user has access to the workspace, and return the workspace and user otherwise undefined- * @param workspaceSlug- * @param tenantId- * @param ctx - trpc context- * @returns {Promise<{ workspaceId: string; userId: string }> | undefined} - workspaceId and userId- */-export const hasUserAccessToWorkspace = async ({- workspaceSlug,- ctx,-}: {- workspaceSlug: string;- ctx: Context;-}) => {- if (!ctx.auth?.userId) return;- const currentUser = ctx.db- .select()- .from(user)- .where(eq(user.tenantId, ctx.auth?.userId))- .as("currentUser");-- const currentWorkspace = await ctx.db- .select()- .from(workspace)- .where(eq(workspace.slug, workspaceSlug))- .get();- if (!currentWorkspace) return;- const result = await ctx.db- .select()- .from(usersToWorkspaces)- .where(eq(usersToWorkspaces.workspaceId, currentWorkspace.id))- .innerJoin(currentUser, eq(usersToWorkspaces.userId, currentUser.id))- .get();- // the user doesn't have access to this workspace- if (!result || !result.users_to_workspaces) return;-- const plan = (currentWorkspace.plan || "free") as "free" | "pro"; // FIXME: that is a hotfix-- return {- workspace: currentWorkspace,- user: result.currentUser,- plan: allPlans[plan],- };-};--export const hasUserAccessToMonitor = async ({- monitorId,- ctx,-}: {- monitorId: number;- ctx: Context;-}) => {- if (!ctx.auth?.userId) return;-- const currentMonitor = await ctx.db- .select()- .from(monitor)- .where(eq(monitor.id, monitorId))- .get();- if (!currentMonitor || !currentMonitor.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, currentMonitor.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,- 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/api/src/router/workspace.test.ts b/packages/api/src/router/workspace.test.tsindex 3ffb6d9c2..24d111abf 100644--- a/packages/api/src/router/workspace.test.ts+++ b/packages/api/src/router/workspace.test.ts@@ -5,18 +5,21 @@ import { createTRPCContext } from "../trpc";vi.mock("@clerk/nextjs/server");test("Get Test Workspace", async () => {- const ctx = await createTRPCContext({+ const ctx = createTRPCContext({+ // @ts-expect-errorreq: {},+ auth: {+ userId: "1",+ sessionId: "1",+ },+ workspace: {+ id: 1,+ },});- // @ts-expect-error- ctx.auth = {- userId: "1",- sessionId: "1",- };-const caller = edgeRouter.createCaller(ctx);- const result = await caller.workspace.getWorkspace({ slug: "test" });+ const result = await caller.workspace.getWorkspace();+expect(result).toEqual({id: 1,slug: "test",@@ -33,31 +36,30 @@ test("Get Test Workspace", async () => {test("No workspace", async () => {const ctx = createTRPCContext({+ // @ts-expect-errorreq: {},+ auth: {+ userId: "1",+ sessionId: "1",+ },+ workspace: undefined,});- // @ts-expect-error- ctx.auth = {- userId: "1",- sessionId: "1",- };-const caller = edgeRouter.createCaller(ctx);- const result = await caller.workspace.getWorkspace({ slug: "Dont Exist" });+ const result = await caller.workspace.getWorkspace();expect(result).toBeUndefined();});test("All workspaces", async () => {const ctx = createTRPCContext({+ // @ts-expect-errorreq: {},+ auth: {+ userId: "1",+ sessionId: "1",+ },});- // @ts-expect-error- ctx.auth = {- userId: "1",- sessionId: "1",- };-const caller = edgeRouter.createCaller(ctx);const result = await caller.workspace.getUserWithWorkspace();expect(result).toMatchObject([diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.tsindex d86c54337..344f61151 100644--- a/packages/api/src/router/workspace.ts+++ b/packages/api/src/router/workspace.ts@@ -9,7 +9,6 @@ import {} from "@openstatus/db/src/schema";import { createTRPCRouter, protectedProcedure } from "../trpc";-import { hasUserAccessToWorkspace } from "./utils";export const workspaceRouter = createTRPCRouter({getUserWithWorkspace: protectedProcedure.query(async (opts) => {@@ -25,21 +24,13 @@ export const workspaceRouter = createTRPCRouter({});}),- getWorkspace: protectedProcedure- .input(z.object({ slug: z.string() }))- .query(async (opts) => {- const data = await hasUserAccessToWorkspace({- workspaceSlug: opts.input.slug,- ctx: opts.ctx,- });- if (!data) return;-- const result = await opts.ctx.db.query.workspace.findFirst({- where: eq(workspace.id, data.workspace.id),- });+ getWorkspace: protectedProcedure.query(async (opts) => {+ const result = await opts.ctx.db.query.workspace.findFirst({+ where: eq(workspace.id, opts.ctx.workspace.id),+ });- return selectWorkspaceSchema.parse(result);- }),+ return selectWorkspaceSchema.parse(result);+ }),createWorkspace: protectedProcedure.input(z.object({ name: z.string() }))diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.tsindex dfd73db82..de77d45c8 100644--- a/packages/api/src/trpc.ts+++ b/packages/api/src/trpc.ts@@ -8,7 +8,8 @@ import { inferAsyncReturnType, initTRPC, TRPCError } from "@trpc/server";import superjson from "superjson";import { ZodError } from "zod";-import { db } from "@openstatus/db";+import { db, eq, schema } from "@openstatus/db";+import type { User, Workspace } from "@openstatus/db/src/schema";/*** 1. CONTEXT@@ -21,6 +22,8 @@ import { db } from "@openstatus/db";*/type CreateContextOptions = {auth: SignedInAuthObject | SignedOutAuthObject | null;+ workspace?: Workspace | null;+ user?: User | null;req?: NextRequest;};@@ -50,9 +53,13 @@ export const createTRPCContext = (opts: {serverSideCall?: boolean;}) => {const auth = !opts.serverSideCall ? getAuth(opts.req) : null;+ const workspace = null;+ const user = null;return createInnerTRPCContext({auth,+ workspace,+ user,req: opts.req,});};@@ -106,16 +113,44 @@ export const publicProcedure = t.procedure;* Reusable middleware that enforces users are logged in before running the* procedure*/-const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {+const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {if (!ctx.auth?.userId) {throw new TRPCError({ code: "UNAUTHORIZED" });}++ /**+ * Attach `user` and `workspace` infos to context by+ * comparing the `user.tenantId` to clerk's `auth.userId`+ */+ const query = await db+ .select()+ .from(schema.user)+ .innerJoin(+ schema.usersToWorkspaces,+ eq(schema.usersToWorkspaces.userId, schema.user.id),+ )+ .innerJoin(+ schema.workspace,+ eq(schema.workspace.id, schema.usersToWorkspaces.workspaceId),+ )+ .where(eq(schema.user.tenantId, ctx.auth.userId))+ .get();++ const workspace = schema.selectWorkspaceSchema.parse(query?.workspace);+ const user = schema.selectUserSchema.parse(query?.user);++ if (!workspace && !user) {+ throw new TRPCError({ code: "UNAUTHORIZED" });+ }+return next({ctx: {auth: {...ctx.auth,userId: ctx.auth.userId,},+ user,+ workspace,},});});diff --git a/packages/api/src/utils.ts b/packages/api/src/utils.tsnew file mode 100644index 000000000..e69de29bbdiff --git a/packages/db/src/schema/incidents/validation.ts b/packages/db/src/schema/incidents/validation.tsindex 0a2d5fead..c8965b49d 100644--- a/packages/db/src/schema/incidents/validation.ts+++ b/packages/db/src/schema/incidents/validation.ts@@ -7,8 +7,6 @@ export const incidentStatusSchema = z.enum(incidentStatus);export const insertIncidentUpdateSchema = createInsertSchema(incidentUpdate, {status: incidentStatusSchema,-}).extend({- workspaceSlug: z.string(), // FIXME: we should do it differently!});export const insertIncidentSchema = createInsertSchema(incident, {@@ -16,7 +14,6 @@ export const insertIncidentSchema = createInsertSchema(incident, {}).extend({date: z.date().optional().default(new Date()),- workspaceSlug: z.string(),/*** relationship to monitors and pages*/diff --git a/packages/db/src/schema/monitors/validation.ts b/packages/db/src/schema/monitors/validation.tsindex 63dc018c2..127242e28 100644--- a/packages/db/src/schema/monitors/validation.ts+++ b/packages/db/src/schema/monitors/validation.ts@@ -69,7 +69,7 @@ export const insertMonitorSchema = createInsertSchema(monitor, {headers: headersSchema.default([]),}).extend({method: monitorMethodsSchema.default("GET"),- notifications: z.array(z.number()).optional(),+ notifications: z.array(z.number()).optional().default([]),body: z.string().default("").optional(),});diff --git a/packages/db/src/schema/pages/validation.ts b/packages/db/src/schema/pages/validation.tsindex aa9804990..b7cef0528 100644--- a/packages/db/src/schema/pages/validation.ts+++ b/packages/db/src/schema/pages/validation.ts@@ -26,7 +26,6 @@ export const insertPageSchema = createInsertSchema(page, {slug: slugSchema,}).extend({monitors: z.array(z.number()).optional().default([]),- workspaceSlug: z.string(),});export const selectPageSchema = createSelectSchema(page);diff --git a/packages/db/src/schema/users/index.ts b/packages/db/src/schema/users/index.tsindex 7616f9e53..fe1a48f74 100644--- a/packages/db/src/schema/users/index.ts+++ b/packages/db/src/schema/users/index.ts@@ -1 +1,2 @@export * from "./user";+export * from "./validation";diff --git a/packages/db/src/schema/users/validation.ts b/packages/db/src/schema/users/validation.tsnew file mode 100644index 000000000..e44fb6cbd--- /dev/null+++ b/packages/db/src/schema/users/validation.ts@@ -0,0 +1,11 @@+import { createInsertSchema, createSelectSchema } from "drizzle-zod";+import type { z } from "zod";++import { user } from "./user";++export const insertUserSchema = createInsertSchema(user);++export const selectUserSchema = createSelectSchema(user);++export type InsertUser = z.infer<typeof insertUserSchema>;+export type User = z.infer<typeof selectUserSchema>;diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 137de5dfc..bb07f365d 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -20,7 +20,7 @@"dependencies": {"@hookform/resolvers": "3.3.1","@radix-ui/react-accordion": "1.1.2",- "@radix-ui/react-alert-dialog": "1.0.4",+ "@radix-ui/react-alert-dialog": "1.0.5","@radix-ui/react-avatar": "1.0.4","@radix-ui/react-checkbox": "1.0.4","@radix-ui/react-context-menu": "2.1.5",diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsxindex 874513831..6c87eaf45 100644--- a/packages/ui/src/components/alert-dialog.tsx+++ b/packages/ui/src/components/alert-dialog.tsx@@ -11,10 +11,9 @@ const AlertDialog = AlertDialogPrimitive.Root;const AlertDialogTrigger = AlertDialogPrimitive.Trigger;const AlertDialogPortal = ({- className,...props}: AlertDialogPrimitive.AlertDialogPortalProps) => (- <AlertDialogPrimitive.Portal className={cn(className)} {...props} />+ <AlertDialogPrimitive.Portal {...props} />);AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 982d2a8a6..c70283891 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -726,8 +726,8 @@ importers:specifier: 1.1.2version: 1.1.2(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-alert-dialog':- specifier: 1.0.4- version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ specifier: 1.0.5+ version: 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-avatar':specifier: 1.0.4version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -2994,8 +2994,8 @@ packages:react-dom: 18.2.0([email protected])dev: false- /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):- resolution: {integrity: sha512-jbfBCRlKYlhbitueOAv7z74PXYeIQmWpKwm3jllsdkw7fGWNkxqP3v0nY9WmOzcPqpQuoorNtvViBgL46n5gVg==}+ /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-OrVIOcZL0tl6xibeuGt5/+UxoT2N27KCFOPjFyfXMnchxSHZ/OW7cCX2nGlIYJrbHK/fczPcFzAwvNBB6XBNMA==}peerDependencies:'@types/react': '*''@types/react-dom': '*'@@ -3011,7 +3011,7 @@ packages:'@radix-ui/primitive': 1.0.1'@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])'@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-dialog': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-dialog': 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-slot': 1.0.2(@types/[email protected])([email protected])'@types/react': 18.2.24@@ -3278,6 +3278,40 @@ packages:react-remove-scroll: 2.5.5(@types/[email protected])([email protected])dev: false+ /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-GjWJX/AUpB703eEBanuBnIWdIXg6NvJFCXcNlSZk4xdszCdhrJgBoUd1cGk67vFO+WdA2pfI/plOpqz/5GUP6Q==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.23.2+ '@radix-ui/primitive': 1.0.1+ '@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-focus-guards': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-focus-scope': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-id': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-portal': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-slot': 1.0.2(@types/[email protected])([email protected])+ '@radix-ui/react-use-controllable-state': 1.0.1(@types/[email protected])([email protected])+ '@types/react': 18.2.24+ '@types/react-dom': 18.2.8+ aria-hidden: 1.2.3+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ react-remove-scroll: 2.5.5(@types/[email protected])([email protected])+ dev: false+resolution: {integrity: sha512-RXcvnXgyvYvBEOhCBuddKecVkoMiI10Jcm5cTI7abJRAHYfFxeu+FBQs/DvdxSYucxR5mna0dNsL6QFlds5TMA==}peerDependencies: