Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Allow users to have multiple subscriptions (#1877)
Luke Vellaaf12e39ec4a5
diff --git a/apps/web/src/app/api/house-keeping/delete-inactive-polls/route.ts b/apps/web/src/app/api/house-keeping/delete-inactive-polls/route.tsindex 6c32efbe5..6d8dc67cb 100644--- a/apps/web/src/app/api/house-keeping/delete-inactive-polls/route.ts+++ b/apps/web/src/app/api/house-keeping/delete-inactive-polls/route.ts@@ -26,12 +26,19 @@ export async function POST() {startTime: { gt: new Date() },},},- // User is either null or doesn't have an active subscription+ // We don't delete polls that belong to a space with an active subscriptionOR: [- { userId: null },+ { spaceId: null },{- user: {- OR: [{ subscription: null }, { subscription: { active: false } }],+ space: {+ subscription: null,+ },+ },+ {+ space: {+ subscription: {+ active: false,+ },},},],diff --git a/apps/web/src/app/api/stripe/webhook/handlers/checkout/expired.ts b/apps/web/src/app/api/stripe/webhook/handlers/checkout/expired.tsindex 3175b3cd2..6d9129c47 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/checkout/expired.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/checkout/expired.ts@@ -1,9 +1,5 @@import type { Stripe } from "@rallly/billing";-import { prisma } from "@rallly/database";import * as Sentry from "@sentry/nextjs";-import { kv } from "@vercel/kv";--import { getEmailClient } from "@/utils/emails";export async function onCheckoutSessionExpired(event: Stripe.Event) {const session = event.data.object as Stripe.Checkout.Session;@@ -24,46 +20,5 @@ export async function onCheckoutSessionExpired(event: Stripe.Event) {return;}- const promoEmailKey = `promo_email_sent:${email}`;- // Track that a promotional email opportunity has been shown to this user- const hasReceivedPromo = await kv.get(promoEmailKey);-- const user = await prisma.user.findUnique({- where: {- id: userId,- },- select: {- locale: true,- subscription: {- select: {- active: true,- },- },- },- });-- const isPro = !!user?.subscription?.active;-- // Avoid spamming people who abandon Checkout multiple times- if (user && !hasReceivedPromo && !isPro) {- console.info("Sending abandoned checkout email");- // Set the flag with a 30-day expiration (in seconds)- await kv.set(promoEmailKey, 1, { ex: 30 * 24 * 60 * 60, nx: true });- getEmailClient(user.locale ?? undefined).sendTemplate(- "AbandonedCheckoutEmail",- {- to: email,- from: {- name: "Luke from Rallly",- address: "[email protected]",- },- props: {- name: session.customer_details?.name ?? undefined,- discount: 20,- couponCode: "GETPRO1Y20",- recoveryUrl,- },- },- );- }+ // TODO (Luke Vella) [2025-08-04]: We may want to send the user an email to users who do not complete checkout}diff --git a/apps/web/src/features/space/components/space-dropdown.tsx b/apps/web/src/features/space/components/space-dropdown.tsxindex ecfe0194e..692b6494b 100644--- a/apps/web/src/features/space/components/space-dropdown.tsx+++ b/apps/web/src/features/space/components/space-dropdown.tsx@@ -13,7 +13,6 @@ import {import { Icon } from "@rallly/ui/icon";import { CirclePlusIcon, SettingsIcon } from "lucide-react";import Link from "next/link";-import { ProBadge } from "@/components/pro-badge";import { RouterLoadingIndicator } from "@/components/router-loading-indicator";import { Trans } from "@/components/trans";import { setActiveSpaceAction } from "@/features/space/actions";@@ -67,7 +66,6 @@ export function SpaceDropdown({><SpaceIcon size="sm" src={space.image} name={space.name} /><span>{space.name}</span>- {space.tier === "pro" ? <ProBadge /> : null}</DropdownMenuRadioItem>))}</DropdownMenuRadioGroup>diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.tsindex 450567be8..b618a51b1 100644--- a/apps/web/src/trpc/trpc.ts+++ b/apps/web/src/trpc/trpc.ts@@ -4,11 +4,9 @@ import { initTRPC, TRPCError } from "@trpc/server";import { Ratelimit } from "@upstash/ratelimit";import { kv } from "@vercel/kv";import superjson from "superjson";-+import { getCurrentUserSpace } from "@/auth/data";import { isQuickCreateEnabled } from "@/features/quick-create";import { isSelfHosted } from "@/utils/constants";-import { getSubscriptionStatus } from "@/utils/subscription";-import type { TRPCContext } from "./context";const t = initTRPC.context<TRPCContext>().create({@@ -97,15 +95,15 @@ export const privateProcedure = t.procedure.use(async ({ ctx, next }) => {});});-export const proProcedure = privateProcedure.use(async ({ ctx, next }) => {+export const proProcedure = privateProcedure.use(async ({ next }) => {if (isSelfHosted) {// Self-hosted instances don't have paid subscriptionsreturn next();}- const { active: isPro } = await getSubscriptionStatus(ctx.user.id);+ const data = await getCurrentUserSpace();- if (!isPro) {+ if (!data || data.space.tier !== "pro") {throw new TRPCError({code: "UNAUTHORIZED",message:diff --git a/apps/web/src/utils/subscription.ts b/apps/web/src/utils/subscription.tsdeleted file mode 100644index d321c7040..000000000--- a/apps/web/src/utils/subscription.ts+++ /dev/null@@ -1,22 +0,0 @@-import { prisma } from "@rallly/database";--import { isSelfHosted } from "./constants";--export const getSubscriptionStatus = async (userId: string) => {- const user = await prisma.user.findUnique({- where: {- id: userId,- },- select: {- subscription: {- select: {- active: true,- },- },- },- });-- return {- active: user?.subscription?.active === true || isSelfHosted,- };-};diff --git a/apps/web/tests/house-keeping.spec.ts b/apps/web/tests/house-keeping.spec.tsindex 4c685164a..8a60d1558 100644--- a/apps/web/tests/house-keeping.spec.ts+++ b/apps/web/tests/house-keeping.spec.ts@@ -1,6 +1,7 @@import { expect, test } from "@playwright/test";import { prisma } from "@rallly/database";import dayjs from "dayjs";+import { createUserInDb, createSpaceWithSubscription, createTestPoll } from "./test-utils";/*** This test suite tests the house-keeping API endpoints:@@ -52,128 +53,79 @@ test.describe("House-keeping API", () => {}}- test("should mark inactive polls as deleted for users without active subscriptions", async ({+ test("should mark inactive polls as deleted except for polls in spaces with active subscriptions", async ({request,baseURL,}) => {// Create test users- const regularUser = await prisma.user.create({- data: {- name: "Regular User",- email: "[email protected]",- },+ const freeUser = await createUserInDb({+ name: "Free User",+ email: "[email protected]",});- createdUserIds.push(regularUser.id);+ createdUserIds.push(freeUser.id);- const proUser = await prisma.user.create({- data: {- name: "Pro User",- email: "[email protected]",- subscription: {- create: {- id: "sub_test_pro",- priceId: "price_test",- amount: 1000,- status: "active",- active: true,- subscriptionItemId: "si_test_pro",- currency: "USD",- interval: "month",- periodStart: new Date(),- periodEnd: dayjs().add(30, "day").toDate(),- },- },- },+ const spaceOwner = await createUserInDb({+ name: "Space Owner",+ email: "[email protected]",});- createdUserIds.push(proUser.id);+ createdUserIds.push(spaceOwner.id);- // Create test polls+ // Create a space with an active subscription+ const paidSpace = await createSpaceWithSubscription({+ name: "Paid Space",+ ownerId: spaceOwner.id,+ subscriptionId: "sub_test_paid",+ });- // 1. Old poll from regular user (should be marked as deleted)- const oldPollRegularUser = await prisma.poll.create({- data: {- id: "old-poll-regular-user",- title: "Old Poll Regular User",- participantUrlId: "old-poll-regular-user-participant",- adminUrlId: "old-poll-regular-user-admin",- userId: regularUser.id,- touchedAt: dayjs().subtract(35, "day").toDate(), // 35 days old- },+ // Create test polls - These should be marked as deleted (free space, old, no future dates)+ const oldPollFromFreeUser = await createTestPoll({+ id: "old-poll-free-user",+ title: "Old Poll from Free User",+ userId: freeUser.id,+ touchedAt: dayjs().subtract(35, "day").toDate(),});- createdPollIds.push(oldPollRegularUser.id);+ createdPollIds.push(oldPollFromFreeUser.id);- // 2. Old poll from pro user (should NOT be marked as deleted)- const oldPollProUser = await prisma.poll.create({- data: {- id: "old-poll-pro-user",- title: "Old Poll Pro User",- participantUrlId: "old-poll-pro-user-participant",- adminUrlId: "old-poll-pro-user-admin",- userId: proUser.id,- touchedAt: dayjs().subtract(35, "day").toDate(), // 35 days old- },+ const oldPollNoUser = await createTestPoll({+ id: "old-poll-no-user",+ title: "Old Poll with No User",+ touchedAt: dayjs().subtract(35, "day").toDate(),});- createdPollIds.push(oldPollProUser.id);+ createdPollIds.push(oldPollNoUser.id);- // 3. Recent poll from regular user (should NOT be marked as deleted)- const recentPollRegularUser = await prisma.poll.create({- data: {- id: "recent-poll-regular-user",- title: "Recent Poll Regular User",- participantUrlId: "recent-poll-regular-user-participant",- adminUrlId: "recent-poll-regular-user-admin",- userId: regularUser.id,- touchedAt: dayjs().subtract(15, "day").toDate(), // 15 days old- },+ // These should NOT be marked as deleted+ const oldPollInPaidSpace = await createTestPoll({+ id: "old-poll-paid-space",+ title: "Old Poll in Paid Space",+ userId: spaceOwner.id,+ spaceId: paidSpace.id,+ touchedAt: dayjs().subtract(35, "day").toDate(),});- createdPollIds.push(recentPollRegularUser.id);+ createdPollIds.push(oldPollInPaidSpace.id);- // 4. Old poll with future options from regular user (should NOT be marked as deleted)- const oldPollWithFutureOptions = await prisma.poll.create({- data: {- id: "old-poll-with-future-options",- title: "Old Poll With Future Options",- participantUrlId: "old-poll-with-future-options-participant",- adminUrlId: "old-poll-with-future-options-admin",- userId: regularUser.id,- touchedAt: dayjs().subtract(35, "day").toDate(), // 35 days old- options: {- create: {- startTime: dayjs().add(10, "day").toDate(), // Future date- duration: 60,- },- },- },+ const recentPollFromFreeUser = await createTestPoll({+ id: "recent-poll-free-user",+ title: "Recent Poll from Free User",+ userId: freeUser.id,+ touchedAt: dayjs().subtract(15, "day").toDate(),});- createdPollIds.push(oldPollWithFutureOptions.id);+ createdPollIds.push(recentPollFromFreeUser.id);- // 5. Old poll without a user (should be marked as deleted)- const oldPollNoUser = await prisma.poll.create({- data: {- id: "old-poll-no-user",- title: "Old Poll No User",- participantUrlId: "old-poll-no-user-participant",- adminUrlId: "old-poll-no-user-admin",- touchedAt: dayjs().subtract(35, "day").toDate(), // 35 days old- },+ const oldPollWithFutureOptions = await createTestPoll({+ id: "old-poll-future-options",+ title: "Old Poll with Future Options",+ userId: freeUser.id,+ touchedAt: dayjs().subtract(35, "day").toDate(),+ hasFutureOptions: true,});- createdPollIds.push(oldPollNoUser.id);+ createdPollIds.push(oldPollWithFutureOptions.id);- // 6. Old poll with recent views from regular user (should NOT be marked as deleted)- const oldPollWithRecentViews = await prisma.poll.create({- data: {- id: "old-poll-with-recent-views",- title: "Old Poll With Recent Views",- participantUrlId: "old-poll-with-recent-views-participant",- adminUrlId: "old-poll-with-recent-views-admin",- userId: regularUser.id,- touchedAt: dayjs().subtract(35, "day").toDate(), // 35 days old- views: {- create: {- viewedAt: dayjs().subtract(15, "day").toDate(), // Viewed 15 days ago- },- },- },+ const oldPollWithRecentViews = await createTestPoll({+ id: "old-poll-recent-views",+ title: "Old Poll with Recent Views",+ userId: freeUser.id,+ touchedAt: dayjs().subtract(35, "day").toDate(),+ hasRecentViews: true,});createdPollIds.push(oldPollWithRecentViews.id);@@ -192,46 +144,47 @@ test.describe("House-keeping API", () => {expect(responseData.success).toBeTruthy();// We expect 2 polls to be marked as deleted:- // - Old poll from regular user+ // - Old poll from free user (not in a paid space)// - Old poll without a userexpect(responseData.summary.markedDeleted).toBe(2);- // Verify the state of each poll- const updatedOldPollRegularUser = await prisma.poll.findUnique({- where: { id: oldPollRegularUser.id },+ // Verify polls that should be marked as deleted+ const deletedPollFromFreeUser = await prisma.poll.findUnique({+ where: { id: oldPollFromFreeUser.id },});- expect(updatedOldPollRegularUser?.deleted).toBe(true);- expect(updatedOldPollRegularUser?.deletedAt).not.toBeNull();+ expect(deletedPollFromFreeUser?.deleted).toBe(true);+ expect(deletedPollFromFreeUser?.deletedAt).not.toBeNull();- const updatedOldPollProUser = await prisma.poll.findUnique({- where: { id: oldPollProUser.id },+ const deletedPollNoUser = await prisma.poll.findUnique({+ where: { id: oldPollNoUser.id },});- expect(updatedOldPollProUser?.deleted).toBe(false);- expect(updatedOldPollProUser?.deletedAt).toBeNull();+ expect(deletedPollNoUser?.deleted).toBe(true);+ expect(deletedPollNoUser?.deletedAt).not.toBeNull();- const updatedRecentPollRegularUser = await prisma.poll.findUnique({- where: { id: recentPollRegularUser.id },+ // Verify polls that should NOT be marked as deleted+ const protectedPollInPaidSpace = await prisma.poll.findUnique({+ where: { id: oldPollInPaidSpace.id },});- expect(updatedRecentPollRegularUser?.deleted).toBe(false);- expect(updatedRecentPollRegularUser?.deletedAt).toBeNull();+ expect(protectedPollInPaidSpace?.deleted).toBe(false);+ expect(protectedPollInPaidSpace?.deletedAt).toBeNull();- const updatedOldPollWithFutureOptions = await prisma.poll.findUnique({- where: { id: oldPollWithFutureOptions.id },+ const protectedRecentPoll = await prisma.poll.findUnique({+ where: { id: recentPollFromFreeUser.id },});- expect(updatedOldPollWithFutureOptions?.deleted).toBe(false);- expect(updatedOldPollWithFutureOptions?.deletedAt).toBeNull();+ expect(protectedRecentPoll?.deleted).toBe(false);+ expect(protectedRecentPoll?.deletedAt).toBeNull();- const updatedOldPollNoUser = await prisma.poll.findUnique({- where: { id: oldPollNoUser.id },+ const protectedPollWithFutureOptions = await prisma.poll.findUnique({+ where: { id: oldPollWithFutureOptions.id },});- expect(updatedOldPollNoUser?.deleted).toBe(true);- expect(updatedOldPollNoUser?.deletedAt).not.toBeNull();+ expect(protectedPollWithFutureOptions?.deleted).toBe(false);+ expect(protectedPollWithFutureOptions?.deletedAt).toBeNull();- const updatedOldPollWithRecentViews = await prisma.poll.findUnique({+ const protectedPollWithRecentViews = await prisma.poll.findUnique({where: { id: oldPollWithRecentViews.id },});- expect(updatedOldPollWithRecentViews?.deleted).toBe(false);- expect(updatedOldPollWithRecentViews?.deletedAt).toBeNull();+ expect(protectedPollWithRecentViews?.deleted).toBe(false);+ expect(protectedPollWithRecentViews?.deletedAt).toBeNull();});test("should permanently remove polls that have been marked as deleted for more than 7 days", async ({diff --git a/apps/web/tests/test-utils.ts b/apps/web/tests/test-utils.tsindex 4ee1ea774..411e72e29 100644--- a/apps/web/tests/test-utils.ts+++ b/apps/web/tests/test-utils.ts@@ -1,6 +1,7 @@import type { Page } from "@playwright/test";import type { UserRole } from "@rallly/database";import { prisma } from "@rallly/database";+import dayjs from "dayjs";import { LoginPage } from "./login-page";export async function createUserInDb({@@ -43,6 +44,85 @@ export async function createUserInDb({});}+export async function createSpaceWithSubscription({+ name,+ ownerId,+ subscriptionId = "sub_test",+}: {+ name: string;+ ownerId: string;+ subscriptionId?: string;+}) {+ return await prisma.space.create({+ data: {+ name,+ ownerId,+ subscription: {+ create: {+ id: subscriptionId,+ priceId: "price_test",+ amount: 1000,+ status: "active",+ active: true,+ subscriptionItemId: "si_test",+ currency: "USD",+ interval: "month",+ periodStart: new Date(),+ periodEnd: dayjs().add(30, "day").toDate(),+ userId: ownerId,+ },+ },+ },+ });+}++export async function createTestPoll({+ id,+ title,+ userId,+ spaceId,+ touchedAt,+ hasRecentViews = false,+ hasFutureOptions = false,+}: {+ id: string;+ title: string;+ userId?: string;+ spaceId?: string;+ touchedAt: Date;+ hasRecentViews?: boolean;+ hasFutureOptions?: boolean;+}) {+ const pollData = {+ id,+ title,+ participantUrlId: `${id}-participant`,+ adminUrlId: `${id}-admin`,+ userId,+ spaceId,+ touchedAt,+ ...(hasRecentViews && {+ views: {+ create: {+ viewedAt: dayjs().subtract(15, "day").toDate(),+ },+ },+ }),+ ...(hasFutureOptions && {+ options: {+ create: {+ startTime: dayjs().add(10, "day").toDate(),+ duration: 60,+ },+ },+ }),+ };++ return await prisma.poll.create({+ data: pollData,+ });+}+export async function loginWithEmail(page: Page, { email }: { email: string }) {const loginPage = new LoginPage(page);await loginPage.goto();diff --git a/packages/database/prisma/migrations/20250804152225_allow_user_multiple_subscriptions/migration.sql b/packages/database/prisma/migrations/20250804152225_allow_user_multiple_subscriptions/migration.sqlnew file mode 100644index 000000000..744b07a80--- /dev/null+++ b/packages/database/prisma/migrations/20250804152225_allow_user_multiple_subscriptions/migration.sql@@ -0,0 +1,2 @@+-- DropIndex+DROP INDEX "subscriptions_user_id_key";diff --git a/packages/database/prisma/models/billing.prisma b/packages/database/prisma/models/billing.prismaindex 84d45beca..721cb7497 100644--- a/packages/database/prisma/models/billing.prisma+++ b/packages/database/prisma/models/billing.prisma@@ -12,7 +12,7 @@ model Subscription {periodStart DateTime @map("period_start")periodEnd DateTime @map("period_end")cancelAtPeriodEnd Boolean @default(false) @map("cancel_at_period_end")- userId String @unique @map("user_id")+ userId String @map("user_id")spaceId String? @unique @map("space_id")user User @relation("UserToSubscription", fields: [userId], references: [id], onDelete: Cascade)diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex 24c9cbaf7..fe82e825c 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -56,9 +56,9 @@ model User {accounts Account[]participants Participant[]paymentMethods PaymentMethod[]- subscription Subscription? @relation("UserToSubscription")spaceMemberInvites SpaceMemberInvite[]+ subscriptions Subscription[] @relation("UserToSubscription")spaces Space[] @relation("UserSpaces")memberOf SpaceMember[]