Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Move Stripe webhook business logic into features/billing (#2575)

Luke Vella085917554734
diff --git a/apps/web/src/app/api/house-keeping/[...method]/route.ts b/apps/web/src/app/api/house-keeping/[...method]/route.ts
index 3104d7294..7512bc906 100644
--- a/apps/web/src/app/api/house-keeping/[...method]/route.ts
+++ b/apps/web/src/app/api/house-keeping/[...method]/route.ts
@@ -1,10 +1,12 @@
-import { prisma } from "@rallly/database";
import { createLogger } from "@rallly/logger";
import { Hono } from "hono";
import { bearerAuth } from "hono/bearer-auth";
import { handle } from "hono/vercel";
-
-const BATCH_SIZE = 100;
+import {
+ autoClosePolls,
+ deleteInactivePolls,
+ removeDeletedPolls,
+} from "@/features/poll/mutations";
const logger = createLogger("api/house-keeping");
@@ -25,52 +27,8 @@ app.use("*", async (c, next) => {
);
});
-/**
- * Marks inactive polls as deleted. Polls are inactive if they have not been
- * updated in the last 30 days and all dates are in the past.
- * Only marks polls as deleted if they belong to users without an active subscription
- * or if they don't have a user associated with them.
- */
app.get("/delete-inactive-polls", async (c) => {
- // Define the 30-day threshold once
- const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
-
- // Mark inactive polls as deleted in a single query
- const { count: markedDeleted } = await prisma.poll.updateMany({
- where: {
- deleted: false,
- // All poll dates are in the past
- options: {
- none: {
- startTime: { gt: new Date() },
- },
- },
- // We don't delete polls that belong to a space with an active subscription
- OR: [
- { spaceId: null },
- {
- space: {
- tier: {
- not: "pro",
- },
- },
- },
- ],
- // Poll is inactive: not edited, and no participant activity (new or
- // updated responses) or new comments in the last 30 days
- updatedAt: { lt: thirtyDaysAgo },
- participants: {
- none: { updatedAt: { gte: thirtyDaysAgo } },
- },
- comments: {
- none: { createdAt: { gte: thirtyDaysAgo } },
- },
- },
- data: {
- deleted: true,
- deletedAt: new Date(),
- },
- });
+ const markedDeleted = await deleteInactivePolls();
logger.info(
{ task: "delete-inactive-polls", markedDeleted },
@@ -85,32 +43,8 @@ app.get("/delete-inactive-polls", async (c) => {
});
});
-/**
- * Closes polls whose options have all ended — i.e. no option ends in the
- * future, where an option ends at start_time + duration (all-day options, with
- * duration 0, are treated as ending 24h after their start). Closing is
- * non-destructive: the poll becomes read-only but is preserved.
- *
- * Raw SQL because the option-end comparison (start_time + duration) can't be
- * expressed in a Prisma `where`. It also deliberately does not touch
- * `updated_at`, so closing a poll doesn't reset the inactivity clock that
- * delete-inactive-polls keys off.
- */
app.get("/auto-close-polls", async (c) => {
- const closed = await prisma.$executeRaw`
- UPDATE polls p
- SET status = 'closed', closed_reason = 'auto'
- WHERE p.status = 'open'
- AND p.deleted = false
- AND EXISTS (SELECT 1 FROM options o WHERE o.poll_id = p.id)
- AND NOT EXISTS (
- SELECT 1 FROM options o
- WHERE o.poll_id = p.id
- AND o.start_time + (CASE WHEN o.duration_minutes = 0
- THEN interval '24 hours'
- ELSE make_interval(mins => o.duration_minutes) END) > (now() AT TIME ZONE 'UTC')
- )
- `;
+ const closed = await autoClosePolls();
logger.info(
{ task: "auto-close-polls", closed },
@@ -125,41 +59,8 @@ app.get("/auto-close-polls", async (c) => {
});
});
-/**
- * Remove polls and corresponding data that have been marked deleted for more than 7 days.
- */
app.get("/remove-deleted-polls", async (c) => {
- // First get the ids of all the polls that have been marked as deleted for at least 7 days
- let totalDeletedPolls = 0;
- let hasMore = true;
-
- const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
-
- while (hasMore) {
- const batch = await prisma.poll.findMany({
- where: {
- deleted: true,
- deletedAt: {
- lt: sevenDaysAgo,
- },
- },
- select: { id: true },
- take: BATCH_SIZE,
- });
-
- if (batch.length === 0) {
- hasMore = false;
- break;
- }
-
- const deleted = await prisma.poll.deleteMany({
- where: {
- id: { in: batch.map((poll) => poll.id) },
- },
- });
-
- totalDeletedPolls += deleted.count;
- }
+ const totalDeletedPolls = await removeDeletedPolls();
logger.info(
{ task: "remove-deleted-polls", deletedPolls: totalDeletedPolls },
diff --git a/apps/web/src/app/api/licensing/v1/[...route]/route.ts b/apps/web/src/app/api/licensing/v1/[...route]/route.ts
index b93ab64fb..ae1cfe09c 100644
--- a/apps/web/src/app/api/licensing/v1/[...route]/route.ts
+++ b/apps/web/src/app/api/licensing/v1/[...route]/route.ts
@@ -1,6 +1,5 @@
import { zValidator } from "@hono/zod-validator";
import { RedisStore } from "@hono-rate-limiter/redis";
-import { prisma } from "@rallly/database";
import { createLogger } from "@rallly/logger";
import { Hono } from "hono";
import { bearerAuth } from "hono/bearer-auth";
@@ -11,7 +10,10 @@ import { redis } from "@/lib/kv";
const logger = createLogger("api/licensing");
-import { generateLicenseKey } from "@/features/licensing/helpers/generate-license-key";
+import {
+ createLicense,
+ validateLicenseKey,
+} from "@/features/licensing/mutations";
import type {
CreateLicenseResponse,
ValidateLicenseKeyResponse,
@@ -46,24 +48,12 @@ if (env.LICENSE_API_AUTH_TOKEN) {
zValidator("json", createLicenseInputSchema),
bearerAuth({ token: env.LICENSE_API_AUTH_TOKEN }),
async (c) => {
- const { type, seats, expiresAt, licenseeEmail, licenseeName, version } =
- c.req.valid("json");
+ const input = c.req.valid("json");
try {
- const license = await prisma.license.create({
- data: {
- licenseKey: generateLicenseKey({ version }),
- version,
- type,
- seats,
- issuedAt: new Date(),
- expiresAt,
- licenseeEmail,
- licenseeName,
- },
- });
+ const license = await createLicense(input);
return c.json({
- data: { key: license.licenseKey },
+ data: { key: license.key },
} satisfies CreateLicenseResponse);
} catch (error) {
logger.error({ error }, "Failed to create license");
@@ -92,57 +82,25 @@ app.post(
async (c) => {
const { key, fingerprint } = c.req.valid("json");
- const license = await prisma.license.findUnique({
- where: {
- licenseKey: key,
- },
- select: {
- id: true,
- licenseKey: true,
- status: true,
- issuedAt: true,
- expiresAt: true,
- licenseeEmail: true,
- licenseeName: true,
- seats: true,
- type: true,
- version: true,
- whiteLabelAddon: true,
- },
+ const result = await validateLicenseKey({
+ key,
+ fingerprint,
+ ipAddress: c.req.header("x-forwarded-for"),
+ userAgent: c.req.header("user-agent"),
});
- if (!license) {
- return c.json({ error: "License not found" }, 404);
- }
-
- if (license.status !== "ACTIVE") {
+ if (!result.valid) {
+ if (result.error === "not_found") {
+ return c.json({ error: "License not found" }, 404);
+ }
+ if (result.error === "expired") {
+ return c.json({ error: "License has expired" }, 400);
+ }
return c.json({ error: "License is not active" }, 400);
}
- await prisma.licenseValidation.create({
- data: {
- licenseId: license.id,
- ipAddress: c.req.header("x-forwarded-for"),
- fingerprint,
- validatedAt: new Date(),
- userAgent: c.req.header("user-agent"),
- },
- });
-
return c.json({
- data: {
- key: license.licenseKey,
- valid: license.status === "ACTIVE",
- status: license.status,
- issuedAt: license.issuedAt,
- expiresAt: license.expiresAt,
- licenseeEmail: license.licenseeEmail,
- licenseeName: license.licenseeName,
- seats: license.seats,
- type: license.type,
- version: license.version,
- whiteLabelAddon: license.whiteLabelAddon,
- },
+ data: result.license,
} satisfies ValidateLicenseKeyResponse);
},
);
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts b/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts
deleted file mode 100644
index 32ecd1866..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { sendLicenseKeyEmail } from "@rallly/emails/templates/license-key";
-import { getInstanceBranding } from "@/emails/branding";
-import { env } from "@/env";
-import { posthog } from "@/features/analytics/posthog";
-import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";
-import { licenseManager } from "@/features/licensing/server";
-
-export async function onCheckoutSessionCompleted(event: Stripe.Event) {
- const checkoutSession = event.data.object as Stripe.Checkout.Session;
-
- if (checkoutSession.subscription === null) {
- const { success, data } = licenseCheckoutMetadataSchema.safeParse(
- checkoutSession.metadata,
- );
-
- if (!success) {
- // If there is no metadata than this is likely a donation from a payment link
- console.info("No metadata found for session: ", checkoutSession.id);
- return;
- }
-
- const { licenseType, version, seats } = data;
-
- const customerDetails = checkoutSession.customer_details;
-
- if (!customerDetails) {
- throw new Error(
- `No customer details found for session: ${checkoutSession.id}`,
- );
- }
-
- const { email } = customerDetails;
-
- if (!email) {
- throw new Error(
- `No email found for customer details in session: ${checkoutSession.id}`,
- );
- }
-
- const license = await licenseManager.createLicense({
- type: licenseType,
- licenseeEmail: email,
- licenseeName: customerDetails.name ?? undefined,
- version,
- seats,
- });
-
- if (!license || !license.data) {
- throw new Error(
- `Failed to create license for session: ${checkoutSession.id} - ${license?.error}`,
- );
- }
-
- await sendLicenseKeyEmail({
- to: email,
- from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },
- branding: await getInstanceBranding(),
- props: {
- licenseKey: license.data.key,
- seats,
- tier: licenseType,
- },
- });
-
- posthog()?.capture({
- distinctId: email,
- event: "license_purchase",
- properties: {
- licenseType,
- seats,
- version,
- stripeEventId: event.id,
- $set: {
- tier: licenseType,
- },
- },
- });
- }
-}
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.ts
deleted file mode 100644
index 6d9129c47..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/checkout/expired.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import * as Sentry from "@sentry/nextjs";
-
-export async function onCheckoutSessionExpired(event: Stripe.Event) {
- const session = event.data.object as Stripe.Checkout.Session;
- // When a Checkout Session expires, the customer's email isn't returned in
- // the webhook payload unless they give consent for promotional content
- const email = session.customer_details?.email;
- const recoveryUrl = session.after_expiration?.recovery?.url;
- const userId = session.metadata?.userId;
-
- if (!userId) {
- Sentry.captureMessage("No user ID found in Checkout Session metadata");
- return;
- }
-
- // Do nothing if the Checkout Session has no email or recovery URL
- if (!email || !recoveryUrl) {
- Sentry.captureMessage("No email or recovery URL found in Checkout Session");
- return;
- }
-
- // 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/app/api/stripe/webhook/handlers/customer-subscription/created.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts
deleted file mode 100644
index 5cf157614..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-import { sendRawEmail } from "@rallly/emails";
-import { after } from "next/server";
-import { env } from "@/env";
-import { posthog } from "@/features/analytics/posthog";
-import { subscriptionMetadataSchema } from "@/features/subscription/schema";
-import {
- getExpandedSubscription,
- getSubscriptionDetails,
- isSubscriptionActive,
- syncSpaceTier,
- toDate,
-} from "../utils";
-
-export async function onCustomerSubscriptionCreated(event: Stripe.Event) {
- const subscription = await getExpandedSubscription(
- (event.data.object as Stripe.Subscription).id,
- );
-
- const isActive = isSubscriptionActive(subscription);
- const { priceId, currency, interval, amount } =
- getSubscriptionDetails(subscription);
-
- const res = subscriptionMetadataSchema.safeParse(subscription.metadata);
-
- if (!res.success) {
- throw new Error("Invalid subscription metadata");
- }
-
- const { userId, spaceId } = res.data;
-
- const subscriptionItem = subscription.items.data[0];
-
- if (!subscriptionItem) {
- throw new Error(
- `Missing subscription item in subscription ${subscription.id}`,
- );
- }
-
- const subscriptionItemId = subscriptionItem.id;
- const quantity = subscriptionItem.quantity ?? 1;
-
- const tier = await prisma.$transaction(async (tx) => {
- await tx.subscription.upsert({
- where: { id: subscription.id },
- create: {
- id: subscription.id,
- userId,
- active: isActive,
- quantity,
- subscriptionItemId,
- priceId,
- currency,
- interval,
- amount,
- status: subscription.status,
- createdAt: toDate(subscription.created),
- periodStart: toDate(subscription.current_period_start),
- periodEnd: toDate(subscription.current_period_end),
- cancelAtPeriodEnd: subscription.cancel_at_period_end,
- spaceId,
- },
- update: {
- id: subscription.id,
- userId,
- active: isActive,
- subscriptionItemId,
- quantity,
- priceId,
- currency,
- interval,
- amount,
- status: subscription.status,
- createdAt: toDate(subscription.created),
- periodStart: toDate(subscription.current_period_start),
- periodEnd: toDate(subscription.current_period_end),
- cancelAtPeriodEnd: subscription.cancel_at_period_end,
- spaceId,
- },
- include: {
- space: true,
- },
- });
-
- return syncSpaceTier(tx, spaceId);
- });
-
- posthog()?.groupIdentify({
- groupType: "space",
- groupKey: spaceId,
- properties: {
- seatCount: quantity,
- tier,
- },
- });
-
- posthog()?.capture({
- distinctId: userId,
- event: "subscription_create",
- properties: {
- interval,
- $set: {
- tier,
- },
- },
- groups: {
- space: spaceId,
- },
- });
-
- if (isActive) {
- after(async () => {
- const user = await prisma.user.findUnique({
- where: { id: userId },
- select: { email: true, name: true },
- });
-
- if (user) {
- await sendRawEmail({
- to: user.email,
- from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },
- subject: "Thanks for subscribing to Rallly Pro",
- text: [
- "Hey there,",
- "Thanks so much for subscribing to Rallly Pro! I really appreciate your support.",
- "I'd love to learn more about how you're using Rallly. What kind of events are you scheduling? Are there any features you wish Rallly had?",
- "Just hit reply and let me know. I read every response and it helps shape what we build next.",
- "Luke\nFounder, Rallly",
- ].join("\n\n"),
- });
- }
- });
- }
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.ts
deleted file mode 100644
index 2557170ac..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-import { posthog } from "@/features/analytics/posthog";
-import { subscriptionMetadataSchema } from "@/features/subscription/schema";
-import { syncSpaceTier } from "../utils";
-
-export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
- const subscription = await stripe.subscriptions.retrieve(
- (event.data.object as Stripe.Subscription).id,
- );
-
- // void any unpaid invoices
- const invoices = await stripe.invoices.list({
- subscription: subscription.id,
- status: "open",
- });
-
- for (const invoice of invoices.data) {
- await stripe.invoices.voidInvoice(invoice.id);
- }
-
- const res = subscriptionMetadataSchema.safeParse(subscription.metadata);
-
- if (!res.success) {
- throw new Error("Invalid subscription metadata");
- }
-
- const { userId, spaceId } = res.data;
-
- const tier = await prisma.$transaction(async (tx) => {
- await tx.subscription.update({
- where: {
- id: subscription.id,
- },
- data: {
- active: false,
- status: "canceled",
- },
- });
-
- return syncSpaceTier(tx, spaceId);
- });
-
- posthog()?.groupIdentify({
- groupType: "space",
- groupKey: spaceId,
- properties: {
- tier,
- },
- });
-
- posthog()?.capture({
- distinctId: userId,
- event: "subscription_cancel",
- properties: {
- $set: {
- tier,
- },
- },
- groups: {
- space: spaceId,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.ts
deleted file mode 100644
index 156c090ee..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-import { posthog } from "@/features/analytics/posthog";
-import { subscriptionMetadataSchema } from "@/features/subscription/schema";
-import {
- getExpandedSubscription,
- getSubscriptionDetails,
- isSubscriptionActive,
- syncSpaceTier,
- toDate,
-} from "../utils";
-
-export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {
- if (event.type !== "customer.subscription.updated") {
- return;
- }
-
- const subscription = await getExpandedSubscription(
- (event.data.object as Stripe.Subscription).id,
- );
-
- const isActive = isSubscriptionActive(subscription);
- const { priceId, currency, interval, amount } =
- getSubscriptionDetails(subscription);
-
- const res = subscriptionMetadataSchema.safeParse(subscription.metadata);
-
- if (!res.success) {
- throw new Error("Invalid subscription metadata");
- }
-
- const { userId, spaceId } = res.data;
-
- const subscriptionItem = subscription.items.data[0];
-
- if (!subscriptionItem) {
- throw new Error("Expected subscription to have one item");
- }
-
- const subscriptionItemId = subscriptionItem.id;
- const quantity = subscriptionItem.quantity ?? 1;
-
- // Update the subscription in the database
- const tier = await prisma.$transaction(async (tx) => {
- await tx.subscription.upsert({
- where: {
- id: subscription.id,
- },
- update: {
- active: isActive,
- priceId,
- currency,
- interval,
- subscriptionItemId,
- quantity,
- amount,
- status: subscription.status,
- periodStart: toDate(subscription.current_period_start),
- periodEnd: toDate(subscription.current_period_end),
- cancelAtPeriodEnd: subscription.cancel_at_period_end,
- },
- create: {
- id: subscription.id,
- userId,
- spaceId,
- active: isActive,
- priceId,
- currency,
- interval,
- subscriptionItemId,
- quantity,
- amount,
- status: subscription.status,
- periodStart: toDate(subscription.current_period_start),
- periodEnd: toDate(subscription.current_period_end),
- cancelAtPeriodEnd: subscription.cancel_at_period_end,
- },
- });
-
- return syncSpaceTier(tx, spaceId);
- });
-
- posthog()?.groupIdentify({
- groupType: "space",
- groupKey: spaceId,
- properties: {
- seatCount: quantity,
- tier,
- },
- });
-
- posthog()?.capture({
- distinctId: userId,
- event: "subscription_update",
- properties: {
- interval,
- quantity,
- $set: {
- tier,
- },
- },
- groups: {
- space: spaceId,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer/created.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer/created.ts
deleted file mode 100644
index af635c265..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/customer/created.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-import { customerMetadataSchema } from "@/features/billing/schema";
-
-export async function onCustomerCreated(event: Stripe.Event) {
- const customer = event.data.object as Stripe.Customer;
-
- const res = customerMetadataSchema.safeParse(customer.metadata);
-
- if (!res.success) {
- // If there's no userId in metadata, ignore the event
- return;
- }
-
- const { userId } = res.data;
-
- // Update the user with the customer id
- await prisma.user.update({
- where: {
- id: userId,
- },
- data: {
- customerId: customer.id,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer/deleted.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer/deleted.ts
deleted file mode 100644
index 3df45e44f..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/customer/deleted.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-
-export async function onCustomerDeleted(event: Stripe.Event) {
- const customer = event.data.object as Stripe.Customer;
-
- // Find and update the user with this customerId
- await prisma.user.updateMany({
- where: {
- customerId: customer.id,
- },
- data: {
- customerId: null,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer/index.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer/index.ts
deleted file mode 100644
index f3f797530..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/customer/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from "./created";
-export * from "./deleted";
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/index.ts b/apps/web/src/app/api/stripe/webhook/handlers/index.ts
deleted file mode 100644
index 0bc44fd62..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/index.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-
-import { onCheckoutSessionCompleted } from "./checkout/completed";
-import { onCheckoutSessionExpired } from "./checkout/expired";
-import { onCustomerCreated, onCustomerDeleted } from "./customer";
-import { onCustomerSubscriptionCreated } from "./customer-subscription/created";
-import { onCustomerSubscriptionDeleted } from "./customer-subscription/deleted";
-import { onCustomerSubscriptionUpdated } from "./customer-subscription/updated";
-import {
- onPaymentMethodAttached,
- onPaymentMethodDetached,
- onPaymentMethodUpdated,
-} from "./payment-method";
-
-type WebhookHandler = (event: Stripe.Event) => Promise<void>;
-
-export function getEventHandler(
- eventType: Stripe.Event["type"],
-): WebhookHandler | null {
- switch (eventType) {
- case "checkout.session.completed":
- return onCheckoutSessionCompleted;
- case "checkout.session.expired":
- return onCheckoutSessionExpired;
- case "customer.created":
- return onCustomerCreated;
- case "customer.deleted":
- return onCustomerDeleted;
- case "customer.subscription.created":
- return onCustomerSubscriptionCreated;
- case "customer.subscription.deleted":
- return onCustomerSubscriptionDeleted;
- case "customer.subscription.updated":
- return onCustomerSubscriptionUpdated;
- case "payment_method.attached":
- return onPaymentMethodAttached;
- case "payment_method.detached":
- return onPaymentMethodDetached;
- case "payment_method.automatically_updated":
- case "payment_method.updated":
- return onPaymentMethodUpdated;
- default:
- return null;
- }
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/attached.ts b/apps/web/src/app/api/stripe/webhook/handlers/payment-method/attached.ts
deleted file mode 100644
index 54c7b2466..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/attached.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-
-import { createOrUpdatePaymentMethod } from "../utils";
-
-export async function onPaymentMethodAttached(event: Stripe.Event) {
- const paymentMethod = event.data.object as Stripe.PaymentMethod;
-
- // Only handle payment methods that are attached to a customer
- if (!paymentMethod.customer) {
- return;
- }
-
- // Find the user associated with this customer
- const user = await prisma.user.findFirst({
- where: {
- customerId: paymentMethod.customer as string,
- },
- });
-
- if (!user) {
- throw new Error(`No user found for customer ${paymentMethod.customer}`);
- }
-
- // Upsert the payment method in our database
- await createOrUpdatePaymentMethod(user.id, paymentMethod);
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/detached.ts b/apps/web/src/app/api/stripe/webhook/handlers/payment-method/detached.ts
deleted file mode 100644
index 1432345c2..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/detached.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { prisma } from "@rallly/database";
-
-export async function onPaymentMethodDetached(event: Stripe.Event) {
- const paymentMethod = event.data.object as Stripe.PaymentMethod;
-
- // Delete the payment method from our database
- await prisma.paymentMethod.delete({
- where: {
- id: paymentMethod.id,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/index.ts b/apps/web/src/app/api/stripe/webhook/handlers/payment-method/index.ts
deleted file mode 100644
index e00523692..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from "./attached";
-export * from "./detached";
-export * from "./updated";
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/updated.ts b/apps/web/src/app/api/stripe/webhook/handlers/payment-method/updated.ts
deleted file mode 100644
index 5400f4c4e..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/payment-method/updated.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import type { Prisma } from "@rallly/database";
-import { prisma } from "@rallly/database";
-
-export async function onPaymentMethodUpdated(event: Stripe.Event) {
- const paymentMethod = event.data.object as Stripe.PaymentMethod;
-
- if (!paymentMethod.customer) {
- return;
- }
-
- // Update the payment method data in our database
- await prisma.paymentMethod.update({
- where: {
- id: paymentMethod.id,
- },
- data: {
- type: paymentMethod.type,
- data: paymentMethod[paymentMethod.type] as Prisma.JsonObject,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/utils.ts b/apps/web/src/app/api/stripe/webhook/handlers/utils.ts
deleted file mode 100644
index d63d59030..000000000
--- a/apps/web/src/app/api/stripe/webhook/handlers/utils.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import type { Stripe } from "@rallly/billing";
-import { stripe } from "@rallly/billing";
-import type { Prisma } from "@rallly/database";
-import { prisma } from "@rallly/database";
-import { billingIntervalSchema } from "@/features/billing/schema";
-
-export function toDate(date: number) {
- return new Date(date * 1000);
-}
-
-export async function getExpandedSubscription(subscriptionId: string) {
- return stripe.subscriptions.retrieve(subscriptionId, {
- expand: ["items.data.price.currency_options"],
- });
-}
-
-export function isSubscriptionActive(subscription: Stripe.Subscription) {
- return (
- subscription.status === "active" ||
- subscription.status === "trialing" ||
- subscription.status === "past_due"
- );
-}
-
-/**
- * Recomputes a space's tier from its subscriptions so the tier reflects whether
- * *any* subscription is active, rather than the state of a single webhook event.
- * Must run after the triggering subscription's `active` flag has been written in
- * the same transaction. Returns the resolved tier.
- */
-export async function syncSpaceTier(
- tx: Prisma.TransactionClient,
- spaceId: string,
-) {
- const activeSubscription = await tx.subscription.findFirst({
- where: { spaceId, active: true },
- select: { id: true },
- });
-
- const tier = activeSubscription ? "pro" : "hobby";
-
- await tx.space.update({
- where: { id: spaceId },
- data: {
- tier,
- ...(tier === "hobby" ? { showBranding: false } : {}),
- },
- });
-
- return tier;
-}
-
-export function getSubscriptionDetails(subscription: Stripe.Subscription) {
- const subscriptionItem = subscription.items.data[0];
- const interval = subscriptionItem.price.recurring?.interval;
- const currency = subscription.currency;
- const amount =
- subscriptionItem.price.currency_options?.[currency]?.unit_amount ??
- subscriptionItem.price.unit_amount;
-
- if (!interval) {
- throw new Error(`Missing interval in subscription ${subscription.id}`);
- }
-
- if (!amount) {
- throw new Error(`Missing amount in subscription ${subscription.id}`);
- }
-
- const intervalResult = billingIntervalSchema.safeParse(interval);
-
- if (!intervalResult.success) {
- throw new Error(`Invalid interval: ${interval}`);
- }
-
- return {
- interval: intervalResult.data,
- currency,
- amount,
- priceId: subscriptionItem.price.id,
- };
-}
-
-export async function createOrUpdatePaymentMethod(
- userId: string,
- paymentMethod: Stripe.PaymentMethod,
-) {
- await prisma.paymentMethod.upsert({
- where: {
- id: paymentMethod.id,
- },
- create: {
- id: paymentMethod.id,
- userId,
- type: paymentMethod.type,
- data: paymentMethod[paymentMethod.type] as Prisma.JsonObject,
- },
- update: {
- type: paymentMethod.type,
- data: paymentMethod[paymentMethod.type] as Prisma.JsonObject,
- },
- });
-}
diff --git a/apps/web/src/app/api/stripe/webhook/route.ts b/apps/web/src/app/api/stripe/webhook/route.ts
index 16d16c2e5..d6c9467ec 100644
--- a/apps/web/src/app/api/stripe/webhook/route.ts
+++ b/apps/web/src/app/api/stripe/webhook/route.ts
@@ -4,8 +4,8 @@ import * as Sentry from "@sentry/nextjs";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { withPostHog } from "@/features/analytics/posthog";
+import { handleStripeWebhookEvent } from "@/features/billing/webhook/mutations";
import { isSelfHosted } from "@/lib/constants";
-import { getEventHandler } from "./handlers";
const handler = async (request: NextRequest) => {
if (isSelfHosted) {
@@ -40,18 +40,13 @@ const handler = async (request: NextRequest) => {
}
try {
- const handler = getEventHandler(event.type);
+ const { handled } = await handleStripeWebhookEvent(event);
- if (!handler) {
+ if (!handled) {
Sentry.captureException(new Error(`Unhandled event type: ${event.type}`));
- return NextResponse.json(
- { error: "Unhandled event type" },
- { status: 400 },
- );
+ return NextResponse.json({ received: true, ignored: true });
}
- await handler(event);
-
return NextResponse.json({ received: true });
} catch (err) {
Sentry.captureException(err);
diff --git a/apps/web/src/features/billing/webhook/mutations.ts b/apps/web/src/features/billing/webhook/mutations.ts
new file mode 100644
index 000000000..0ed4c5858
--- /dev/null
+++ b/apps/web/src/features/billing/webhook/mutations.ts
@@ -0,0 +1,581 @@
+import "server-only";
+
+import type { Stripe } from "@rallly/billing";
+import { stripe } from "@rallly/billing";
+import type { Prisma } from "@rallly/database";
+import { prisma } from "@rallly/database";
+import { sendRawEmail } from "@rallly/emails";
+import { sendLicenseKeyEmail } from "@rallly/emails/templates/license-key";
+import * as Sentry from "@sentry/nextjs";
+import { after } from "next/server";
+import { getInstanceBranding } from "@/emails/branding";
+import { env } from "@/env";
+import { posthog } from "@/features/analytics/posthog";
+import { customerMetadataSchema } from "@/features/billing/schema";
+import {
+ getSubscriptionDetails,
+ isSubscriptionActive,
+ toDate,
+} from "@/features/billing/webhook/utils";
+import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";
+import { licenseManager } from "@/features/licensing/server";
+import { subscriptionMetadataSchema } from "@/features/subscription/schema";
+
+async function getExpandedSubscription(subscriptionId: string) {
+ return stripe.subscriptions.retrieve(subscriptionId, {
+ expand: ["items.data.price.currency_options"],
+ });
+}
+
+/**
+ * Recomputes a space's tier from its subscriptions so the tier reflects whether
+ * *any* subscription is active, rather than the state of a single webhook event.
+ * Must run after the triggering subscription's `active` flag has been written in
+ * the same transaction. Returns the resolved tier.
+ */
+async function syncSpaceTier(tx: Prisma.TransactionClient, spaceId: string) {
+ const activeSubscription = await tx.subscription.findFirst({
+ where: { spaceId, active: true },
+ select: { id: true },
+ });
+
+ const tier = activeSubscription ? "pro" : "hobby";
+
+ await tx.space.update({
+ where: { id: spaceId },
+ data: {
+ tier,
+ ...(tier === "hobby" ? { showBranding: false } : {}),
+ },
+ });
+
+ return tier;
+}
+
+async function createOrUpdatePaymentMethod(
+ userId: string,
+ paymentMethod: Stripe.PaymentMethod,
+) {
+ await prisma.paymentMethod.upsert({
+ where: {
+ id: paymentMethod.id,
+ },
+ create: {
+ id: paymentMethod.id,
+ userId,
+ type: paymentMethod.type,
+ data: paymentMethod[paymentMethod.type] as Prisma.JsonObject,
+ },
+ update: {
+ type: paymentMethod.type,
+ data: paymentMethod[paymentMethod.type] as Prisma.JsonObject,
+ },
+ });
+}
+
+async function onCheckoutSessionCompleted(event: Stripe.Event) {
+ const checkoutSession = event.data.object as Stripe.Checkout.Session;
+
+ if (checkoutSession.subscription === null) {
+ const { success, data } = licenseCheckoutMetadataSchema.safeParse(
+ checkoutSession.metadata,
+ );
+
+ if (!success) {
+ // If there is no metadata than this is likely a donation from a payment link
+ console.info("No metadata found for session: ", checkoutSession.id);
+ return;
+ }
+
+ const { licenseType, version, seats } = data;
+
+ const customerDetails = checkoutSession.customer_details;
+
+ if (!customerDetails) {
+ throw new Error(
+ `No customer details found for session: ${checkoutSession.id}`,
+ );
+ }
+
+ const { email } = customerDetails;
+
+ if (!email) {
+ throw new Error(
+ `No email found for customer details in session: ${checkoutSession.id}`,
+ );
+ }
+
+ const license = await licenseManager.createLicense({
+ type: licenseType,
+ licenseeEmail: email,
+ licenseeName: customerDetails.name ?? undefined,
+ version,
+ seats,
+ idempotencyKey: checkoutSession.id,
+ });
+
+ if (!license || !license.data) {
+ throw new Error(
+ `Failed to create license for session: ${checkoutSession.id} - ${license?.error}`,
+ );
+ }
+
+ await sendLicenseKeyEmail({
+ to: email,
+ from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },
+ branding: await getInstanceBranding(),
+ props: {
+ licenseKey: license.data.key,
+ seats,
+ tier: licenseType,
+ },
+ });
+
+ posthog()?.capture({
+ distinctId: email,
+ event: "license_purchase",
+ properties: {
+ licenseType,
+ seats,
+ version,
+ stripeEventId: event.id,
+ $set: {
+ tier: licenseType,
+ },
+ },
+ });
+ }
+}
+
+async function onCheckoutSessionExpired(event: Stripe.Event) {
+ const session = event.data.object as Stripe.Checkout.Session;
+ // When a Checkout Session expires, the customer's email isn't returned in
+ // the webhook payload unless they give consent for promotional content
+ const email = session.customer_details?.email;
+ const recoveryUrl = session.after_expiration?.recovery?.url;
+ const userId = session.metadata?.userId;
+
+ if (!userId) {
+ Sentry.captureMessage("No user ID found in Checkout Session metadata");
+ return;
+ }
+
+ // Do nothing if the Checkout Session has no email or recovery URL
+ if (!email || !recoveryUrl) {
+ Sentry.captureMessage("No email or recovery URL found in Checkout Session");
+ return;
+ }
+
+ // TODO (Luke Vella) [2025-08-04]: We may want to send the user an email to users who do not complete checkout
+}
+
+async function onCustomerCreated(event: Stripe.Event) {
+ const customer = event.data.object as Stripe.Customer;
+
+ const res = customerMetadataSchema.safeParse(customer.metadata);
+
+ if (!res.success) {
+ // If there's no userId in metadata, ignore the event
+ return;
+ }
+
+ const { userId } = res.data;
+
+ // Update the user with the customer id
+ await prisma.user.update({
+ where: {
+ id: userId,
+ },
+ data: {
+ customerId: customer.id,
+ },
+ });
+}
+
+async function onCustomerDeleted(event: Stripe.Event) {
+ const customer = event.data.object as Stripe.Customer;
+
+ // Find and update the user with this customerId
+ await prisma.user.updateMany({
+ where: {
+ customerId: customer.id,
+ },
+ data: {
+ customerId: null,
+ },
+ });
+}
+
+async function onCustomerSubscriptionCreated(event: Stripe.Event) {
+ const subscription = await getExpandedSubscription(
+ (event.data.object as Stripe.Subscription).id,
+ );
+
+ const isActive = isSubscriptionActive(subscription);
+ const { priceId, currency, interval, amount } =
+ getSubscriptionDetails(subscription);
+
+ const res = subscriptionMetadataSchema.safeParse(subscription.metadata);
+
+ if (!res.success) {
+ throw new Error("Invalid subscription metadata");
+ }
+
+ const { userId, spaceId } = res.data;
+
+ const subscriptionItem = subscription.items.data[0];
+
+ if (!subscriptionItem) {
+ throw new Error(
+ `Missing subscription item in subscription ${subscription.id}`,
+ );
+ }
+
+ const subscriptionItemId = subscriptionItem.id;
+ const quantity = subscriptionItem.quantity ?? 1;
+
+ const tier = await prisma.$transaction(async (tx) => {
+ await tx.subscription.upsert({
+ where: { id: subscription.id },
+ create: {
+ id: subscription.id,
+ userId,
+ active: isActive,
+ quantity,
+ subscriptionItemId,
+ priceId,
+ currency,
+ interval,
+ amount,
+ status: subscription.status,
+ createdAt: toDate(subscription.created),
+ periodStart: toDate(subscription.current_period_start),
+ periodEnd: toDate(subscription.current_period_end),
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ spaceId,
+ },
+ update: {
+ id: subscription.id,
+ userId,
+ active: isActive,
+ subscriptionItemId,
+ quantity,
+ priceId,
+ currency,
+ interval,
+ amount,
+ status: subscription.status,
+ createdAt: toDate(subscription.created),
+ periodStart: toDate(subscription.current_period_start),
+ periodEnd: toDate(subscription.current_period_end),
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ spaceId,
+ },
+ include: {
+ space: true,
+ },
+ });
+
+ return syncSpaceTier(tx, spaceId);
+ });
+
+ posthog()?.groupIdentify({
+ groupType: "space",
+ groupKey: spaceId,
+ properties: {
+ seatCount: quantity,
+ tier,
+ },
+ });
+
+ posthog()?.capture({
+ distinctId: userId,
+ event: "subscription_create",
+ properties: {
+ interval,
+ $set: {
+ tier,
+ },
+ },
+ groups: {
+ space: spaceId,
+ },
+ });
+
+ if (isActive) {
+ after(async () => {
+ const user = await prisma.user.findUnique({
+ where: { id: userId },
+ select: { email: true, name: true },
+ });
+
+ if (user) {
+ await sendRawEmail({
+ to: user.email,
+ from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },
+ subject: "Thanks for subscribing to Rallly Pro",
+ text: [
+ "Hey there,",
+ "Thanks so much for subscribing to Rallly Pro! I really appreciate your support.",
+ "I'd love to learn more about how you're using Rallly. What kind of events are you scheduling? Are there any features you wish Rallly had?",
+ "Just hit reply and let me know. I read every response and it helps shape what we build next.",
+ "Luke\nFounder, Rallly",
+ ].join("\n\n"),
+ });
+ }
+ });
+ }
+}
+
+async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
+ const subscription = await stripe.subscriptions.retrieve(
+ (event.data.object as Stripe.Subscription).id,
+ );
+
+ // void any unpaid invoices
+ const invoices = await stripe.invoices.list({
+ subscription: subscription.id,
+ status: "open",
+ });
+
+ for (const invoice of invoices.data) {
+ await stripe.invoices.voidInvoice(invoice.id);
+ }
+
+ const res = subscriptionMetadataSchema.safeParse(subscription.metadata);
+
+ if (!res.success) {
+ throw new Error("Invalid subscription metadata");
+ }
+
+ const { userId, spaceId } = res.data;
+
+ const tier = await prisma.$transaction(async (tx) => {
+ // updateMany so a missing row (e.g. already cascade-deleted with the user
+ // or space) doesn't abort the transaction before the tier sync runs
+ await tx.subscription.updateMany({
+ where: {
+ id: subscription.id,
+ },
+ data: {
+ active: false,
+ status: "canceled",
+ },
+ });
+
+ return syncSpaceTier(tx, spaceId);
+ });
+
+ posthog()?.groupIdentify({
+ groupType: "space",
+ groupKey: spaceId,
+ properties: {
+ tier,
+ },
+ });
+
+ posthog()?.capture({
+ distinctId: userId,
+ event: "subscription_cancel",
+ properties: {
+ $set: {
+ tier,
+ },
+ },
+ groups: {
+ space: spaceId,
+ },
+ });
+}
+
+async function onCustomerSubscriptionUpdated(event: Stripe.Event) {
+ if (event.type !== "customer.subscription.updated") {
+ return;
+ }
+
+ const subscription = await getExpandedSubscription(
+ (event.data.object as Stripe.Subscription).id,
+ );
+
+ const isActive = isSubscriptionActive(subscription);
+ const { priceId, currency, interval, amount } =
+ getSubscriptionDetails(subscription);
+
+ const res = subscriptionMetadataSchema.safeParse(subscription.metadata);
+
+ if (!res.success) {
+ throw new Error("Invalid subscription metadata");
+ }
+
+ const { userId, spaceId } = res.data;
+
+ const subscriptionItem = subscription.items.data[0];
+
+ if (!subscriptionItem) {
+ throw new Error("Expected subscription to have one item");
+ }
+
+ const subscriptionItemId = subscriptionItem.id;
+ const quantity = subscriptionItem.quantity ?? 1;
+
+ // Update the subscription in the database
+ const tier = await prisma.$transaction(async (tx) => {
+ await tx.subscription.upsert({
+ where: {
+ id: subscription.id,
+ },
+ update: {
+ active: isActive,
+ priceId,
+ currency,
+ interval,
+ subscriptionItemId,
+ quantity,
+ amount,
+ status: subscription.status,
+ periodStart: toDate(subscription.current_period_start),
+ periodEnd: toDate(subscription.current_period_end),
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ },
+ create: {
+ id: subscription.id,
+ userId,
+ spaceId,
+ active: isActive,
+ priceId,
+ currency,
+ interval,
+ subscriptionItemId,
+ quantity,
+ amount,
+ status: subscription.status,
+ createdAt: toDate(subscription.created),
+ periodStart: toDate(subscription.current_period_start),
+ periodEnd: toDate(subscription.current_period_end),
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ },
+ });
+
+ return syncSpaceTier(tx, spaceId);
+ });
+
+ posthog()?.groupIdentify({
+ groupType: "space",
+ groupKey: spaceId,
+ properties: {
+ seatCount: quantity,
+ tier,
+ },
+ });
+
+ posthog()?.capture({
+ distinctId: userId,
+ event: "subscription_update",
+ properties: {
+ interval,
+ quantity,
+ $set: {
+ tier,
+ },
+ },
+ groups: {
+ space: spaceId,
+ },
+ });
+}
+
+async function onPaymentMethodAttached(event: Stripe.Event) {
+ const paymentMethod = event.data.object as Stripe.PaymentMethod;
+
+ // Only handle payment methods that are attached to a customer
+ if (!paymentMethod.customer) {
+ return;
+ }
+
+ // Find the user associated with this customer
+ const user = await prisma.user.findFirst({
+ where: {
+ customerId: paymentMethod.customer as string,
+ },
+ });
+
+ if (!user) {
+ throw new Error(`No user found for customer ${paymentMethod.customer}`);
+ }
+
+ // Upsert the payment method in our database
+ await createOrUpdatePaymentMethod(user.id, paymentMethod);
+}
+
+async function onPaymentMethodDetached(event: Stripe.Event) {
+ const paymentMethod = event.data.object as Stripe.PaymentMethod;
+
+ // deleteMany so repeated detach events don't throw when the record is gone
+ await prisma.paymentMethod.deleteMany({
+ where: {
+ id: paymentMethod.id,
+ },
+ });
+}
+
+async function onPaymentMethodUpdated(event: Stripe.Event) {
+ const paymentMethod = event.data.object as Stripe.PaymentMethod;
+
+ if (!paymentMethod.customer) {
+ return;
+ }
+
+ // Find the user associated with this customer
+ const user = await prisma.user.findFirst({
+ where: {
+ customerId: paymentMethod.customer as string,
+ },
+ });
+
+ if (!user) {
+ throw new Error(`No user found for customer ${paymentMethod.customer}`);
+ }
+
+ // Upsert so the event succeeds even if the attach event was missed
+ await createOrUpdatePaymentMethod(user.id, paymentMethod);
+}
+
+export async function handleStripeWebhookEvent(event: Stripe.Event) {
+ switch (event.type) {
+ case "checkout.session.completed":
+ await onCheckoutSessionCompleted(event);
+ break;
+ case "checkout.session.expired":
+ await onCheckoutSessionExpired(event);
+ break;
+ case "customer.created":
+ await onCustomerCreated(event);
+ break;
+ case "customer.deleted":
+ await onCustomerDeleted(event);
+ break;
+ case "customer.subscription.created":
+ await onCustomerSubscriptionCreated(event);
+ break;
+ case "customer.subscription.deleted":
+ await onCustomerSubscriptionDeleted(event);
+ break;
+ case "customer.subscription.updated":
+ await onCustomerSubscriptionUpdated(event);
+ break;
+ case "payment_method.attached":
+ await onPaymentMethodAttached(event);
+ break;
+ case "payment_method.detached":
+ await onPaymentMethodDetached(event);
+ break;
+ case "payment_method.automatically_updated":
+ case "payment_method.updated":
+ await onPaymentMethodUpdated(event);
+ break;
+ default:
+ return { handled: false };
+ }
+
+ return { handled: true };
+}
diff --git a/apps/web/src/features/billing/webhook/utils.ts b/apps/web/src/features/billing/webhook/utils.ts
new file mode 100644
index 000000000..5c4119e61
--- /dev/null
+++ b/apps/web/src/features/billing/webhook/utils.ts
@@ -0,0 +1,52 @@
+import type { Stripe } from "@rallly/billing";
+import { billingIntervalSchema } from "@/features/billing/schema";
+
+export function toDate(date: number) {
+ return new Date(date * 1000);
+}
+
+export function isSubscriptionActive(subscription: Stripe.Subscription) {
+ return (
+ subscription.status === "active" ||
+ subscription.status === "trialing" ||
+ subscription.status === "past_due"
+ );
+}
+
+export function getSubscriptionDetails(subscription: Stripe.Subscription) {
+ const subscriptionItem = subscription.items.data[0];
+
+ if (!subscriptionItem) {
+ throw new Error(
+ `Missing subscription item in subscription ${subscription.id}`,
+ );
+ }
+
+ const interval = subscriptionItem.price.recurring?.interval;
+ const currency = subscription.currency;
+ const amount =
+ subscriptionItem.price.currency_options?.[currency]?.unit_amount ??
+ subscriptionItem.price.unit_amount;
+
+ if (!interval) {
+ throw new Error(`Missing interval in subscription ${subscription.id}`);
+ }
+
+ // Nullish check: unit_amount can legitimately be 0 for free prices
+ if (amount == null) {
+ throw new Error(`Missing amount in subscription ${subscription.id}`);
+ }
+
+ const intervalResult = billingIntervalSchema.safeParse(interval);
+
+ if (!intervalResult.success) {
+ throw new Error(`Invalid interval: ${interval}`);
+ }
+
+ return {
+ interval: intervalResult.data,
+ currency,
+ amount,
+ priceId: subscriptionItem.price.id,
+ };
+}
diff --git a/apps/web/src/features/licensing/mutations.ts b/apps/web/src/features/licensing/mutations.ts
new file mode 100644
index 000000000..741428641
--- /dev/null
+++ b/apps/web/src/features/licensing/mutations.ts
@@ -0,0 +1,108 @@
+import "server-only";
+
+import { prisma } from "@rallly/database";
+import { generateLicenseKey } from "@/features/licensing/helpers/generate-license-key";
+import type { CreateLicenseInput } from "@/features/licensing/schema";
+
+export async function createLicense({
+ type,
+ seats,
+ expiresAt,
+ licenseeEmail,
+ licenseeName,
+ version,
+ idempotencyKey,
+}: CreateLicenseInput) {
+ const data = {
+ licenseKey: generateLicenseKey({ version }),
+ version,
+ type,
+ seats,
+ issuedAt: new Date(),
+ expiresAt,
+ licenseeEmail,
+ licenseeName,
+ };
+
+ // Upsert with an empty update so concurrent requests with the same key
+ // atomically resolve to the existing license instead of racing the insert
+ const license = idempotencyKey
+ ? await prisma.license.upsert({
+ where: { idempotencyKey },
+ update: {},
+ create: { ...data, idempotencyKey },
+ })
+ : await prisma.license.create({ data });
+
+ return { key: license.licenseKey };
+}
+
+export async function validateLicenseKey({
+ key,
+ fingerprint,
+ ipAddress,
+ userAgent,
+}: {
+ key: string;
+ fingerprint?: string;
+ ipAddress?: string;
+ userAgent?: string;
+}) {
+ const license = await prisma.license.findUnique({
+ where: {
+ licenseKey: key,
+ },
+ select: {
+ id: true,
+ licenseKey: true,
+ status: true,
+ issuedAt: true,
+ expiresAt: true,
+ licenseeEmail: true,
+ licenseeName: true,
+ seats: true,
+ type: true,
+ version: true,
+ whiteLabelAddon: true,
+ },
+ });
+
+ if (!license) {
+ return { valid: false as const, error: "not_found" as const };
+ }
+
+ if (license.status !== "ACTIVE") {
+ return { valid: false as const, error: "not_active" as const };
+ }
+
+ if (license.expiresAt && license.expiresAt < new Date()) {
+ return { valid: false as const, error: "expired" as const };
+ }
+
+ await prisma.licenseValidation.create({
+ data: {
+ licenseId: license.id,
+ ipAddress,
+ fingerprint,
+ validatedAt: new Date(),
+ userAgent,
+ },
+ });
+
+ return {
+ valid: true as const,
+ license: {
+ key: license.licenseKey,
+ valid: license.status === "ACTIVE",
+ status: license.status,
+ issuedAt: license.issuedAt,
+ expiresAt: license.expiresAt,
+ licenseeEmail: license.licenseeEmail,
+ licenseeName: license.licenseeName,
+ seats: license.seats,
+ type: license.type,
+ version: license.version,
+ whiteLabelAddon: license.whiteLabelAddon,
+ },
+ };
+}
diff --git a/apps/web/src/features/licensing/schema.ts b/apps/web/src/features/licensing/schema.ts
index 62935aef3..b303b89cf 100644
--- a/apps/web/src/features/licensing/schema.ts
+++ b/apps/web/src/features/licensing/schema.ts
@@ -36,6 +36,7 @@ export const createLicenseInputSchema = z.object({
licenseeEmail: z.string().optional(),
licenseeName: z.string().optional(),
version: z.coerce.number().optional(),
+ idempotencyKey: z.string().min(1).optional(),
});
export type CreateLicenseInput = z.infer<typeof createLicenseInputSchema>;
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index 56a0a7ec5..c0596b286 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -1,3 +1,5 @@
+import "server-only";
+
import { prisma } from "@rallly/database";
import { nanoid } from "@rallly/utils/nanoid";
@@ -104,3 +106,124 @@ export const deletePoll = async (pollId: string, spaceId: string) => {
return { id: pollId };
};
+
+/**
+ * Marks inactive polls as deleted. Polls are inactive if they have not been
+ * updated in the last 30 days and all dates are in the past.
+ * Only marks polls as deleted if they belong to users without an active subscription
+ * or if they don't have a user associated with them.
+ */
+export async function deleteInactivePolls() {
+ // Define the 30-day threshold once
+ const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
+
+ // Mark inactive polls as deleted in a single query
+ const { count: markedDeleted } = await prisma.poll.updateMany({
+ where: {
+ deleted: false,
+ // All poll dates are in the past
+ options: {
+ none: {
+ startTime: { gt: new Date() },
+ },
+ },
+ // We don't delete polls that belong to a space with an active subscription
+ OR: [
+ { spaceId: null },
+ {
+ space: {
+ tier: {
+ not: "pro",
+ },
+ },
+ },
+ ],
+ // Poll is inactive: not edited, and no participant activity (new or
+ // updated responses) or new comments in the last 30 days
+ updatedAt: { lt: thirtyDaysAgo },
+ participants: {
+ none: { updatedAt: { gte: thirtyDaysAgo } },
+ },
+ comments: {
+ none: { createdAt: { gte: thirtyDaysAgo } },
+ },
+ },
+ data: {
+ deleted: true,
+ deletedAt: new Date(),
+ },
+ });
+
+ return markedDeleted;
+}
+
+/**
+ * Closes polls whose options have all ended — i.e. no option ends in the
+ * future, where an option ends at start_time + duration (all-day options, with
+ * duration 0, are treated as ending 24h after their start). Closing is
+ * non-destructive: the poll becomes read-only but is preserved.
+ *
+ * Raw SQL because the option-end comparison (start_time + duration) can't be
+ * expressed in a Prisma `where`. It also deliberately does not touch
+ * `updated_at`, so closing a poll doesn't reset the inactivity clock that
+ * delete-inactive-polls keys off.
+ */
+export async function autoClosePolls() {
+ const closed = await prisma.$executeRaw`
+ UPDATE polls p
+ SET status = 'closed', closed_reason = 'auto'
+ WHERE p.status = 'open'
+ AND p.deleted = false
+ AND EXISTS (SELECT 1 FROM options o WHERE o.poll_id = p.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM options o
+ WHERE o.poll_id = p.id
+ AND o.start_time + (CASE WHEN o.duration_minutes = 0
+ THEN interval '24 hours'
+ ELSE make_interval(mins => o.duration_minutes) END) > (now() AT TIME ZONE 'UTC')
+ )
+ `;
+
+ return closed;
+}
+
+const REMOVE_DELETED_POLLS_BATCH_SIZE = 100;
+
+/**
+ * Remove polls and corresponding data that have been marked deleted for more than 7 days.
+ */
+export async function removeDeletedPolls() {
+ // First get the ids of all the polls that have been marked as deleted for at least 7 days
+ let totalDeletedPolls = 0;
+ let hasMore = true;
+
+ const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
+
+ while (hasMore) {
+ const batch = await prisma.poll.findMany({
+ where: {
+ deleted: true,
+ deletedAt: {
+ lt: sevenDaysAgo,
+ },
+ },
+ select: { id: true },
+ take: REMOVE_DELETED_POLLS_BATCH_SIZE,
+ });
+
+ if (batch.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const deleted = await prisma.poll.deleteMany({
+ where: {
+ id: { in: batch.map((poll) => poll.id) },
+ },
+ });
+
+ totalDeletedPolls += deleted.count;
+ }
+
+ return totalDeletedPolls;
+}
diff --git a/packages/database/prisma/migrations/20260710120000_add_license_idempotency_key/migration.sql b/packages/database/prisma/migrations/20260710120000_add_license_idempotency_key/migration.sql
new file mode 100644
index 000000000..eafead1da
--- /dev/null
+++ b/packages/database/prisma/migrations/20260710120000_add_license_idempotency_key/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "licenses" ADD COLUMN "idempotency_key" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "licenses_idempotency_key_key" ON "licenses"("idempotency_key");
diff --git a/packages/database/prisma/models/licensing.prisma b/packages/database/prisma/models/licensing.prisma
index ef781f54b..95245f090 100644
--- a/packages/database/prisma/models/licensing.prisma
+++ b/packages/database/prisma/models/licensing.prisma
@@ -12,6 +12,7 @@ enum LicenseStatus {
model License {
id String @id @default(cuid())
licenseKey String @unique @map("license_key")
+ idempotencyKey String? @unique @map("idempotency_key")
version Int? @map("version")
type LicenseType
seats Int? @map("seats")