Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

feat: add support for yearly pricing

Mohamed Bassem3d4194d6ccbc
diff --git a/apps/landing/src/Pricing.tsx b/apps/landing/src/Pricing.tsx
index 78ec0681..7a840a87 100644
--- a/apps/landing/src/Pricing.tsx
+++ b/apps/landing/src/Pricing.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Check, ExternalLink } from "lucide-react";
@@ -10,7 +11,8 @@ const CONTACT_EMAIL = "mailto:[email protected]";
const pricingTiers = [
{
name: "Free",
- price: "$0",
+ monthlyPrice: "$0",
+ yearlyPrice: "$0",
period: "",
description: "Trying Karakeep out",
features: [
@@ -25,8 +27,10 @@ const pricingTiers = [
},
{
name: "Pro",
- price: "$4",
+ monthlyPrice: "$4",
+ yearlyPrice: "$40",
period: "per month",
+ yearlyPeriod: "per year",
description: "For serious bookmark collectors",
features: [
"50,000 bookmarks",
@@ -42,7 +46,8 @@ const pricingTiers = [
},
{
name: "Self-Hosted",
- price: "Free",
+ monthlyPrice: "Free",
+ yearlyPrice: "Free",
period: "forever",
description: "Complete control and privacy",
features: [
@@ -60,7 +65,8 @@ const pricingTiers = [
},
{
name: "Corporate",
- price: "Custom",
+ monthlyPrice: "Custom",
+ yearlyPrice: "Custom",
period: "per seat",
description: "For teams and organizations",
features: [
@@ -77,86 +83,138 @@ const pricingTiers = [
},
];
-function PricingHeader() {
+function PricingHeader({
+ billingPeriod,
+ setBillingPeriod,
+}: {
+ billingPeriod: "monthly" | "yearly";
+ setBillingPeriod: (period: "monthly" | "yearly") => void;
+}) {
return (
<div className="text-center">
<h1 className="text-4xl font-bold sm:text-6xl">Simple Pricing</h1>
<p className="mt-4 text-lg text-gray-600">
Choose the plan that works best for you
</p>
+ <div className="mt-8 inline-flex items-center rounded-lg bg-gray-100 p-1">
+ <button
+ onClick={() => setBillingPeriod("monthly")}
+ className={cn(
+ "rounded-md px-4 py-2 text-sm font-medium transition-colors",
+ billingPeriod === "monthly"
+ ? "bg-white text-gray-900 shadow-sm"
+ : "text-gray-600 hover:text-gray-900",
+ )}
+ >
+ Monthly
+ </button>
+ <button
+ onClick={() => setBillingPeriod("yearly")}
+ className={cn(
+ "rounded-md px-4 py-2 text-sm font-medium transition-colors",
+ billingPeriod === "yearly"
+ ? "bg-white text-gray-900 shadow-sm"
+ : "text-gray-600 hover:text-gray-900",
+ )}
+ >
+ Yearly
+ <span className="ml-1.5 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
+ Save 17%
+ </span>
+ </button>
+ </div>
</div>
);
}
-function PricingCards() {
- const renderCard = (tier: (typeof pricingTiers)[number]) => (
- <div
- key={tier.name}
- className={cn(
- "relative rounded-2xl border bg-white p-8 shadow-sm",
- tier.popular && "border-purple-500 shadow-lg",
- )}
- >
- <div className="text-center">
- <h3 className="text-xl font-semibold">{tier.name}</h3>
- <div className="mt-4 flex items-baseline justify-center">
- <span className="text-4xl font-bold">{tier.price}</span>
- {tier.period && (
- <span className="ml-1 text-gray-500">/{tier.period}</span>
- )}
+function PricingCards({
+ billingPeriod,
+}: {
+ billingPeriod: "monthly" | "yearly";
+}) {
+ const renderCard = (tier: (typeof pricingTiers)[number]) => {
+ const price =
+ billingPeriod === "yearly" ? tier.yearlyPrice : tier.monthlyPrice;
+ const period =
+ billingPeriod === "yearly" && tier.yearlyPeriod
+ ? tier.yearlyPeriod
+ : tier.period;
+
+ return (
+ <div
+ key={tier.name}
+ className={cn(
+ "relative rounded-2xl border bg-white p-8 shadow-sm",
+ tier.popular && "border-purple-500 shadow-lg",
+ )}
+ >
+ <div className="text-center">
+ <h3 className="text-xl font-semibold">{tier.name}</h3>
+ <div className="mt-4 flex items-baseline justify-center">
+ <span className="text-4xl font-bold">{price}</span>
+ {period && <span className="ml-1 text-gray-500">/{period}</span>}
+ </div>
+ {billingPeriod === "yearly" &&
+ tier.monthlyPrice !== tier.yearlyPrice &&
+ tier.yearlyPeriod && (
+ <p className="mt-1 text-sm text-green-600">
+ ${(Number(tier.yearlyPrice.replace("$", "")) / 12).toFixed(2)}
+ /mo equivalent
+ </p>
+ )}
+ <p className="mt-2 text-gray-600">{tier.description}</p>
</div>
- <p className="mt-2 text-gray-600">{tier.description}</p>
- </div>
- <ul className="mt-8 space-y-3">
- {tier.features.map((feature) => (
- <li key={feature} className="flex items-center">
- <Check className="h-5 w-5 text-green-500" />
- <span className="ml-3 text-gray-700">{feature}</span>
- </li>
- ))}
- </ul>
+ <ul className="mt-8 space-y-3">
+ {tier.features.map((feature) => (
+ <li key={feature} className="flex items-center">
+ <Check className="h-5 w-5 text-green-500" />
+ <span className="ml-3 text-gray-700">{feature}</span>
+ </li>
+ ))}
+ </ul>
- <div className="mt-8">
- {tier.isContact ? (
- <a
- href={CONTACT_EMAIL}
- className={cn(
- "flex w-full items-center justify-center",
- buttonVariants({ variant: tier.buttonVariant, size: "lg" }),
- )}
- >
- {tier.buttonText}
- </a>
- ) : tier.isGitHub ? (
- <a
- href={GITHUB_LINK}
- target="_blank"
- className={cn(
- "flex w-full items-center justify-center gap-2",
- buttonVariants({ variant: tier.buttonVariant, size: "lg" }),
- )}
- rel="noreferrer"
- >
- <ExternalLink className="h-4 w-4" />
- {tier.buttonText}
- </a>
- ) : (
- <a
- href={CLOUD_SIGNUP_LINK}
- target="_blank"
- className={cn(
- "flex w-full items-center justify-center",
- buttonVariants({ variant: tier.buttonVariant, size: "lg" }),
- )}
- rel="noreferrer"
- >
- {tier.buttonText}
- </a>
- )}
+ <div className="mt-8">
+ {tier.isContact ? (
+ <a
+ href={CONTACT_EMAIL}
+ className={cn(
+ "flex w-full items-center justify-center",
+ buttonVariants({ variant: tier.buttonVariant, size: "lg" }),
+ )}
+ >
+ {tier.buttonText}
+ </a>
+ ) : tier.isGitHub ? (
+ <a
+ href={GITHUB_LINK}
+ target="_blank"
+ className={cn(
+ "flex w-full items-center justify-center gap-2",
+ buttonVariants({ variant: tier.buttonVariant, size: "lg" }),
+ )}
+ rel="noreferrer"
+ >
+ <ExternalLink className="h-4 w-4" />
+ {tier.buttonText}
+ </a>
+ ) : (
+ <a
+ href={CLOUD_SIGNUP_LINK}
+ target="_blank"
+ className={cn(
+ "flex w-full items-center justify-center",
+ buttonVariants({ variant: tier.buttonVariant, size: "lg" }),
+ )}
+ rel="noreferrer"
+ >
+ {tier.buttonText}
+ </a>
+ )}
+ </div>
</div>
- </div>
- );
+ );
+ };
return (
<div className="mx-auto mt-16 px-6">
@@ -207,17 +265,24 @@ function FAQ() {
}
export default function Pricing() {
+ const [billingPeriod, setBillingPeriod] = useState<"monthly" | "yearly">(
+ "monthly",
+ );
+
return (
<>
<SEO
title="Pricing"
- description="Simple, transparent pricing for Karakeep. Free plan available. Pro plan at $4/month with AI tagging, full-text search, and 50GB storage. Self-hosted option is free forever."
+ description="Simple, transparent pricing for Karakeep. Free plan available. Pro plan at $4/month or $40/year with AI tagging, full-text search, and 50GB storage. Self-hosted option is free forever."
path="/pricing"
/>
<div className="container mx-auto">
<div className="py-16">
- <PricingHeader />
- <PricingCards />
+ <PricingHeader
+ billingPeriod={billingPeriod}
+ setBillingPeriod={setBillingPeriod}
+ />
+ <PricingCards billingPeriod={billingPeriod} />
<FAQ />
</div>
</div>
diff --git a/apps/web/components/settings/SubscriptionSettings.tsx b/apps/web/components/settings/SubscriptionSettings.tsx
index 9c533e6c..fa93572a 100644
--- a/apps/web/components/settings/SubscriptionSettings.tsx
+++ b/apps/web/components/settings/SubscriptionSettings.tsx
@@ -1,10 +1,10 @@
"use client";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import { toast } from "@/components/ui/sonner";
import { useTranslation } from "@/lib/i18n/client";
import { useMutation, useQuery } from "@tanstack/react-query";
-import { Loader2 } from "lucide-react";
+import { Check, Loader2 } from "lucide-react";
import { useTRPC } from "@karakeep/shared-react/trpc";
@@ -17,6 +17,9 @@ import { SettingsSection } from "./SettingsPage";
export default function SubscriptionSettings() {
const api = useTRPC();
const { t } = useTranslation();
+ const [billingPeriod, setBillingPeriod] = useState<"monthly" | "yearly">(
+ "monthly",
+ );
const {
data: subscriptionStatus,
refetch,
@@ -72,6 +75,13 @@ export default function SubscriptionSettings() {
syncStripeState();
}, []);
+ const hasYearlyPricing = !!subscriptionPrice?.yearly;
+
+ const currentPrice =
+ billingPeriod === "yearly" && subscriptionPrice?.yearly
+ ? subscriptionPrice.yearly
+ : subscriptionPrice?.monthly;
+
const formatDate = (date: Date | null) => {
if (!date) return "N/A";
return new Intl.DateTimeFormat("en-US", {
@@ -96,6 +106,11 @@ export default function SubscriptionSettings() {
}
};
+ const formatPrice = (amount: number | null, currency: string) => {
+ if (amount === null) return null;
+ return `${amount / 100} ${currency.toUpperCase()}`;
+ };
+
return (
<SettingsSection
title={t("settings.subscription.subscription")}
@@ -160,31 +175,93 @@ export default function SubscriptionSettings() {
<div className="space-y-4">
{!subscriptionStatus?.hasActiveSubscription ? (
<div className="space-y-4">
- <div className="rounded-lg border p-4">
- <div className="flex items-center justify-between">
+ <div className="rounded-lg border p-6">
+ <h3 className="font-semibold">
+ {t("settings.subscription.paid_plan")}
+ </h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t("settings.subscription.unlock_bigger_quota")}
+ </p>
+
+ <ul className="mt-4 space-y-1.5">
+ {(
+ ["pro_feature_bookmarks", "pro_feature_storage"] as const
+ ).map((key) => (
+ <li key={key} className="flex items-center text-sm">
+ <Check className="mr-2 h-4 w-4 shrink-0 text-green-500" />
+ {t(`settings.subscription.${key}`)}
+ </li>
+ ))}
+ </ul>
+
+ <div className="mt-4 flex items-end justify-between border-t pt-4">
<div>
- <h3 className="flex items-center gap-2 font-semibold">
- {t("settings.subscription.paid_plan")}
- </h3>
- <p className="text-sm text-muted-foreground">
- {t("settings.subscription.unlock_bigger_quota")}
- </p>
- {subscriptionPrice && subscriptionPrice.amount ? (
+ {hasYearlyPricing && (
+ <div className="mb-2 inline-flex items-center rounded-lg bg-muted p-1">
+ <button
+ type="button"
+ onClick={() => setBillingPeriod("monthly")}
+ className={`rounded-md px-3 py-1 text-sm font-medium transition-colors ${
+ billingPeriod === "monthly"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {t("settings.subscription.monthly")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setBillingPeriod("yearly")}
+ className={`rounded-md px-3 py-1 text-sm font-medium transition-colors ${
+ billingPeriod === "yearly"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {t("settings.subscription.yearly")}
+ {subscriptionPrice?.monthly?.amount &&
+ subscriptionPrice?.yearly?.amount && (
+ <span className="ml-1.5 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
+ {t("settings.subscription.yearly_savings", {
+ percent: Math.round(
+ (1 -
+ subscriptionPrice.yearly.amount /
+ (subscriptionPrice.monthly.amount *
+ 12)) *
+ 100,
+ ),
+ })}
+ </span>
+ )}
+ </button>
+ </div>
+ )}
+ {currentPrice && currentPrice.amount ? (
<span className="flex items-baseline gap-2">
- <p className="mt-2 text-lg font-bold uppercase">
- {subscriptionPrice.amount / 100}{" "}
- {subscriptionPrice.currency}
- </p>
+ <span className="text-2xl font-bold">
+ {formatPrice(
+ currentPrice.amount,
+ currentPrice.currency,
+ )}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ /
+ {billingPeriod === "yearly"
+ ? t("settings.subscription.per_year")
+ : t("settings.subscription.per_month")}
+ </span>
<span className="text-xs italic text-muted-foreground">
- (excl. VAT)
+ ({t("settings.subscription.excl_vat")})
</span>
</span>
) : (
- <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-6 w-24" />
)}
</div>
<Button
- onClick={() => createCheckoutSession.mutate()}
+ onClick={() =>
+ createCheckoutSession.mutate({ billingPeriod })
+ }
disabled={isLoading}
size="lg"
className="shadow-md transition-all hover:scale-[1.02] hover:shadow-lg active:scale-[0.98]"
diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.json
index 59c24cc9..9973aa32 100644
--- a/apps/web/lib/i18n/locales/en/translation.json
+++ b/apps/web/lib/i18n/locales/en/translation.json
@@ -412,7 +412,17 @@
"approaching_quota_limit": "Approaching quota limit",
"loading_usage": "Loading usage information...",
"free": "Free",
- "paid": "Paid"
+ "paid": "Paid",
+ "monthly": "Monthly",
+ "yearly": "Yearly",
+ "per_month": "month",
+ "per_year": "year",
+ "excl_vat": "excl. VAT",
+ "yearly_savings": "Save {{percent}}%",
+ "pro_feature_bookmarks": "50,000 bookmarks",
+ "pro_feature_storage": "50GB storage",
+ "pro_feature_ai_tagging": "AI-powered tagging",
+ "pro_feature_full_text_search": "Full-text search"
},
"import_sessions": {
"title": "Import Sessions",
diff --git a/apps/web/lib/i18n/locales/en_US/translation.json b/apps/web/lib/i18n/locales/en_US/translation.json
index 03917192..205a814a 100644
--- a/apps/web/lib/i18n/locales/en_US/translation.json
+++ b/apps/web/lib/i18n/locales/en_US/translation.json
@@ -496,7 +496,17 @@
"approaching_quota_limit": "Approaching quota limit",
"loading_usage": "Loading usage information...",
"free": "Free",
- "paid": "Paid"
+ "paid": "Paid",
+ "monthly": "Monthly",
+ "yearly": "Yearly",
+ "per_month": "month",
+ "per_year": "year",
+ "excl_vat": "excl. VAT",
+ "yearly_savings": "Save {{percent}}%",
+ "pro_feature_bookmarks": "50,000 bookmarks",
+ "pro_feature_storage": "50GB storage",
+ "pro_feature_ai_tagging": "AI-powered tagging",
+ "pro_feature_full_text_search": "Full-text search"
},
"import_sessions": {
"title": "Import Sessions",
diff --git a/packages/shared/config.ts b/packages/shared/config.ts
index 173b87fd..68616c8d 100644
--- a/packages/shared/config.ts
+++ b/packages/shared/config.ts
@@ -175,6 +175,7 @@ const allEnv = z.object({
STRIPE_PUBLISHABLE_KEY: z.string().optional(),
STRIPE_WEBHOOK_SECRET: z.string().optional(),
STRIPE_PRICE_ID: z.string().optional(),
+ STRIPE_YEARLY_PRICE_ID: z.string().optional(),
FREE_QUOTA_BOOKMARK_LIMIT: z.coerce.number().optional(),
FREE_QUOTA_ASSET_SIZE_BYTES: z.coerce.number().optional(),
@@ -426,6 +427,7 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {
publishableKey: val.STRIPE_PUBLISHABLE_KEY,
webhookSecret: val.STRIPE_WEBHOOK_SECRET,
priceId: val.STRIPE_PRICE_ID,
+ yearlyPriceId: val.STRIPE_YEARLY_PRICE_ID,
isConfigured: !!val.STRIPE_SECRET_KEY && !!val.STRIPE_PUBLISHABLE_KEY,
},
quotas: {
diff --git a/packages/trpc/routers/subscriptions.test.ts b/packages/trpc/routers/subscriptions.test.ts
index 76dae9d6..33815cb5 100644
--- a/packages/trpc/routers/subscriptions.test.ts
+++ b/packages/trpc/routers/subscriptions.test.ts
@@ -22,6 +22,9 @@ const mockStripeInstance = vi.hoisted(() => ({
create: vi.fn(),
},
},
+ prices: {
+ retrieve: vi.fn(),
+ },
subscriptions: {
update: vi.fn(),
list: vi.fn(),
@@ -47,6 +50,7 @@ vi.mock("@karakeep/shared/config", async (original) => {
stripe: {
secretKey: "sk_test_123",
priceId: "price_123",
+ yearlyPriceId: "price_yearly_123",
webhookSecret: "whsec_123",
isConfigured: true,
},
@@ -73,6 +77,7 @@ describe("Subscription Routes", () => {
let mockBillingPortalSessionsCreate: ReturnType<typeof vi.fn>;
let mockWebhooksConstructEvent: ReturnType<typeof vi.fn>;
let mockSubscriptionsList: ReturnType<typeof vi.fn>;
+ let mockPricesRetrieve: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
@@ -84,6 +89,7 @@ describe("Subscription Routes", () => {
mockStripeInstance.billingPortal.sessions.create;
mockWebhooksConstructEvent = mockStripeInstance.webhooks.constructEvent;
mockSubscriptionsList = mockStripeInstance.subscriptions.list;
+ mockPricesRetrieve = mockStripeInstance.prices.retrieve;
});
describe("getSubscriptionStatus", () => {
@@ -151,6 +157,48 @@ describe("Subscription Routes", () => {
});
});
+ describe("getSubscriptionPrice", () => {
+ test<CustomTestContext>("returns monthly and yearly prices", async ({
+ db,
+ unauthedAPICaller,
+ }) => {
+ const user = await unauthedAPICaller.users.create({
+ name: "Test User",
+ email: "[email protected]",
+ password: "pass1234",
+ confirmPassword: "pass1234",
+ });
+ const caller = getApiCaller(db, user.id);
+
+ mockPricesRetrieve
+ .mockResolvedValueOnce({
+ id: "price_123",
+ currency: "usd",
+ unit_amount: 400,
+ })
+ .mockResolvedValueOnce({
+ id: "price_yearly_123",
+ currency: "usd",
+ unit_amount: 4000,
+ });
+
+ const result = await caller.subscriptions.getSubscriptionPrice();
+
+ expect(result).toEqual({
+ monthly: {
+ priceId: "price_123",
+ currency: "usd",
+ amount: 400,
+ },
+ yearly: {
+ priceId: "price_yearly_123",
+ currency: "usd",
+ amount: 4000,
+ },
+ });
+ });
+ });
+
describe("createCheckoutSession", () => {
test<CustomTestContext>("creates checkout session for new customer", async ({
db,
@@ -213,6 +261,48 @@ describe("Subscription Routes", () => {
});
});
+ test<CustomTestContext>("creates checkout session with yearly price when billingPeriod is yearly", async ({
+ db,
+ unauthedAPICaller,
+ }) => {
+ const user = await unauthedAPICaller.users.create({
+ name: "Test User",
+ email: "[email protected]",
+ password: "pass1234",
+ confirmPassword: "pass1234",
+ });
+ const caller = getApiCaller(db, user.id);
+
+ mockCustomersCreate.mockResolvedValue({
+ id: "cus_new123",
+ });
+
+ mockCheckoutSessionsCreate.mockResolvedValue({
+ id: "cs_123",
+ url: "https://checkout.stripe.com/pay/cs_123",
+ });
+
+ const result = await caller.subscriptions.createCheckoutSession({
+ billingPeriod: "yearly",
+ });
+
+ expect(result).toEqual({
+ sessionId: "cs_123",
+ url: "https://checkout.stripe.com/pay/cs_123",
+ });
+
+ expect(mockCheckoutSessionsCreate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ line_items: [
+ {
+ price: "price_yearly_123",
+ quantity: 1,
+ },
+ ],
+ }),
+ );
+ });
+
test<CustomTestContext>("throws error if user already has active subscription", async ({
db,
unauthedAPICaller,
diff --git a/packages/trpc/routers/subscriptions.ts b/packages/trpc/routers/subscriptions.ts
index fa76e619..deb998db 100644
--- a/packages/trpc/routers/subscriptions.ts
+++ b/packages/trpc/routers/subscriptions.ts
@@ -24,7 +24,11 @@ function requireStripeConfig() {
message: "Stripe is not configured. Please contact your administrator.",
});
}
- return { stripe, priceId: serverConfig.stripe.priceId };
+ return {
+ stripe,
+ priceId: serverConfig.stripe.priceId,
+ yearlyPriceId: serverConfig.stripe.yearlyPriceId,
+ };
}
// Taken from https://github.com/t3dotgg/stripe-recommendations
@@ -217,100 +221,134 @@ export const subscriptionsRouter = router({
});
}
- const { priceId } = requireStripeConfig();
-
- const price = await stripe.prices.retrieve(priceId);
-
- return {
- priceId: price.id,
- currency: price.currency,
- amount: price.unit_amount,
+ const { priceId, yearlyPriceId } = requireStripeConfig();
+
+ const monthlyPrice = await stripe.prices.retrieve(priceId);
+
+ const result: {
+ monthly: { priceId: string; currency: string; amount: number | null };
+ yearly: {
+ priceId: string;
+ currency: string;
+ amount: number | null;
+ } | null;
+ } = {
+ monthly: {
+ priceId: monthlyPrice.id,
+ currency: monthlyPrice.currency,
+ amount: monthlyPrice.unit_amount,
+ },
+ yearly: null,
};
- }),
- createCheckoutSession: authedProcedure.mutation(async ({ ctx }) => {
- const { stripe, priceId } = requireStripeConfig();
+ if (yearlyPriceId) {
+ const yearlyPrice = await stripe.prices.retrieve(yearlyPriceId);
+ result.yearly = {
+ priceId: yearlyPrice.id,
+ currency: yearlyPrice.currency,
+ amount: yearlyPrice.unit_amount,
+ };
+ }
- const user = await ctx.db.query.users.findFirst({
- where: eq(users.id, ctx.user.id),
- columns: {
- email: true,
- },
- with: {
- subscription: true,
- },
- });
+ return result;
+ }),
- if (!user) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
+ createCheckoutSession: authedProcedure
+ .input(
+ z
+ .object({
+ billingPeriod: z.enum(["monthly", "yearly"]).default("monthly"),
+ })
+ .default({}),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { stripe, priceId, yearlyPriceId } = requireStripeConfig();
+
+ const selectedPriceId =
+ input.billingPeriod === "yearly" && yearlyPriceId
+ ? yearlyPriceId
+ : priceId;
+
+ const user = await ctx.db.query.users.findFirst({
+ where: eq(users.id, ctx.user.id),
+ columns: {
+ email: true,
+ },
+ with: {
+ subscription: true,
+ },
});
- }
- const existingSubscription = user.subscription;
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
+ });
+ }
- if (existingSubscription?.status === "active") {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "User already has an active subscription",
- });
- }
+ const existingSubscription = user.subscription;
- let customerId = existingSubscription?.stripeCustomerId;
+ if (existingSubscription?.status === "active") {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "User already has an active subscription",
+ });
+ }
- if (!customerId) {
- const customer = await stripe.customers.create({
- email: user.email,
- metadata: {
- userId: ctx.user.id,
- },
- });
- customerId = customer.id;
+ let customerId = existingSubscription?.stripeCustomerId;
- if (!existingSubscription) {
- await ctx.db.insert(subscriptions).values({
- userId: ctx.user.id,
- stripeCustomerId: customerId,
- status: "unpaid",
+ if (!customerId) {
+ const customer = await stripe.customers.create({
+ email: user.email,
+ metadata: {
+ userId: ctx.user.id,
+ },
});
- } else {
- await ctx.db
- .update(subscriptions)
- .set({ stripeCustomerId: customerId })
- .where(eq(subscriptions.userId, ctx.user.id));
+ customerId = customer.id;
+
+ if (!existingSubscription) {
+ await ctx.db.insert(subscriptions).values({
+ userId: ctx.user.id,
+ stripeCustomerId: customerId,
+ status: "unpaid",
+ });
+ } else {
+ await ctx.db
+ .update(subscriptions)
+ .set({ stripeCustomerId: customerId })
+ .where(eq(subscriptions.userId, ctx.user.id));
+ }
}
- }
- // @ts-expect-error managed_payments is a Stripe preview feature not yet in the SDK types
- const session = await stripe.checkout.sessions.create({
- customer: customerId,
- line_items: [
- {
- price: priceId,
- quantity: 1,
+ // @ts-expect-error managed_payments is a Stripe preview feature not yet in the SDK types
+ const session = await stripe.checkout.sessions.create({
+ customer: customerId,
+ line_items: [
+ {
+ price: selectedPriceId,
+ quantity: 1,
+ },
+ ],
+ mode: "subscription",
+ success_url: `${serverConfig.publicUrl}/settings/subscription?success=true`,
+ cancel_url: `${serverConfig.publicUrl}/settings/subscription?canceled=true`,
+ metadata: {
+ userId: ctx.user.id,
},
- ],
- mode: "subscription",
- success_url: `${serverConfig.publicUrl}/settings/subscription?success=true`,
- cancel_url: `${serverConfig.publicUrl}/settings/subscription?canceled=true`,
- metadata: {
- userId: ctx.user.id,
- },
- customer_update: {
- address: "auto",
- },
- allow_promotion_codes: true,
- managed_payments: {
- enabled: true,
- },
- });
+ customer_update: {
+ address: "auto",
+ },
+ allow_promotion_codes: true,
+ managed_payments: {
+ enabled: true,
+ },
+ });
- return {
- sessionId: session.id,
- url: session.url,
- };
- }),
+ return {
+ sessionId: session.id,
+ url: session.url,
+ };
+ }),
syncWithStripe: authedProcedure.mutation(async ({ ctx }) => {
const subscription = await ctx.db.query.subscriptions.findFirst({