Skip to content

Open-source status page, incident response and uptime monitoring

💸 Stripe Integration (#178)

Thibault Le Ouay5c2c99bed471
diff --git a/apps/web/package.json b/apps/web/package.json
index 8b38850a4..be487a614 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -10,7 +10,7 @@
"tsc": "tsc --noEmit"
},
"dependencies": {
- "@clerk/nextjs": "4.23.1",
+ "@clerk/nextjs": "4.23.2",
"@hookform/resolvers": "3.1.1",
"@openstatus/analytics": "workspace:^",
"@openstatus/api": "workspace:^",
@@ -35,6 +35,7 @@
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-toast": "1.1.4",
"@radix-ui/react-tooltip": "1.0.6",
+ "@stripe/stripe-js": "2.0.0",
"@t3-oss/env-nextjs": "0.4.1",
"@tailwindcss/typography": "0.5.9",
"@tanstack/react-table": "8.9.3",
@@ -67,6 +68,7 @@
"rehype-pretty-code": "0.10.0",
"resend": "0.15.3",
"shiki": "0.14.3",
+ "stripe": "12.17.0",
"superjson": "1.13.1",
"svix": "1.4.12",
"tailwind-merge": "1.13.2",
diff --git a/apps/web/src/app/api/webhook/stripe/route.ts b/apps/web/src/app/api/webhook/stripe/route.ts
new file mode 100644
index 000000000..49476264a
--- /dev/null
+++ b/apps/web/src/app/api/webhook/stripe/route.ts
@@ -0,0 +1,56 @@
+import type { NextRequest } from "next/server";
+import { TRPCError } from "@trpc/server";
+import { getHTTPStatusCodeFromError } from "@trpc/server/http";
+
+import { createTRPCContext } from "@openstatus/api";
+import { lambdaRouter, stripe } from "@openstatus/api/src/lambda";
+
+import { env } from "@/env";
+
+export async function POST(req: NextRequest) {
+ const payload = await req.text();
+ const signature = req.headers.get("Stripe-Signature");
+ if (!signature) return new Response("No signature", { status: 400 });
+
+ try {
+ const event = stripe.webhooks.constructEvent(
+ payload,
+ signature,
+ env.STRIPE_WEBHOOK_SECRET_KEY,
+ );
+
+ /**
+ * Forward to tRPC API to handle the webhook event
+ */
+ const ctx = createTRPCContext({ req });
+ const caller = lambdaRouter.createCaller(ctx);
+
+ switch (event.type) {
+ case "checkout.session.completed":
+ await caller.stripeRouter.webhooks.sessionCompleted({ event });
+ break;
+
+ case "customer.subscription.deleted":
+ await caller.stripeRouter.webhooks.customerSubscriptionDeleted({
+ event,
+ });
+ break;
+
+ default:
+ throw new Error(`Unhandled event type ${event.type}`);
+ }
+ } catch (error) {
+ if (error instanceof TRPCError) {
+ const errorCode = getHTTPStatusCodeFromError(error);
+ console.error("Error in tRPC webhook handler", error);
+ return new Response(error.message, { status: errorCode });
+ }
+
+ const message = error instanceof Error ? error.message : "Unknown error";
+ return new Response(`Webhook Error: ${message}`, {
+ status: 400,
+ });
+ }
+
+ return new Response(null, { status: 200 });
+}
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx
index 58423cea8..37cc27606 100644
--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx
+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/monitors/page.tsx
@@ -23,8 +23,13 @@ export default async function MonitorPage({
const monitors = await api.monitor.getMonitorsByWorkspace.query({
workspaceSlug: params.workspaceSlug,
});
+ const workspace = await api.workspace.getWorkspace.query({
+ slug: params.workspaceSlug,
+ });
- const isLimit = (monitors?.length || 0) >= limit;
+ const isLimit =
+ (monitors?.length || 0) >=
+ allPlans[workspace?.plan || "free"].limits.monitors;
return (
<div className="grid gap-6 md:grid-cols-2 md:gap-8">
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/page.tsx
index ebeccf1dc..39972683a 100644
--- a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/page.tsx
+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/page.tsx
@@ -5,5 +5,5 @@ export default function DashboardRedirect({
}: {
params: { workspaceId: string };
}) {
- return redirect(`/app/${params.workspaceId}/dashboard`);
+ return redirect(`/app/${params.workspaceId}/monitors`);
}
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/_components/plan.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/_components/plan.tsx
new file mode 100644
index 000000000..d945c6ec5
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/_components/plan.tsx
@@ -0,0 +1,157 @@
+"use client";
+
+import { useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { Check } from "lucide-react";
+import type { z } from "zod";
+
+import type { selectWorkspaceSchema } from "@openstatus/db/src/schema/workspace";
+
+import { Shell } from "@/components/dashboard/shell";
+import { Button } from "@/components/ui/button";
+import { getStripe } from "@/lib/stripe/client";
+import { cn } from "@/lib/utils";
+import { api } from "@/trpc/client";
+
+interface Plan {
+ title: string;
+ description: string;
+ cost: number | string;
+ features: string[];
+ action: {
+ text: string;
+ onClick: () => void;
+ };
+ loading?: boolean;
+}
+
+interface Props extends Plan {
+ className?: string;
+}
+export const SettingsPlan = ({
+ workspaceSlug,
+ workspaceData,
+}: {
+ workspaceSlug: string;
+ workspaceData: z.infer<typeof selectWorkspaceSchema>;
+}) => {
+ const router = useRouter();
+
+ const [isPending, startTransition] = useTransition();
+
+ const getCheckoutSession = () => {
+ startTransition(async () => {
+ const result = await api.stripeRouter.getCheckoutSession.mutate({
+ workspaceSlug: workspaceSlug,
+ });
+ if (!result) return;
+
+ const stripe = await getStripe();
+ stripe?.redirectToCheckout({ sessionId: result.id });
+ });
+ };
+ const getUserCustomerPortal = async () => {
+ const url = await api.stripeRouter.getUserCustomerPortal.mutate({
+ workspaceSlug: workspaceSlug,
+ });
+ if (!url) return;
+ router.push(url);
+ return;
+ };
+ getUserCustomerPortal;
+ const plans: Record<"free" | "pro", Plan> = {
+ free: {
+ title: "Free",
+ description: "Get started now and upgrade once reaching the limits.",
+ cost: 0,
+ features: [
+ "5 monitors",
+ "1 status page",
+ "subdomain",
+ "10m, 30m, 1h checks",
+ ],
+ action: {
+ text: workspaceData?.plan === "free" ? "Current plan" : "Downgrade",
+ onClick: async () => {
+ await getUserCustomerPortal();
+ },
+ },
+ },
+ pro: {
+ title: "Pro",
+ description: "Scale and build monitors for all your services.",
+ cost: 29,
+ features: [
+ "20 monitors",
+ "5 status page",
+ "custom domain",
+ "1m, 5m, 10m, 30m, 1h checks",
+ "5 team members",
+ ],
+ loading: isPending,
+ action: {
+ text: workspaceData?.plan === "free" ? "Upgrade" : "Current plan",
+ onClick: async () => {
+ await getCheckoutSession();
+ },
+ },
+ },
+ };
+
+ return (
+ <Shell className="mt-4 w-full">
+ <div className="grid gap-4 md:grid-cols-2 md:gap-0">
+ <Plan
+ {...plans.free}
+ className="md:border-border/50 md:border-r md:pr-4"
+ />
+ <Plan {...plans.pro} className="md:pl-4" />
+ </div>
+ </Shell>
+ );
+};
+
+export function Plan({
+ title,
+ description,
+ cost,
+ features,
+ action,
+ loading,
+ className,
+}: Props) {
+ return (
+ <div key={title} className={cn("flex w-full flex-col", className)}>
+ <div className="flex-1">
+ <div className="flex items-end justify-between gap-4">
+ <div>
+ <p className="font-cal mb-2 text-xl">{title}</p>
+ <p className="text-muted-foreground">{description}</p>
+ </div>
+ <p className="shrink-0">
+ <span className="font-cal text-2xl">{cost}</span>
+ {typeof cost === "number" ? (
+ <span className="text-muted-foreground font-light">/month</span>
+ ) : null}
+ </p>
+ </div>
+ <ul className="border-border/50 grid divide-y py-2">
+ {features.map((item) => (
+ <li
+ key={item}
+ className="text-muted-foreground inline-flex items-center py-2 text-sm"
+ >
+ <Check className="mr-2 h-4 w-4 text-green-500" />
+ {item}
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div>
+ <Button size="sm" onClick={action.onClick} disabled={loading}>
+ {action.text}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsx
new file mode 100644
index 000000000..68e6cc45e
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/[workspaceSlug]/settings/page.tsx
@@ -0,0 +1,40 @@
+import * as React from "react";
+
+import { Header } from "@/components/dashboard/header";
+import { Badge } from "@/components/ui/badge";
+import { api } from "@/trpc/server";
+import { SettingsPlan } from "./_components/plan";
+
+export default async function Page({
+ params,
+}: {
+ params: { workspaceSlug: string };
+}) {
+ const data = await api.workspace.getWorkspace.query({
+ slug: params.workspaceSlug,
+ });
+
+ if (!data) {
+ return <>Workspace not found</>;
+ }
+ return (
+ <div className="grid gap-6 md:grid-cols-2 md:gap-8">
+ <Header
+ title="Settings"
+ description="Your OpenStatus workspace settings."
+ ></Header>
+ <div className="col-span-full">
+ <h3 className="text-lg font-medium">Plans</h3>
+
+ <div className="mt-4 flex items-center space-x-2 text-sm">
+ Your current plan is{" "}
+ <Badge className="ml-2">{data?.plan || "free"}</Badge>
+ </div>
+ <SettingsPlan
+ workspaceSlug={params.workspaceSlug}
+ workspaceData={data}
+ />
+ </div>
+ </div>
+ );
+}
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.tsx
index ff8d098dc..4b9c296b9 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
@@ -13,8 +13,6 @@ import { api } from "@/trpc/server";
import { ActionButton } from "./_components/action-button";
import { EmptyState } from "./_components/empty-state";
-const limit = allPlans.free.limits["status-pages"];
-
// export const revalidate = 0;
export const dynamic = "force-dynamic";
@@ -30,7 +28,14 @@ export default async function Page({
workspaceSlug: params.workspaceSlug,
});
- const isLimit = (pages?.length || 0) >= limit;
+ const workspace = await api.workspace.getWorkspace.query({
+ slug: params.workspaceSlug,
+ });
+
+ const isLimit =
+ (monitors?.length || 0) >=
+ allPlans[workspace?.plan || "free"].limits["status-pages"];
+
const disableButton = isLimit || !Boolean(monitors);
return (
diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsx
index 84b1edf49..60b0dba6b 100644
--- a/apps/web/src/components/icons.tsx
+++ b/apps/web/src/components/icons.tsx
@@ -1,6 +1,7 @@
import {
Activity,
Calendar,
+ Cog,
Fingerprint,
LayoutDashboard,
Link,
@@ -28,6 +29,7 @@ export const Icons = {
"panel-top": PanelTop,
table: Table,
"toy-brick": ToyBrick,
+ cog: Cog,
search: Search,
"search-check": SearchCheck,
fingerprint: Fingerprint,
diff --git a/apps/web/src/components/layout/app-sidebar.tsx b/apps/web/src/components/layout/app-sidebar.tsx
index 1b1c24ab6..777ab48a6 100644
--- a/apps/web/src/components/layout/app-sidebar.tsx
+++ b/apps/web/src/components/layout/app-sidebar.tsx
@@ -10,28 +10,46 @@ import { Icons } from "../icons";
export function AppSidebar() {
const pathname = usePathname();
const params = useParams();
+
return (
- <ul className="grid gap-1">
- {pagesConfig.map(({ title, href, icon, disabled }) => {
- const Icon = Icons[icon];
- const link = `/app/${params.workspaceSlug}${href}`;
- return (
- <li key={title} className="w-full">
- <Link
- href={link}
- className={cn(
- "hover:bg-muted/50 hover:text-foreground text-muted-foreground group flex w-full min-w-[200px] items-center rounded-md border border-transparent px-3 py-1",
- pathname.startsWith(link) &&
- "bg-muted/50 border-border text-foreground",
- disabled && "pointer-events-none opacity-60",
- )}
- >
- <Icon className={cn("mr-2 h-4 w-4")} />
- {title}
- </Link>
- </li>
- );
- })}
- </ul>
+ <div className="flex h-full flex-col justify-between">
+ <ul className="grid gap-1">
+ {pagesConfig.map(({ title, href, icon, disabled }) => {
+ const Icon = Icons[icon];
+ const link = `/app/${params.workspaceSlug}${href}`;
+ return (
+ <li key={title} className="w-full">
+ <Link
+ href={link}
+ className={cn(
+ "hover:bg-muted/50 hover:text-foreground text-muted-foreground group flex w-full min-w-[200px] items-center rounded-md border border-transparent px-3 py-1",
+ pathname.startsWith(link) &&
+ "bg-muted/50 border-border text-foreground",
+ disabled && "pointer-events-none opacity-60",
+ )}
+ >
+ <Icon className={cn("mr-2 h-4 w-4")} />
+ {title}
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ <ul>
+ <li className="w-full">
+ <Link
+ href={`/app/${params.workspaceSlug}/settings`}
+ className={cn(
+ "hover:bg-muted/50 hover:text-foreground text-muted-foreground group flex w-full min-w-[200px] items-center rounded-md border border-transparent px-3 py-1",
+ pathname.startsWith(`/app/${params.workspaceSlug}/settings`) &&
+ "bg-muted/50 border-border text-foreground",
+ )}
+ >
+ <Icons.cog className={cn("mr-2 h-4 w-4")} />
+ Settings
+ </Link>
+ </li>
+ </ul>
+ </div>
);
}
diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts
index 14f54ef73..54536db69 100644
--- a/apps/web/src/env.ts
+++ b/apps/web/src/env.ts
@@ -13,6 +13,7 @@ export const env = createEnv({
QSTASH_CURRENT_SIGNING_KEY: z.string().min(1),
QSTASH_NEXT_SIGNING_KEY: z.string().min(1),
QSTASH_TOKEN: z.string().min(1),
+ STRIPE_WEBHOOK_SECRET_KEY: z.string(),
},
client: {
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: z.string().min(1),
@@ -20,6 +21,7 @@ export const env = createEnv({
NEXT_PUBLIC_CLERK_SIGN_UP_URL: z.string().min(1),
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL: z.string().min(1),
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL: z.string().min(1),
+ NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: z.string(),
},
runtimeEnv: {
CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY,
@@ -37,5 +39,8 @@ export const env = createEnv({
QSTASH_CURRENT_SIGNING_KEY: process.env.QSTASH_CURRENT_SIGNING_KEY,
QSTASH_NEXT_SIGNING_KEY: process.env.QSTASH_NEXT_SIGNING_KEY,
QSTASH_TOKEN: process.env.QSTASH_TOKEN,
+ NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:
+ process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,
+ STRIPE_WEBHOOK_SECRET_KEY: process.env.STRIPE_WEBHOOK_SECRET_KEY,
},
});
diff --git a/apps/web/src/lib/stripe/client.ts b/apps/web/src/lib/stripe/client.ts
new file mode 100644
index 000000000..50e713747
--- /dev/null
+++ b/apps/web/src/lib/stripe/client.ts
@@ -0,0 +1,14 @@
+import type { Stripe as StripeProps } from "@stripe/stripe-js";
+import { loadStripe } from "@stripe/stripe-js";
+
+import { env } from "@/env";
+
+let stripePromise: Promise<StripeProps | null>;
+
+export const getStripe = () => {
+ if (!stripePromise) {
+ stripePromise = loadStripe(env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
+ }
+
+ return stripePromise;
+};
diff --git a/apps/web/src/trpc/shared.ts b/apps/web/src/trpc/shared.ts
index 9094e83c3..b37ad30fc 100644
--- a/apps/web/src/trpc/shared.ts
+++ b/apps/web/src/trpc/shared.ts
@@ -10,7 +10,7 @@ const getBaseUrl = () => {
return `http://localhost:3000`;
};
-const lambdas = ["clerk"];
+const lambdas = ["clerkRouter", "stripeRouter"];
export const endingLink = (opts?: { headers?: HTTPHeaders }) =>
((runtime) => {
diff --git a/packages/analytics/src/type.ts b/packages/analytics/src/type.ts
index bbb65f1c8..22a07f250 100644
--- a/packages/analytics/src/type.ts
+++ b/packages/analytics/src/type.ts
@@ -13,4 +13,5 @@ export type AnalyticsEvents =
event: "Page Created";
slug: string;
}
+ | { event: "User Upgraded"; email: string }
| { event: "User Signed In" };
diff --git a/packages/api/package.json b/packages/api/package.json
index d3e9b3f6a..4e9dd7dd9 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -12,9 +12,11 @@
"@openstatus/db": "workspace:^",
"@openstatus/emails": "workspace:^",
"@openstatus/plans": "workspace:^",
+ "@t3-oss/env-core": "0.6.0",
"@trpc/client": "10.35.0",
"@trpc/server": "10.35.0",
"random-word-slugs": "0.1.7",
+ "stripe": "12.17.0",
"superjson": "1.13.1",
"zod": "3.21.4"
},
diff --git a/packages/api/src/env.ts b/packages/api/src/env.ts
new file mode 100644
index 000000000..3b09b9962
--- /dev/null
+++ b/packages/api/src/env.ts
@@ -0,0 +1,16 @@
+import { createEnv } from "@t3-oss/env-core";
+import { z } from "zod";
+
+export const env = createEnv({
+ server: {
+ STRIPE_SECRET_KEY: z.string(),
+ STRIPE_PRO_PRODUCT_ID: z.string(),
+ STRIPE_PRO_MONTHLY_PRICE_ID: z.string(),
+ },
+
+ runtimeEnv: {
+ STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
+ STRIPE_PRO_PRODUCT_ID: process.env.STRIPE_PRO_PRODUCT_ID,
+ STRIPE_PRO_MONTHLY_PRICE_ID: process.env.STRIPE_PRO_MONTHLY_PRICE_ID,
+ },
+});
diff --git a/packages/api/src/lambda.ts b/packages/api/src/lambda.ts
index f520c747d..d479d2f35 100644
--- a/packages/api/src/lambda.ts
+++ b/packages/api/src/lambda.ts
@@ -1,9 +1,13 @@
import { clerkRouter } from "./router/clerk/webhook";
+import { stripeRouter } from "./router/stripe";
import { createTRPCRouter } from "./trpc";
// Deployed to /trpc/lambda/**
export const lambdaRouter = createTRPCRouter({
clerkRouter: clerkRouter,
+ stripeRouter: stripeRouter,
// TODO: Add open api router
// See trpc-openapi
});
+
+export { stripe } from "./router/stripe/shared";
diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.ts
new file mode 100644
index 000000000..030ee282d
--- /dev/null
+++ b/packages/api/src/router/stripe/index.ts
@@ -0,0 +1,141 @@
+import { z } from "zod";
+
+import { eq } from "@openstatus/db";
+import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema";
+
+import { createTRPCRouter, protectedProcedure } from "../../trpc";
+import { stripe } from "./shared";
+import { webhookRouter } from "./webhook";
+
+const url =
+ process.env.NODE_ENV === "production"
+ ? "https://www.openstatus.dev"
+ : "http://localhost:3000";
+
+export const stripeRouter = createTRPCRouter({
+ webhooks: webhookRouter,
+
+ getUserCustomerPortal: protectedProcedure
+ .input(z.object({ workspaceSlug: z.string() }))
+ .mutation(async (opts) => {
+ const result = await opts.ctx.db
+ .select()
+ .from(workspace)
+ .where(eq(workspace.slug, opts.input.workspaceSlug))
+ .get();
+
+ if (!result) return;
+
+ const currentUser = opts.ctx.db
+ .select()
+ .from(user)
+ .where(eq(user.tenantId, opts.ctx.auth.userId))
+ .as("currentUser");
+ const userHasAccess = await opts.ctx.db
+ .select()
+ .from(usersToWorkspaces)
+ .where(eq(usersToWorkspaces.workspaceId, result.id))
+ .innerJoin(currentUser, eq(usersToWorkspaces.userId, currentUser.id))
+ .get();
+
+ if (!userHasAccess || !userHasAccess.users_to_workspaces) return;
+ let stripeId = result.stripeId;
+ if (!stripeId) {
+ const customerData: {
+ metadata: { workspaceId: string };
+ email?: string;
+ } = {
+ metadata: {
+ workspaceId: String(workspace.id),
+ },
+ email: opts.ctx.auth.user?.emailAddresses[0].emailAddress || "",
+ };
+
+ const stripeUser = await stripe.customers.create(customerData);
+
+ stripeId = stripeUser.id;
+ await opts.ctx.db
+ .update(workspace)
+ .set({ stripeId })
+ .where(eq(workspace.id, result.id))
+ .run();
+ }
+
+ const session = await stripe.billingPortal.sessions.create({
+ customer: stripeId || "",
+ return_url: `${url}/app/${result.slug}/settings`,
+ });
+
+ return session.url;
+ }),
+
+ getCheckoutSession: protectedProcedure
+ .input(z.object({ workspaceSlug: z.string() }))
+ .mutation(async (opts) => {
+ console.log("getCheckoutSession");
+ // The following code is duplicated we should extract it
+ const result = await opts.ctx.db
+ .select()
+ .from(workspace)
+ .where(eq(workspace.slug, opts.input.workspaceSlug))
+ .get();
+
+ if (!result) return;
+
+ const currentUser = opts.ctx.db
+ .select()
+ .from(user)
+ .where(eq(user.tenantId, opts.ctx.auth.userId))
+ .as("currentUser");
+ const userHasAccess = await opts.ctx.db
+ .select()
+ .from(usersToWorkspaces)
+ .where(eq(usersToWorkspaces.workspaceId, result.id))
+ .innerJoin(currentUser, eq(usersToWorkspaces.userId, currentUser.id))
+ .get();
+
+ if (!userHasAccess || !userHasAccess.users_to_workspaces) return;
+ let stripeId = result.stripeId;
+ if (!stripeId) {
+ const currentUser = await opts.ctx.db
+ .select()
+ .from(user)
+ .where(eq(user.tenantId, opts.ctx.auth.userId))
+ .get();
+ const customerData: {
+ metadata: { workspaceId: string };
+ email?: string;
+ } = {
+ metadata: {
+ workspaceId: String(workspace.id),
+ },
+ email: currentUser.email || "",
+ };
+ const stripeUser = await stripe.customers.create(customerData);
+
+ stripeId = stripeUser.id;
+ await opts.ctx.db
+ .update(workspace)
+ .set({ stripeId })
+ .where(eq(workspace.id, result.id))
+ .run();
+ }
+
+ const session = await stripe.checkout.sessions.create({
+ payment_method_types: ["card"],
+ customer: stripeId,
+
+ line_items: [
+ {
+ price: process.env.STRIPE_PRO_MONTHLY_PRICE_ID,
+ quantity: 1,
+ },
+ ],
+ mode: "subscription",
+ success_url: `${url}/app/${result.slug}/settings?success=true`,
+ cancel_url: `${url}/app/${result.slug}/settings`,
+ });
+
+ return session;
+ }),
+});
diff --git a/packages/api/src/router/stripe/shared.ts b/packages/api/src/router/stripe/shared.ts
new file mode 100644
index 000000000..e1bed6f7e
--- /dev/null
+++ b/packages/api/src/router/stripe/shared.ts
@@ -0,0 +1,35 @@
+import Stripe from "stripe";
+
+import { env } from "../../env";
+
+export const stripe = new Stripe(env.STRIPE_SECRET_KEY ?? "", {
+ apiVersion: "2022-11-15",
+ appInfo: {
+ name: "OpenStatus",
+ version: "0.1.0",
+ },
+});
+
+export async function cancelSubscription(customer?: string) {
+ if (!customer) return;
+
+ try {
+ const subscriptionId = await stripe.subscriptions
+ .list({
+ customer,
+ })
+ .then((res) => res.data[0]?.id);
+
+ if (!subscriptionId) return;
+
+ return await stripe.subscriptions.update(subscriptionId, {
+ cancel_at_period_end: true,
+ cancellation_details: {
+ comment: "Customer deleted their OpenStatus project.",
+ },
+ });
+ } catch (error) {
+ console.log("Error cancelling Stripe subscription", error);
+ return;
+ }
+}
diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.ts
new file mode 100644
index 000000000..22f9da4e0
--- /dev/null
+++ b/packages/api/src/router/stripe/webhook.ts
@@ -0,0 +1,98 @@
+import { TRPCError } from "@trpc/server";
+import type Stripe from "stripe";
+import { custom, z } from "zod";
+
+import { analytics, trackAnalytics } from "@openstatus/analytics";
+import { eq } from "@openstatus/db";
+import { user, workspace } from "@openstatus/db/src/schema";
+
+import { createTRPCRouter, publicProcedure } from "../../trpc";
+import { stripe } from "./shared";
+
+const webhookProcedure = publicProcedure.input(
+ z.object({
+ // From type Stripe.Event
+ event: z.object({
+ id: z.string(),
+ account: z.string().nullish(),
+ created: z.number(),
+ data: z.object({
+ object: z.record(z.any()),
+ }),
+ type: z.string(),
+ }),
+ }),
+);
+
+export const webhookRouter = createTRPCRouter({
+ sessionCompleted: webhookProcedure.mutation(async (opts) => {
+ const session = opts.input.event.data.object as Stripe.Checkout.Session;
+ if (typeof session.subscription !== "string") {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Missing or invalid subscription id",
+ });
+ }
+ const subscription = await stripe.subscriptions.retrieve(
+ session.subscription,
+ );
+ const customerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id;
+ const result = await opts.ctx.db
+ .select()
+ .from(workspace)
+ .where(eq(workspace.stripeId, customerId))
+ .get();
+ if (!result) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Workspace not found",
+ });
+ }
+ await opts.ctx.db
+ .update(workspace)
+ .set({
+ plan: "pro",
+ subscriptionId: subscription.id,
+ endsAt: new Date(subscription.current_period_end * 1000),
+ paidUntil: new Date(subscription.current_period_end * 1000),
+ })
+ .where(eq(workspace.id, result.id))
+ .run();
+ const customer = await stripe.customers.retrieve(customerId);
+ if (!customer.deleted && customer.email) {
+ const userResult = await opts.ctx.db
+ .select()
+ .from(user)
+ .where(eq(user.email, customer.email))
+ .get();
+ await analytics.identify(String(userResult.id), {
+ email: customer.email,
+ userId: userResult.id,
+ });
+ await trackAnalytics({
+ event: "User Upgraded",
+ email: customer.email,
+ });
+ }
+ }),
+ customerSubscriptionDeleted: webhookProcedure.mutation(async (opts) => {
+ const subscription = opts.input.event.data.object as Stripe.Subscription;
+ const customerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id;
+
+ await opts.ctx.db
+ .update(workspace)
+ .set({
+ subscriptionId: null,
+ plan: "FREE",
+ paidUntil: null,
+ })
+ .where(eq(workspace.stripeId, customerId))
+ .run();
+ }),
+});
diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.ts
index da5262874..a6f745ce6 100644
--- a/packages/api/src/router/workspace.ts
+++ b/packages/api/src/router/workspace.ts
@@ -2,7 +2,13 @@ import { generateSlug } from "random-word-slugs";
import { z } from "zod";
import { eq } from "@openstatus/db";
-import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema";
+import {
+ selectPageSchema,
+ selectWorkspaceSchema,
+ user,
+ usersToWorkspaces,
+ workspace,
+} from "@openstatus/db/src/schema";
import { createTRPCRouter, protectedProcedure } from "../trpc";
@@ -41,12 +47,11 @@ export const workspaceRouter = createTRPCRouter({
if (!result.users_to_workspaces) return;
- return await opts.ctx.db.query.workspace.findMany({
- with: {
- pages: true,
- },
+ const data = await opts.ctx.db.query.workspace.findFirst({
where: eq(workspace.id, currentWorkspace.id),
});
+
+ return selectWorkspaceSchema.parse(data);
}),
createWorkspace: protectedProcedure
diff --git a/packages/db/drizzle/0005_even_baron_strucker.sql b/packages/db/drizzle/0005_even_baron_strucker.sql
new file mode 100644
index 000000000..c02806248
--- /dev/null
+++ b/packages/db/drizzle/0005_even_baron_strucker.sql
@@ -0,0 +1,4 @@
+ALTER TABLE workspace ADD `subscription_id` text;--> statement-breakpoint
+ALTER TABLE workspace ADD `plan` text(3);--> statement-breakpoint
+ALTER TABLE workspace ADD `ends_at` integer;--> statement-breakpoint
+ALTER TABLE workspace ADD `paid_until` integer;
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0005_snapshot.json b/packages/db/drizzle/meta/0005_snapshot.json
new file mode 100644
index 000000000..2230c49ca
--- /dev/null
+++ b/packages/db/drizzle/meta/0005_snapshot.json
@@ -0,0 +1,722 @@
+{
+ "version": "5",
+ "dialect": "sqlite",
+ "id": "84447f0c-af79-4add-93d7-eb6868983258",
+ "prevId": "c7088c9f-2521-43af-884e-b7b0b81b0cb9",
+ "tables": {
+ "incident": {
+ "name": "incident",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text(4)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "incident_workspace_id_workspace_id_fk": {
+ "name": "incident_workspace_id_workspace_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "incident_update": {
+ "name": "incident_update",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text(4)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "incident_id": {
+ "name": "incident_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "incident_update_incident_id_incident_id_fk": {
+ "name": "incident_update_incident_id_incident_id_fk",
+ "tableFrom": "incident_update",
+ "tableTo": "incident",
+ "columnsFrom": [
+ "incident_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "incidents_to_monitors": {
+ "name": "incidents_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "incident_id": {
+ "name": "incident_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "incidents_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "incidents_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "incidents_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_to_monitors_incident_id_incident_id_fk": {
+ "name": "incidents_to_monitors_incident_id_incident_id_fk",
+ "tableFrom": "incidents_to_monitors",
+ "tableTo": "incident",
+ "columnsFrom": [
+ "incident_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "incidents_to_monitors_monitor_id_incident_id_pk": {
+ "columns": [
+ "incident_id",
+ "monitor_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "page": {
+ "name": "page",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "custom_domain": {
+ "name": "custom_domain",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "published": {
+ "name": "published",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "page_slug_unique": {
+ "name": "page_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "page_workspace_id_workspace_id_fk": {
+ "name": "page_workspace_id_workspace_id_fk",
+ "tableFrom": "page",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "monitor": {
+ "name": "monitor",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'other'"
+ },
+ "periodicity": {
+ "name": "periodicity",
+ "type": "text(6)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'other'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text(2)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'inactive'"
+ },
+ "active": {
+ "name": "active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(512)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_workspace_id_workspace_id_fk": {
+ "name": "monitor_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "monitors_to_pages": {
+ "name": "monitors_to_pages",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitors_to_pages_monitor_id_monitor_id_fk": {
+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitors_to_pages_page_id_page_id_fk": {
+ "name": "monitors_to_pages_page_id_page_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitors_to_pages_monitor_id_page_id_pk": {
+ "columns": [
+ "monitor_id",
+ "page_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_name": {
+ "name": "last_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "photo_url": {
+ "name": "photo_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "user_tenant_id_unique": {
+ "name": "user_tenant_id_unique",
+ "columns": [
+ "tenant_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "users_to_workspaces": {
+ "name": "users_to_workspaces",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "users_to_workspaces_user_id_user_id_fk": {
+ "name": "users_to_workspaces_user_id_user_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "users_to_workspaces_workspace_id_workspace_id_fk": {
+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "users_to_workspaces_user_id_workspace_id_pk": {
+ "columns": [
+ "user_id",
+ "workspace_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "workspace": {
+ "name": "workspace",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripe_id": {
+ "name": "stripe_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan": {
+ "name": "plan",
+ "type": "text(3)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ends_at": {
+ "name": "ends_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "paid_until": {
+ "name": "paid_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "workspace_slug_unique": {
+ "name": "workspace_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "workspace_stripe_id_unique": {
+ "name": "workspace_stripe_id_unique",
+ "columns": [
+ "stripe_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ }
+ },
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index c2c135f22..086658d09 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -36,6 +36,13 @@
"when": 1691850907670,
"tag": "0004_fixed_dakota_north",
"breakpoints": true
+ },
+ {
+ "idx": 5,
+ "version": "5",
+ "when": 1691930414569,
+ "tag": "0005_even_baron_strucker",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/package.json b/packages/db/package.json
index 13d0b42b7..b3e89a7c7 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -10,11 +10,11 @@
"studio": "drizzle-kit studio"
},
"dependencies": {
- "@libsql/client": "^0.3.1",
+ "@libsql/client": "0.3.1",
"@t3-oss/env-core": "0.6.0",
"dotenv": "16.3.1",
"drizzle-orm": "0.27.2",
- "drizzle-zod": "^0.4.4",
+ "drizzle-zod": "0.4.4",
"zod": "3.21.4"
},
"devDependencies": {
@@ -22,10 +22,10 @@
"drizzle-kit": "0.19.10",
"tsconfig": "workspace:^",
"typescript": "5.1.6",
- "bufferutil": "^4.0.7",
- "utf-8-validate": "^6.0.3",
+ "bufferutil": "4.0.7",
+ "utf-8-validate": "6.0.3",
"encoding": "0.1.13",
- "ts-node": "^10.9.1"
+ "ts-node": "10.9.1"
},
"author": ""
}
diff --git a/packages/db/src/schema/workspace.ts b/packages/db/src/schema/workspace.ts
index 72f63c4ec..5e9f0f866 100644
--- a/packages/db/src/schema/workspace.ts
+++ b/packages/db/src/schema/workspace.ts
@@ -1,15 +1,24 @@
import { relations, sql } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
+import { createSelectSchema } from "drizzle-zod";
+import { z } from "zod";
import { page } from "./page";
import { usersToWorkspaces } from "./user";
+const plan = ["free", "pro"] as const;
+
export const workspace = sqliteTable("workspace", {
id: integer("id").primaryKey(),
slug: text("slug").notNull().unique(), // we love random words
- stripeId: text("stripe_id", { length: 256 }).unique(),
name: text("name"),
+ stripeId: text("stripe_id", { length: 256 }).unique(),
+ subscriptionId: text("subscription_id"),
+ plan: text("plan", plan),
+ endsAt: integer("ends_at", { mode: "timestamp" }),
+ paidUntil: integer("paid_until", { mode: "timestamp" }),
+
createdAt: integer("created_at", { mode: "timestamp" }).default(
sql`(strftime('%s', 'now'))`,
),
@@ -22,3 +31,11 @@ export const workspaceRelations = relations(workspace, ({ many }) => ({
usersToWorkspaces: many(usersToWorkspaces),
pages: many(page),
}));
+
+export const selectWorkspaceSchema = createSelectSchema(workspace).extend({
+ plan: z
+ .enum(plan)
+ .nullable()
+ .default("free")
+ .transform((val) => val ?? "free"),
+});
diff --git a/packages/plans/index.ts b/packages/plans/index.ts
index e029fdbb3..69df41048 100644
--- a/packages/plans/index.ts
+++ b/packages/plans/index.ts
@@ -10,7 +10,7 @@ type Plan = {
};
};
-export const allPlans: Record<"free", Plan> = {
+export const allPlans: Record<"free" | "pro", Plan> = {
free: {
limits: {
monitors: 5,
@@ -18,4 +18,11 @@ export const allPlans: Record<"free", Plan> = {
periodicity: ["10m", "30m", "1h"],
},
},
+ pro: {
+ limits: {
+ monitors: 20,
+ "status-pages": 5,
+ periodicity: ["1m", "5m", "10m", "30m", "1h"],
+ },
+ },
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 33aa6d2b1..a15a3d874 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -76,8 +76,8 @@ importers:
apps/web:
dependencies:
'@clerk/nextjs':
- specifier: 4.23.1
+ specifier: 4.23.2
'@hookform/resolvers':
specifier: 3.1.1
version: 3.1.1([email protected])
@@ -150,6 +150,9 @@ importers:
'@radix-ui/react-tooltip':
specifier: 1.0.6
+ '@stripe/stripe-js':
+ specifier: 2.0.0
+ version: 2.0.0
'@t3-oss/env-nextjs':
specifier: 0.4.1
@@ -246,6 +249,9 @@ importers:
shiki:
specifier: 0.14.3
version: 0.14.3
+ stripe:
+ specifier: 12.17.0
+ version: 12.17.0
superjson:
specifier: 1.13.1
version: 1.13.1
@@ -350,6 +356,9 @@ importers:
'@openstatus/plans':
specifier: workspace:^
version: link:../plans
+ '@t3-oss/env-core':
+ specifier: 0.6.0
'@trpc/client':
specifier: 10.35.0
version: 10.35.0(@trpc/[email protected])
@@ -359,6 +368,9 @@ importers:
random-word-slugs:
specifier: 0.1.7
version: 0.1.7
+ stripe:
+ specifier: 12.17.0
+ version: 12.17.0
superjson:
specifier: 1.13.1
version: 1.13.1
@@ -410,7 +422,7 @@ importers:
packages/db:
dependencies:
'@libsql/client':
- specifier: ^0.3.1
+ specifier: 0.3.1
'@t3-oss/env-core':
specifier: 0.6.0
@@ -422,7 +434,7 @@ importers:
specifier: 0.27.2
version: 0.27.2(@libsql/[email protected])
drizzle-zod:
- specifier: ^0.4.4
+ specifier: 0.4.4
zod:
specifier: 3.21.4
@@ -432,7 +444,7 @@ importers:
specifier: 20.3.1
version: 20.3.1
bufferutil:
- specifier: ^4.0.7
+ specifier: 4.0.7
version: 4.0.7
drizzle-kit:
specifier: 0.19.10
@@ -441,7 +453,7 @@ importers:
specifier: 0.1.13
version: 0.1.13
ts-node:
- specifier: ^10.9.1
+ specifier: 10.9.1
version: 10.9.1(@types/[email protected])([email protected])
tsconfig:
specifier: workspace:^
@@ -450,7 +462,7 @@ importers:
specifier: 5.1.6
version: 5.1.6
utf-8-validate:
- specifier: ^6.0.3
+ specifier: 6.0.3
version: 6.0.3
packages/emails:
@@ -966,6 +978,20 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-Sj541JrpqAn1A/UwdyDBxFV3stq2A/Pe/8HdPTG3Cct6briPyavfi46O5s1+L3BSvUcKUY+UbM0+8VsoCNFi4w==}
+ engines: {node: '>=14'}
+ dependencies:
+ '@clerk/types': 3.49.0
+ '@peculiar/webcrypto': 1.4.1
+ '@types/node': 16.18.6
+ cookie: 0.5.0
+ deepmerge: 4.2.2
+ node-fetch-native: 1.0.1
+ snakecase-keys: 5.4.4
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-X0h7I2aPxc3cY7f5ZOaUrrgYjYXSOWbWOCyNuF4rZeW1L6ED8mZEFpQV4+EluUgAomxgGrt8kdMIyMwSsGw3Tg==}
engines: {node: '>=14'}
@@ -979,6 +1005,18 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-6MJa8ecr22qHhTfdkMMIJGctMBqj01fLJ4vmfZvr22tIkwkPXoeYJd5XcFKuSoO2dXc1eHD/F9i/HdCqGm68gw==}
+ engines: {node: '>=14'}
+ peerDependencies:
+ react: '>=16'
+ dependencies:
+ '@clerk/shared': 0.21.0([email protected])
+ '@clerk/types': 3.49.0
+ react: 18.2.0
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-KR8L0zX9YWms8ScZPXLfBmEHYxFWuI+JeXJ/UtYhTP5qu2LBoAOBbZI0zsYPwTKE2L/1i2Gga6m3whmVAJfmzg==}
engines: {node: '>=14'}
@@ -993,6 +1031,20 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-7xYPsLSeGO5XoP0No/9m2dsCMezwtmiYGKOwWzt41ZzJNFlU0rfqYF3VOZEsbtQlc3ZXeU+67ItjoJYrf3kT6A==}
+ engines: {node: '>=14'}
+ dependencies:
+ '@clerk/backend': 0.27.0
+ '@clerk/types': 3.49.0
+ '@types/cookies': 0.7.7
+ '@types/express': 4.17.14
+ '@types/node-fetch': 2.6.2
+ camelcase-keys: 6.2.2
+ snakecase-keys: 3.2.1
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-r7lSisqvUvyvlakn69AN+3EDBgIuEQQBR7Hn/MR71UT7zfKvdsRCyTENsj+rxDgfb8a4guiytDJGk1lOewLLvQ==}
engines: {node: '>=14'}
@@ -1012,6 +1064,25 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-99bSVu9r1E9MxybO/6mmPAufSKq4KU7SFeMVkylX7UF8sy5t/LE9cLHyc+9jitcCGgZNai9Om4sj1WIgkNOP8w==}
+ engines: {node: '>=14'}
+ peerDependencies:
+ next: '>=10'
+ react: ^17.0.2 || ^18.0.0-0
+ react-dom: ^17.0.2 || ^18.0.0-0
+ dependencies:
+ '@clerk/backend': 0.27.0
+ '@clerk/clerk-react': 4.23.2([email protected])
+ '@clerk/clerk-sdk-node': 4.12.2
+ '@clerk/types': 3.49.0
+ path-to-regexp: 6.2.1
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-VbJZQ3DwF35qPNTa1u2r/UO0vEfk4Gzf8dzbbma6fLPRILAFovQGYb5Cwvmef+Qj7S0XPpOlW1lSYHBHL326gQ==}
peerDependencies:
@@ -1023,6 +1094,17 @@ packages:
swr: 1.3.0([email protected])
dev: false
+ resolution: {integrity: sha512-tkV2OAddFMPBHDjcMbtNNrV3NQD+hGKf2hn3TKv1mRJNZ2oR5Bfk8r0bkaqwoqxX8ndkbHLCa9gwR8SWO7GGow==}
+ peerDependencies:
+ react: '>=16'
+ dependencies:
+ glob-to-regexp: 0.4.1
+ js-cookie: 3.0.1
+ react: 18.2.0
+ swr: 1.3.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-bpSSfqdrw4iYCLlJ8UVN8HWMkA12wOH0lICdjnefPKKm1qO3yb8P5p6jmaCckcwF77unMECAslO2q2ocZcO1QA==}
engines: {node: '>=14'}
@@ -1030,6 +1112,13 @@ packages:
csstype: 3.1.1
dev: false
+ resolution: {integrity: sha512-vAx5R/iYfsgIaIDMiDr6ZKQnAneAmRrUVYz6KCtPG6/hnEAnRYhwXpEUi89e5G0BFmuUfSxe/N/Anfc1PNteXQ==}
+ engines: {node: '>=14'}
+ dependencies:
+ csstype: 3.1.1
+ dev: false
+
resolution: {integrity: sha512-v0BqORYamk1koxDon6femDGLWSL7P78vYTyOU5nFaALnmNALL+ktgdHvWbxzzBBJIKS7kv3XvM/DqNwiLcgFTA==}
peerDependencies:
@@ -1307,7 +1396,6 @@ packages:
cpu: [arm64]
os: [android]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1343,7 +1431,6 @@ packages:
cpu: [arm]
os: [android]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1379,7 +1466,6 @@ packages:
cpu: [x64]
os: [android]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1415,7 +1501,6 @@ packages:
cpu: [arm64]
os: [darwin]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1451,7 +1536,6 @@ packages:
cpu: [x64]
os: [darwin]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1487,7 +1571,6 @@ packages:
cpu: [arm64]
os: [freebsd]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1523,7 +1606,6 @@ packages:
cpu: [x64]
os: [freebsd]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1559,7 +1641,6 @@ packages:
cpu: [arm64]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1595,7 +1676,6 @@ packages:
cpu: [arm]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1631,7 +1711,6 @@ packages:
cpu: [ia32]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1667,7 +1746,6 @@ packages:
cpu: [loong64]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1703,7 +1781,6 @@ packages:
cpu: [mips64el]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1739,7 +1816,6 @@ packages:
cpu: [ppc64]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1775,7 +1851,6 @@ packages:
cpu: [riscv64]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1811,7 +1886,6 @@ packages:
cpu: [s390x]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1847,7 +1921,6 @@ packages:
cpu: [x64]
os: [linux]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1883,7 +1956,6 @@ packages:
cpu: [x64]
os: [netbsd]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1919,7 +1991,6 @@ packages:
cpu: [x64]
os: [openbsd]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1955,7 +2026,6 @@ packages:
cpu: [x64]
os: [sunos]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -1991,7 +2061,6 @@ packages:
cpu: [arm64]
os: [win32]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -2027,7 +2096,6 @@ packages:
cpu: [ia32]
os: [win32]
requiresBuild: true
- dev: false
optional: true
/@esbuild/[email protected]:
@@ -2063,7 +2131,6 @@ packages:
cpu: [x64]
os: [win32]
requiresBuild: true
- dev: false
optional: true
@@ -4865,6 +4932,10 @@ packages:
resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}
dev: false
+ /@stripe/[email protected]:
+ resolution: {integrity: sha512-SxZnf192En0uAfgbigUIj7oJYaXgGc5AI1aos59YXvO8DPeLI0AtT4oMg/Wuk17wbpquEv73+akyCe7xdEjGlA==}
+ dev: false
+
resolution: {integrity: sha512-4C7nX/dvpzB7za4Ql9K81xK3HPxCpHMgwTZVyf+9JQ6VUbn9jjZVN7/Nkdz/Ugzs2CSjqnL/UPXroiVBVHUWUw==}
dependencies:
@@ -7182,8 +7253,8 @@ packages:
camelcase: 7.0.1
chalk: 5.3.0
commander: 9.5.0
- esbuild: 0.18.16
- esbuild-register: 3.4.2([email protected])
+ esbuild: 0.18.17
+ esbuild-register: 3.4.2([email protected])
glob: 8.1.0
hanji: 0.0.5
json-diff: 0.9.0
@@ -7430,13 +7501,13 @@ packages:
es6-symbol: 3.1.3
dev: true
resolution: {integrity: sha512-kG/XyTDyz6+YDuyfB9ZoSIOOmgyFCH+xPRtsCa8W85HLRV5Csp+o3jWVbOSHgSLfyLc5DmP+KFDNwty4mEjC+Q==}
peerDependencies:
esbuild: '>=0.12 <1'
dependencies:
debug: 4.3.4
- esbuild: 0.18.16
+ esbuild: 0.18.17
transitivePeerDependencies:
- supports-color
dev: true
@@ -7559,7 +7630,6 @@ packages:
'@esbuild/win32-arm64': 0.18.17
'@esbuild/win32-ia32': 0.18.17
'@esbuild/win32-x64': 0.18.17
- dev: false
resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==}
@@ -11787,6 +11857,13 @@ packages:
engines: {node: '>=6.0.0'}
dev: false
+ resolution: {integrity: sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==}
+ engines: {node: '>=0.6'}
+ dependencies:
+ side-channel: 1.0.4
+ dev: false
+
resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==}
dev: false
@@ -12772,6 +12849,14 @@ packages:
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-f8GhS2LQlGCDZ1Akyu57txgSWyLUEYf0yZYS7x2aTKJXVua5lLmmgfJFFYHfTgEdS5P6rurf0Ghcf/HVLggv5g==}
+ engines: {node: '>=12.*'}
+ dependencies:
+ '@types/node': 20.3.1
+ qs: 6.11.2
+ dev: false
+
resolution: {integrity: sha512-zKI5gN/zb7LS/Vm0eUwjmjrXWw8IMtyA8aPBJZdYiQTXj4+wQ3IucOLIOnF7zCHxvW8UhIGh/uZh/t9zEHXNTQ==}
dependencies: