Skip to content

Open-source status page, incident response and uptime monitoring

chore: quantity addons (#1697)

Maximilian Kaske13110804a878
diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
index 294669ebd..8537e82b1 100644
--- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
@@ -127,7 +127,7 @@ export function Client() {
if (!workspace) return null;
- const addons = allPlans[workspace.plan].addons;
+ const planAddons = allPlans[workspace.plan].addons;
return (
<SectionGroup>
@@ -179,8 +179,7 @@ export function Client() {
</FormCardDescription>
</FormCardHeader>
<div className="flex flex-col gap-2 pt-4">
- {/* TODO: redirect to stripe product */}
- {addons["email-domain-protection"] ? (
+ {planAddons["email-domain-protection"] ? (
<BillingAddons
label="Magic Link (Auth)"
description="Only allow user with a given email domain to access the status page."
@@ -188,7 +187,7 @@ export function Client() {
workspace={workspace}
/>
) : null}
- {addons["white-label"] ? (
+ {planAddons["white-label"] ? (
<BillingAddons
label="White Label"
description="Remove the 'powered by openstatus.dev' footer from your status pages."
@@ -196,7 +195,15 @@ export function Client() {
workspace={workspace}
/>
) : null}
- {Object.keys(addons).length === 0 ? (
+ {planAddons["status-pages"] ? (
+ <BillingAddons
+ label="Status Pages"
+ description="Create and manage status pages for your workspace."
+ addon="status-pages"
+ workspace={workspace}
+ />
+ ) : null}
+ {Object.keys(planAddons).length === 0 ? (
<EmptyStateContainer>
<EmptyStateTitle>No add-ons available</EmptyStateTitle>
</EmptyStateContainer>
diff --git a/apps/dashboard/src/components/content/billing-addons.tsx b/apps/dashboard/src/components/content/billing-addons.tsx
index 9f2d38a2f..82efe1df9 100644
--- a/apps/dashboard/src/components/content/billing-addons.tsx
+++ b/apps/dashboard/src/components/content/billing-addons.tsx
@@ -13,15 +13,18 @@ import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { useCookieState } from "@/hooks/use-cookie-state";
+import { ButtonGroup } from "@/components/ui/button-group";
import { useTRPC } from "@/lib/trpc/client";
import type { RouterOutputs } from "@openstatus/api";
+import { allPlans } from "@openstatus/db/src/schema/plan/config";
import type { Addons } from "@openstatus/db/src/schema/plan/schema";
import { getAddonPriceConfig } from "@openstatus/db/src/schema/plan/utils";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { isTRPCClientError } from "@trpc/client";
-import { Check } from "lucide-react";
-import { useState, useTransition } from "react";
+import { Check, MinusIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState, useTransition } from "react";
import { toast } from "sonner";
+import { Input } from "../ui/input";
type Workspace = RouterOutputs["workspace"]["get"];
@@ -32,6 +35,12 @@ interface BillingAddonsProps {
workspace: Workspace;
}
+interface PriceConfig {
+ value: number;
+ currency: string;
+ locale: string;
+}
+
export function BillingAddons({
label,
description,
@@ -52,24 +61,39 @@ export function BillingAddons({
},
}),
);
-
const plan = workspace.plan;
- const value = workspace.limits[addon];
+ const defaultLimit = allPlans[workspace.plan].limits[addon];
+ const workspaceLimit = workspace.limits[addon];
+ const defaultValue =
+ typeof workspaceLimit === "number" && typeof defaultLimit === "number"
+ ? // current value - default value to evaluate the difference
+ workspaceLimit - defaultLimit
+ : workspaceLimit;
+ const [value, setValue] = useState<number | boolean>(defaultValue);
const price = getAddonPriceConfig(plan, addon, currency);
+ // Reset value when modal opens
+ useEffect(() => {
+ if (open) {
+ setValue(defaultValue);
+ }
+ }, [open, defaultValue]);
+
function submitAction() {
startTransition(async () => {
try {
+ // toggle the value if it's a boolean otherwise use the value
+ const newValue = typeof value === "boolean" ? !value : value;
const promise = checkoutSessionMutation.mutateAsync({
workspaceSlug: workspace.slug,
feature: addon,
- remove: value,
+ value: newValue,
});
toast.promise(promise, {
loading: "Updating...",
success: () => {
setOpen(false);
- return value ? "Removed" : "Added";
+ return "Billing information updated";
},
error: (error) => {
if (isTRPCClientError(error)) {
@@ -84,78 +108,177 @@ export function BillingAddons({
}
});
}
+ const hasAddon =
+ typeof defaultValue === "number"
+ ? defaultValue > 0
+ : defaultValue !== defaultLimit;
+ const isQuantity = typeof value === "number";
return (
- <div className="flex flex-col gap-2">
- <div className="flex flex-col justify-between gap-1.5 sm:flex-row">
- <div className="space-y-0.5 text-sm">
- <Label>{label}</Label>
- <div className="truncate text-muted-foreground">{description}</div>
- </div>
- <div className="flex items-center gap-2">
- {value ? <Check className="size-4 text-success" /> : null}
- <span className="font-mono text-foreground text-sm">
- {price
- ? new Intl.NumberFormat(price.locale, {
- style: "currency",
- currency: price.currency,
- }).format(price.value)
- : "N/A"}
- /mo.
- </span>
- <AlertDialog open={open} onOpenChange={setOpen}>
+ <AlertDialog open={open} onOpenChange={setOpen}>
+ <div className="flex flex-col gap-2">
+ <div className="grid grid-cols-3 gap-1.5 lg:grid-cols-5">
+ <div className="col-span-3 space-y-0.5 text-sm">
+ <Label>{label}</Label>
+ <div className="text-muted-foreground">{description}</div>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <span className="font-mono text-foreground text-sm">
+ {formatPrice(price)}
+ {isQuantity ? "/mo./each" : "/mo."}
+ </span>
+ {hasAddon && !isQuantity ? (
+ <Check className="size-4 text-success" />
+ ) : null}
+ {hasAddon && isQuantity ? (
+ <span className="font-mono text-success">+{defaultValue}</span>
+ ) : null}
+ </div>
+ <div className="col-span-2 flex items-center justify-end gap-1.5 lg:col-span-1">
<AlertDialogTrigger asChild>
<Button size="sm" variant="secondary">
- {value ? "Remove" : "Add"}
+ {getButtonLabel(hasAddon, value)}
</Button>
</AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{label}</AlertDialogTitle>
- <AlertDialogDescription>
- {value ? (
- <>
- {label} will be removed from your subscription. You will
- save{" "}
- {price
- ? new Intl.NumberFormat(price.locale, {
- style: "currency",
- currency: price.currency,
- }).format(price.value)
- : "N/A"}
- /mo. on your next billing cycle.
- </>
- ) : (
- <>
- {label} will be added to your subscription. You will be
- charged an additional{" "}
- {price
- ? new Intl.NumberFormat(price.locale, {
- style: "currency",
- currency: price.currency,
- }).format(price.value)
- : "N/A"}
- /mo. on your next billing cycle.
- </>
- )}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- submitAction();
- }}
- disabled={isPending}
- >
- {isPending ? "Updating..." : value ? "Remove" : "Add"}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ </div>
</div>
</div>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{label}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {getDialogDescription(label, price, value, hasAddon)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {isQuantity &&
+ typeof value === "number" &&
+ typeof defaultLimit === "number" ? (
+ <QuantityControl
+ value={value}
+ setValue={setValue}
+ defaultLimit={defaultLimit}
+ />
+ ) : null}
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={(e) => {
+ e.preventDefault();
+ submitAction();
+ }}
+ disabled={
+ isPending ||
+ (typeof value === "number" &&
+ typeof defaultValue === "number" &&
+ value === defaultValue)
+ }
+ >
+ {getButtonLabel(hasAddon, value, isPending)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+// NOTE: could move to lib/formatter.ts
+function formatPrice(price: PriceConfig | null) {
+ if (!price) return "N/A";
+ return new Intl.NumberFormat(price.locale, {
+ style: "currency",
+ currency: price.currency,
+ }).format(price.value);
+}
+
+function getButtonLabel(
+ hasAddon: boolean,
+ value: number | boolean,
+ isPending = false,
+) {
+ if (isPending) return "Updating...";
+
+ const isBoolean = typeof value === "boolean";
+ const isQuantity = typeof value === "number";
+
+ if (isQuantity) return "Update";
+
+ if (isBoolean) {
+ return hasAddon ? "Remove" : "Add";
+ }
+
+ return null;
+}
+
+function getDialogDescription(
+ label: string,
+ price: PriceConfig | null,
+ value: number | boolean,
+ hasAddon: boolean,
+) {
+ const formattedPrice = formatPrice(price);
+ const isBoolean = typeof value === "boolean";
+ const isQuantity = typeof value === "number";
+ const priceSuffix = isQuantity ? "/mo./each" : "/mo.";
+
+ if (isBoolean) {
+ if (hasAddon) {
+ return `${label} will be removed from your subscription. You will save ${formattedPrice}${priceSuffix} on your next billing cycle.`;
+ }
+ return `${label} will be added to your subscription. You will be charged an additional ${formattedPrice}${priceSuffix} on your next billing cycle.`;
+ }
+
+ if (isQuantity) {
+ return `${label} will be updated to ${value} on your next billing cycle. You will be charged ${formattedPrice}${priceSuffix} on your next billing cycle.`;
+ }
+}
+
+function QuantityControl({
+ value,
+ setValue,
+ defaultLimit,
+}: {
+ value: number;
+ setValue: (value: number) => void;
+ defaultLimit: number | boolean;
+}) {
+ const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const newValue = Number.parseInt(e.target.value);
+ if (Number.isNaN(newValue)) {
+ setValue(typeof defaultLimit === "number" ? defaultLimit : 0);
+ } else {
+ setValue(
+ Math.max(typeof defaultLimit === "number" ? defaultLimit : 0, newValue),
+ );
+ }
+ };
+
+ return (
+ <div className="flex items-center justify-center gap-2 py-2">
+ <ButtonGroup aria-label="Quantity" className="h-fit">
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => setValue(value - 1)}
+ disabled={value <= 0}
+ >
+ <MinusIcon />
+ </Button>
+ <Input
+ type="number"
+ value={value}
+ className="w-16 text-right"
+ step={1}
+ min={0}
+ onChange={handleChange}
+ />
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => setValue(value + 1)}
+ >
+ <PlusIcon />
+ </Button>
+ </ButtonGroup>
</div>
);
}
diff --git a/apps/dashboard/src/components/data-table/billing/data-table.tsx b/apps/dashboard/src/components/data-table/billing/data-table.tsx
index b6c270145..cbcbd71b8 100644
--- a/apps/dashboard/src/components/data-table/billing/data-table.tsx
+++ b/apps/dashboard/src/components/data-table/billing/data-table.tsx
@@ -159,17 +159,28 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {
currency,
);
if (!price) return null;
+
+ const isNumber = typeof limitValue === "number";
return (
<div>
- <span className="text-muted-foreground">
- add-on{" "}
+ <span>
+ {isNumber
+ ? new Intl.NumberFormat("us")
+ .format(limitValue)
+ .toString()
+ : null}
</span>
<span>
- {new Intl.NumberFormat(price.locale, {
- style: "currency",
- currency: price.currency,
- }).format(price.value)}
- /mo.
+ <span className="text-muted-foreground">
+ {isNumber ? " + " : ""}
+ </span>
+ <span>
+ {new Intl.NumberFormat(price.locale, {
+ style: "currency",
+ currency: price.currency,
+ }).format(price.value)}
+ {isNumber ? "/mo./each" : "/mo."}
+ </span>
</span>
</div>
);
diff --git a/apps/dashboard/src/components/ui/button-group.tsx b/apps/dashboard/src/components/ui/button-group.tsx
new file mode 100644
index 000000000..16dd752e2
--- /dev/null
+++ b/apps/dashboard/src/components/ui/button-group.tsx
@@ -0,0 +1,83 @@
+import { Slot } from "@radix-ui/react-slot";
+import { type VariantProps, cva } from "class-variance-authority";
+
+import { Separator } from "@/components/ui/separator";
+import { cn } from "@/lib/utils";
+
+const buttonGroupVariants = cva(
+ "flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
+ {
+ variants: {
+ orientation: {
+ horizontal:
+ "[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
+ vertical:
+ "flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
+ },
+ },
+ defaultVariants: {
+ orientation: "horizontal",
+ },
+ },
+);
+
+function ButtonGroup({
+ className,
+ orientation,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="button-group"
+ data-orientation={orientation}
+ className={cn(buttonGroupVariants({ orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupText({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot : "div";
+
+ return (
+ <Comp
+ className={cn(
+ "flex items-center gap-2 rounded-md border bg-muted px-4 font-medium text-sm shadow-xs [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupSeparator({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="button-group-separator"
+ orientation={orientation}
+ className={cn(
+ "!m-0 relative self-stretch bg-input data-[orientation=vertical]:h-auto",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ ButtonGroup,
+ ButtonGroupSeparator,
+ ButtonGroupText,
+ buttonGroupVariants,
+};
diff --git a/apps/dashboard/src/components/ui/button.tsx b/apps/dashboard/src/components/ui/button.tsx
index 11621b95f..89e974f65 100644
--- a/apps/dashboard/src/components/ui/button.tsx
+++ b/apps/dashboard/src/components/ui/button.tsx
@@ -26,6 +26,8 @@ const buttonVariants = cva(
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
+ "icon-sm": "size-8",
+ "icon-lg": "size-10",
},
},
defaultVariants: {
@@ -37,8 +39,8 @@ const buttonVariants = cva(
function Button({
className,
- variant,
- size,
+ variant = "default",
+ size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
@@ -50,6 +52,8 @@ function Button({
return (
<Comp
data-slot="button"
+ data-variant={variant}
+ data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
diff --git a/apps/dashboard/src/components/ui/separator.tsx b/apps/dashboard/src/components/ui/separator.tsx
index 8fc1c16d4..5e944795f 100644
--- a/apps/dashboard/src/components/ui/separator.tsx
+++ b/apps/dashboard/src/components/ui/separator.tsx
@@ -13,7 +13,7 @@ function Separator({
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
- data-slot="separator-root"
+ data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
diff --git a/apps/web/src/content/pages/unrelated/pricing.mdx b/apps/web/src/content/pages/unrelated/pricing.mdx
index b56ac72e1..f48599e71 100644
--- a/apps/web/src/content/pages/unrelated/pricing.mdx
+++ b/apps/web/src/content/pages/unrelated/pricing.mdx
@@ -10,9 +10,9 @@ category: "Company"
data={{
headers: [
"Features comparison",
- <>$0/month <span className="text-muted-foreground">| Hobby</span></>,
- <>$30/month <span className="text-muted-foreground">| Starter</span></>,
- <>$100/month <span className="text-muted-foreground">| Pro</span></>,
+ <>$0/month<span className="text-muted-foreground">|Hobby</span></>,
+ <>$30/month<span className="text-muted-foreground">|Starter</span></>,
+ <>$100/month<span className="text-muted-foreground">|Pro</span></>,
],
rows: [
[<a href="/uptime-monitoring"><strong>Monitors</strong></a>, "", "", ""],
@@ -27,15 +27,15 @@ category: "Company"
["OTel Exporter", "", "", "+"],
["Number of on-demand checks", "30/mo.", "100/mo.", "300/mo."],
[<a href="/status-page"><strong>Status Pages</strong></a>, "", "", ""],
- ["Number of status pages", "1", "1", "5"],
+ ["Number of status pages", "1", "1 +$20/mo./each", "5 +$20/mo./each"],
["Maintenance status", "+", "+", "+"],
["Toggle numbers visibility", "+", "+", "+"],
["Subscribers", "", "+", "+"],
["Custom domain", "", "+", "+"],
- ["White Label", "", "add-on $300/mo.", "add-on $300/mo."],
+ ["White Label", "", "$300/mo.", "$300/mo."],
[<strong>Audience</strong>, "", "", ""],
["Password Protection", "", "+", "+"],
- ["Email Authentification", "", "add-on $100/mo.", "add-on $100/mo."],
+ ["Email Authentification", "", "$100/mo.", "$100/mo."],
[<strong>Alerts</strong>, "", "", ""],
["Slack, Discord, Email, Webhook, ntfy.sh", "+", "+", "+"],
["WhatsApp", "", "+", "+"],
diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.ts
index 78b3b74d4..f54e46d2a 100644
--- a/packages/api/src/router/stripe/index.ts
+++ b/packages/api/src/router/stripe/index.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { eq } from "@openstatus/db";
+import { count, eq, schema } from "@openstatus/db";
import {
selectWorkspaceSchema,
user,
@@ -9,6 +9,7 @@ import {
workspacePlans,
} from "@openstatus/db/src/schema";
+import { allPlans } from "@openstatus/db/src/schema/plan/config";
import { addons } from "@openstatus/db/src/schema/plan/schema";
import { updateAddonInLimits } from "@openstatus/db/src/schema/plan/utils";
import { TRPCError } from "@trpc/server";
@@ -176,7 +177,7 @@ export const stripeRouter = createTRPCRouter({
z.object({
workspaceSlug: z.string(),
feature: z.enum(addons),
- remove: z.boolean().optional(),
+ value: z.union([z.boolean(), z.number()]),
}),
)
.mutation(async (opts) => {
@@ -226,30 +227,66 @@ export const stripeRouter = createTRPCRouter({
const priceId = getPriceIdForFeature(opts.input.feature);
- if (opts.input.remove) {
- const items = await stripe.subscriptionItems.list({
- subscription: sub.subscriptions?.data[0]?.id,
+ if (!priceId) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid feature",
});
- const item = items.data.find((item) => item.price.id === priceId);
- if (item) {
- await stripe.subscriptionItems.del(item.id);
+ }
+
+ const quantity =
+ typeof opts.input.value === "number" ? opts.input.value : 1;
+
+ // We need to check the total of status page
+ if (opts.input.feature === "status-pages") {
+ const statusPageCt = await opts.ctx.db
+ .select({ count: count() })
+ .from(schema.page)
+ .where(eq(schema.page.workspaceId, result.id))
+ .get();
+ const pageCount = statusPageCt?.count ?? 0;
+ if (pageCount > quantity + allPlans[ws.plan].limits["status-pages"]) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `You already have ${pageCount} status pages, please delete some status page first.`,
+ });
}
+ }
+
+ const items = await stripe.subscriptionItems.list({
+ subscription: sub.subscriptions?.data[0]?.id,
+ });
+
+ const item = items.data.find((item) => item.price.id === priceId);
+
+ if (!opts.input.value && typeof opts.input.value === "boolean" && item) {
+ await stripe.subscriptionItems.del(item.id);
+ } else if (typeof opts.input.value === "number" && item) {
+ await stripe.subscriptionItems.update(item.id, {
+ quantity,
+ });
} else {
await stripe.subscriptionItems.create({
price: priceId,
subscription: sub.subscriptions?.data[0]?.id,
- quantity: 1,
+ quantity,
});
}
- // NOTE: update the limits based on the feature type
+ const defaultLimit = allPlans[ws.plan].limits[opts.input.feature];
+ const newValue =
+ typeof opts.input.value === "number" && typeof defaultLimit === "number"
+ ? opts.input.value + defaultLimit
+ : opts.input.value;
const newLimits = updateAddonInLimits(
ws.limits,
opts.input.feature,
- opts.input.remove ? "remove" : "add",
+ newValue,
);
+ console.log("new Limits");
+
await opts.ctx.db
.update(workspace)
.set({ limits: JSON.stringify(newLimits) })
diff --git a/packages/api/src/router/stripe/utils.ts b/packages/api/src/router/stripe/utils.ts
index af8380a8e..aa3256691 100644
--- a/packages/api/src/router/stripe/utils.ts
+++ b/packages/api/src/router/stripe/utils.ts
@@ -84,6 +84,17 @@ export const FEATURES = [
},
},
},
+ {
+ feature: "status-pages",
+ price: {
+ monthly: {
+ priceIds: {
+ test: "price_1Slrk8BXJcTfzsyJXQxshFU4",
+ production: "price_1SlrkHBXJcTfzsyJIxHeKUYe",
+ },
+ },
+ },
+ },
] satisfies Array<{
feature: keyof Addons;
price: {
diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.ts
index 4389f9b46..bcedb47b8 100644
--- a/packages/api/src/router/stripe/webhook.ts
+++ b/packages/api/src/router/stripe/webhook.ts
@@ -54,30 +54,41 @@ export const webhookRouter = createTRPCRouter({
});
}
- for (const item of subscription.items.data) {
- console.log(item);
- const feature = getFeatureFromPriceId(item.price.id);
- if (!feature) {
- continue;
- }
- const _ws = await opts.ctx.db
- .select()
- .from(workspace)
- .where(eq(workspace.stripeId, customerId))
- .get();
-
- const ws = selectWorkspaceSchema.parse(_ws);
-
- const newLimits = updateAddonInLimits(ws.limits, feature.feature, "add");
-
- await opts.ctx.db
- .update(workspace)
- .set({
- limits: JSON.stringify(newLimits),
- })
- .where(eq(workspace.id, result.id))
- .run();
- }
+ // for (const item of subscription.items.data) {
+ // const feature = getFeatureFromPriceId(item.price.id);
+ // if (!feature) {
+ // continue;
+ // }
+ // const _ws = await opts.ctx.db
+ // .select()
+ // .from(workspace)
+ // .where(eq(workspace.stripeId, customerId))
+ // .get();
+
+ // const ws = selectWorkspaceSchema.parse(_ws);
+
+ // const currentValue = ws.limits[feature.feature];
+ // const newValue =
+ // typeof currentValue === "boolean"
+ // ? true
+ // : typeof currentValue === "number"
+ // ? currentValue + 1
+ // : currentValue;
+
+ // const newLimits = updateAddonInLimits(
+ // ws.limits,
+ // feature.feature,
+ // newValue,
+ // );
+
+ // await opts.ctx.db
+ // .update(workspace)
+ // .set({
+ // limits: JSON.stringify(newLimits),
+ // })
+ // .where(eq(workspace.id, result.id))
+ // .run();
+ // }
const customer = await stripe.customers.retrieve(customerId);
if (!customer.deleted && customer.email) {
@@ -137,10 +148,18 @@ export const webhookRouter = createTRPCRouter({
const ws = selectWorkspaceSchema.parse(_ws);
+ const currentValue = ws.limits[feature.feature];
+ const newValue =
+ typeof currentValue === "boolean"
+ ? true
+ : typeof currentValue === "number"
+ ? currentValue + 1
+ : currentValue;
+
const newLimits = updateAddonInLimits(
ws.limits,
feature.feature,
- "add",
+ newValue,
);
await opts.ctx.db
diff --git a/packages/db/src/schema/plan/config.ts b/packages/db/src/schema/plan/config.ts
index 02337d9ef..1d0c76d64 100644
--- a/packages/db/src/schema/plan/config.ts
+++ b/packages/db/src/schema/plan/config.ts
@@ -79,6 +79,13 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
INR: 30_000,
},
},
+ "status-pages": {
+ price: {
+ USD: 20,
+ EUR: 20,
+ INR: 2_000,
+ },
+ },
},
limits: {
version: undefined,
@@ -136,6 +143,13 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
INR: 30_000,
},
},
+ "status-pages": {
+ price: {
+ USD: 20,
+ EUR: 20,
+ INR: 2_000,
+ },
+ },
},
limits: {
version: undefined,
diff --git a/packages/db/src/schema/plan/schema.ts b/packages/db/src/schema/plan/schema.ts
index 11294b4fb..e421e1b3c 100644
--- a/packages/db/src/schema/plan/schema.ts
+++ b/packages/db/src/schema/plan/schema.ts
@@ -68,6 +68,7 @@ export type Price = z.infer<typeof priceSchema>;
export const addons = [
"email-domain-protection",
"white-label",
+ "status-pages",
] as const satisfies Partial<keyof Limits>[];
export const addonsSchema = z.partialRecord(
diff --git a/packages/db/src/schema/plan/utils.ts b/packages/db/src/schema/plan/utils.ts
index d241781bf..1f07ab735 100644
--- a/packages/db/src/schema/plan/utils.ts
+++ b/packages/db/src/schema/plan/utils.ts
@@ -129,33 +129,27 @@ export function getPlansForLimit(
}
/**
- * Add or remove an addon from limits
- * Automatically infers addon type (toggle/quantity) from the limit field type
+ * Update an addon value in limits
* @param limits - Current workspace limits
- * @param addon - Addon key to add/remove
- * @param action - "add" to enable/increment, "remove" to disable/decrement
- * @param quantity - Optional quantity for quantity-based addons (defaults to 1)
+ * @param addon - Addon key to update
+ * @param value - The value to set (boolean for toggle addons, number for quantity addons)
* @returns Updated limits object
*/
export function updateAddonInLimits(
limits: Limits,
addon: keyof Addons,
- action: "add" | "remove",
- _quantity = 1,
+ value: boolean | number,
): Limits {
const currentValue = limits[addon];
const newLimits = { ...limits };
- // Infer addon type from the limit field type
- if (typeof currentValue === "boolean") {
- // Toggle addon: boolean on/off
- newLimits[addon] = action === "add";
- } else if (typeof currentValue === "number") {
- // Quantity addon: increment/decrement
- // newLimits[addon] = Math.max(
- // 0,
- // currentValue + (action === "add" ? quantity : -quantity)
- // ); // Don't go below 0
+ // Infer addon type from the limit field type and set the value
+ if (typeof currentValue === "boolean" && typeof value === "boolean") {
+ // Toggle addon: set boolean value
+ (newLimits[addon] as boolean) = value;
+ } else if (typeof currentValue === "number" && typeof value === "number") {
+ // Quantity addon: set numeric value (ensure it doesn't go below 0)
+ (newLimits[addon] as number) = Math.max(0, value);
}
return limitsSchema.parse(newLimits);