Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: update pause coupon workflow
Marc Seitz71c622ed1b51
diff --git a/components/billing/upgrade-plan-container.tsx b/components/billing/upgrade-plan-container.tsxindex 656c3d7e..089add8d 100644--- a/components/billing/upgrade-plan-container.tsx+++ b/components/billing/upgrade-plan-container.tsx@@ -5,7 +5,12 @@ import { useState } from "react";import { useTeam } from "@/context/team-context";import { CancellationModal } from "@/ee/features/billing/cancellation/components";import { PlanEnum } from "@/ee/stripe/constants";-import { CreditCardIcon, MoreVertical, ReceiptTextIcon } from "lucide-react";+import {+ CirclePauseIcon,+ CreditCardIcon,+ MoreVertical,+ ReceiptTextIcon,+} from "lucide-react";import { toast } from "sonner";import { mutate } from "swr";@@ -45,6 +50,7 @@ export default function UpgradePlanContainer() {isCustomer,startsAt,endsAt,+ pauseStartsAt,discount,mutate: mutatePlan,} = usePlan({ withDiscount: true });@@ -310,13 +316,15 @@ export default function UpgradePlanContainer() {</span></CardDescription>)}- {isPaused && endsAt && (+ {isPaused && pauseStartsAt && (<CardDescription><span className="font-medium text-foreground">- Subscription will pause on:{" "}+ Subscription{" "}+ {pauseStartsAt > new Date() ? "will pause on" : "paused on"}+ :{" "}</span><span className="text-foreground">- {new Date(endsAt).toLocaleDateString("en-US", {+ {new Date(pauseStartsAt).toLocaleDateString("en-US", {month: "short",day: "numeric",year: "numeric",diff --git a/ee/features/billing/cancellation/api/automatic-unpause-route.ts b/ee/features/billing/cancellation/api/automatic-unpause-route.tsnew file mode 100644index 00000000..afb8d898--- /dev/null+++ b/ee/features/billing/cancellation/api/automatic-unpause-route.ts@@ -0,0 +1,156 @@+import { NextApiRequest, NextApiResponse } from "next";++import { stripeInstance } from "@/ee/stripe";+import { isOldAccount } from "@/ee/stripe/utils";+import { waitUntil } from "@vercel/functions";++import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";++export const config = {+ // in order to enable `waitUntil` function+ supportsResponseStreaming: true,+};++export async function handleRoute(req: NextApiRequest, res: NextApiResponse) {+ if (req.method !== "POST") {+ res.setHeader("Allow", ["POST"]);+ res.status(405).end(`Method ${req.method} Not Allowed`);+ return;+ }++ // Extract the API Key from the Authorization header+ const authHeader = req.headers.authorization;+ const token = authHeader?.split(" ")[1]; // Assuming the format is "Bearer [token]"++ // Check if the API Key matches+ if (token !== process.env.INTERNAL_API_KEY) {+ res.status(401).json({ message: "Unauthorized" });+ return;+ }++ const { teamId } = req.body;++ if (!teamId) {+ return res.status(400).json({ error: "teamId is required" });+ }++ try {+ // Get team details and verify it's still paused+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ },+ select: {+ id: true,+ name: true,+ plan: true,+ subscriptionId: true,+ pauseStartsAt: true,+ pauseEndsAt: true,+ pausedAt: true,+ },+ });++ if (!team) {+ return res.status(404).json({ error: "Team not found" });+ }++ // Check if team is still paused+ if (!team.pausedAt || !team.pauseStartsAt || !team.pauseEndsAt) {+ return res.status(400).json({+ error: "Team is no longer paused",+ teamId,+ pausedAt: team.pausedAt,+ pauseStartsAt: team.pauseStartsAt,+ pauseEndsAt: team.pauseEndsAt,+ });+ }++ // Check if we're past the pause end date+ const now = new Date();+ if (now < team.pauseEndsAt) {+ return res.status(400).json({+ error: "Pause period has not ended yet",+ teamId,+ pauseEndsAt: team.pauseEndsAt,+ currentTime: now,+ });+ }++ if (!team.subscriptionId) {+ return res.status(400).json({+ error: "No subscription ID found",+ teamId,+ });+ }++ // Perform the automatic unpause+ const isOld = isOldAccount(team.plan);+ const stripe = stripeInstance(isOld);++ // First, check the subscription to determine if it was paused with old method or new method+ const subscription = await stripe.subscriptions.retrieve(+ team.subscriptionId,+ );++ // Check if this subscription was paused using the old pause_collection method+ const isOldPauseMethod = subscription.pause_collection !== null;++ if (isOldPauseMethod) {+ // Handle old pause_collection method+ // For automatic unpause (3 months passed), we always want to reset billing cycle+ await stripe.subscriptions.update(team.subscriptionId, {+ pause_collection: "", // Remove pause_collection (unpause)+ });+ } else {+ // Handle new coupon-based method+ // Since 3 months have passed, we definitely need to reset the billing cycle+ // Need to do this in two steps to avoid Stripe proration calculation issues++ // Step 1: Remove the discount first+ await stripe.subscriptions.deleteDiscount(team.subscriptionId);++ // Step 2: Reset billing cycle to charge immediately (now that discount is removed)+ await stripe.subscriptions.update(team.subscriptionId, {+ proration_behavior: "create_prorations", // Create prorations for immediate billing+ billing_cycle_anchor: "now", // Reset billing cycle to start immediately+ });+ }++ // Update database to clear pause status+ await prisma.team.update({+ where: { id: teamId },+ data: {+ pausedAt: null,+ pauseStartsAt: null,+ pauseEndsAt: null,+ },+ });++ waitUntil(+ log({+ message: `Team ${teamId} (${team.plan}) automatically unpaused after 3-month pause period ended using ${isOldPauseMethod ? "pause_collection method" : "coupon method"}.`,+ type: "info",+ }),+ );++ return res.status(200).json({+ success: true,+ message: "Subscription automatically unpaused successfully",+ teamId,+ teamName: team.name,+ });+ } catch (error) {+ console.error("Error automatically unpausing subscription:", error);+ await log({+ message: `Error automatically unpausing subscription for team ${teamId}: ${error}`,+ type: "error",+ });++ return res.status(500).json({+ error: "Failed to automatically unpause subscription",+ teamId,+ });+ }+}diff --git a/ee/features/billing/cancellation/api/pause-route.ts b/ee/features/billing/cancellation/api/pause-route.tsindex d361bf48..67f04ba3 100644--- a/ee/features/billing/cancellation/api/pause-route.ts+++ b/ee/features/billing/cancellation/api/pause-route.ts@@ -1,6 +1,8 @@import { NextApiRequest, NextApiResponse } from "next";+import { PAUSE_COUPON_ID } from "@/ee/features/billing/cancellation/constants";import { sendPauseResumeNotificationTask } from "@/ee/features/billing/cancellation/lib/trigger/pause-resume-notification";+import { automaticUnpauseTask } from "@/ee/features/billing/cancellation/lib/trigger/unpause-task";import { stripeInstance } from "@/ee/stripe";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { waitUntil } from "@vercel/functions";@@ -70,15 +72,23 @@ export async function handleRoute(req: NextApiRequest, res: NextApiResponse) {// Pause the subscription in Stripeawait stripe.subscriptions.update(team.subscriptionId, {- pause_collection: {- behavior: "mark_uncollectible",- resumes_at: Math.floor(pauseEndsAt.getTime() / 1000), // seconds (int)- },+ discounts: [+ {+ coupon:+ PAUSE_COUPON_ID[isOldAccount ? "old" : "new"][+ process.env.VERCEL_ENV === "production" ? "prod" : "test"+ ],+ },+ ],metadata: {pause_starts_at: pauseStartsAt.toISOString(),pause_ends_at: pauseEndsAt.toISOString(),paused_reason: "user_request",original_plan: team.plan,+ pause_coupon_id:+ PAUSE_COUPON_ID[isOldAccount ? "old" : "new"][+ process.env.VERCEL_ENV === "production" ? "prod" : "test"+ ],},});@@ -102,8 +112,16 @@ export async function handleRoute(req: NextApiRequest, res: NextApiResponse) {idempotencyKey: `pause-resume-${teamId}-${new Date().getTime()}`,},),- // Remove the existing discounts from the subscription- stripe.subscriptions.deleteDiscount(team.subscriptionId),+ // Schedule automatic unpause when the 3-month pause period ends+ automaticUnpauseTask.trigger(+ { teamId },+ {+ delay: pauseEndsAt, // Exactly when pause period ends+ tags: [`team_${teamId}`],+ idempotencyKey: `automatic-unpause-${teamId}-${new Date().getTime()}`,+ },+ ),+log({message: `Team ${teamId} (${team.plan}) paused their subscription for 3 months.`,type: "info",diff --git a/ee/features/billing/cancellation/api/unpause-route.ts b/ee/features/billing/cancellation/api/unpause-route.tsindex 6c43b01d..d18d90e8 100644--- a/ee/features/billing/cancellation/api/unpause-route.ts+++ b/ee/features/billing/cancellation/api/unpause-route.ts@@ -67,10 +67,41 @@ export async function handleRoute(req: NextApiRequest, res: NextApiResponse) {const isOldAccount = team.plan.includes("+old");const stripe = stripeInstance(isOldAccount);- // Unpause the subscription in Stripe- await stripe.subscriptions.update(team.subscriptionId, {- pause_collection: "",- });+ // First, check the subscription to determine if it was paused with old method or new method+ const subscription = await stripe.subscriptions.retrieve(+ team.subscriptionId,+ );++ const now = new Date();+ const originalPauseStart = team.pauseStartsAt;++ // Determine if we're still in the original billing cycle or have moved to the next one+ const isInOriginalBillingCycle = now <= originalPauseStart;++ // Check if this subscription was paused using the old pause_collection method+ const isOldPauseMethod = subscription.pause_collection !== null;++ if (isOldPauseMethod) {+ // Handle old pause_collection method+ await stripe.subscriptions.update(team.subscriptionId, {+ pause_collection: "", // Remove pause_collection (unpause)+ });+ } else {+ // Handle new coupon-based method+ if (isInOriginalBillingCycle) {+ // Scenario 1: Still within the original billing cycle where user paused+ // Just remove the coupon, no billing cycle reset needed+ await stripe.subscriptions.deleteDiscount(team.subscriptionId);+ } else {+ // Scenario 2: We're already in the next billing cycle (or beyond)+ // Remove coupon and reset billing cycle to charge immediately+ await stripe.subscriptions.deleteDiscount(team.subscriptionId);+ await stripe.subscriptions.update(team.subscriptionId, {+ proration_behavior: "create_prorations", // Create prorations for immediate billing+ billing_cycle_anchor: "now", // Reset billing cycle to start immediately+ });+ }+ }await prisma.team.update({where: { id: teamId },@@ -81,20 +112,23 @@ export async function handleRoute(req: NextApiRequest, res: NextApiResponse) {},});- // Get all delayed and queued runs for this dataroom+ // Get all delayed and queued runs for this team (both notification and automatic unpause)const allRuns = await runs.list({- taskIdentifier: ["send-pause-resume-notification"],+ taskIdentifier: [+ "send-pause-resume-notification",+ "automatic-unpause-subscription",+ ],tag: [`team_${teamId}`],status: ["DELAYED", "QUEUED"],period: "90d",});- // Cancel any existing unsent notification runs for this dataroom+ // Cancel any existing unsent notification and automatic unpause runswaitUntil(Promise.all([allRuns.data.map((run) => runs.cancel(run.id)),log({- message: `Team ${teamId} (${team.plan}) unpaused their subscription. Next billing date: ${team.endsAt}`,+ message: `Team ${teamId} (${team.plan}) manually unpaused their subscription using ${isOldPauseMethod ? "pause_collection method" : "coupon method"}${!isOldPauseMethod && hasDiscountCoupon ? (isInOriginalBillingCycle ? " within original billing cycle" : " with billing cycle reset") : ""}.`,type: "info",}),]),diff --git a/ee/features/billing/cancellation/constants.ts b/ee/features/billing/cancellation/constants.tsnew file mode 100644index 00000000..10ef3913--- /dev/null+++ b/ee/features/billing/cancellation/constants.ts@@ -0,0 +1,4 @@+export const PAUSE_COUPON_ID = {+ old: { prod: "V1uIzDQU", test: "3Fs2L1Tq" },+ new: { prod: "V1uIzDQU", test: "3Fs2L1Tq" },+};diff --git a/ee/features/billing/cancellation/lib/trigger/unpause-task.ts b/ee/features/billing/cancellation/lib/trigger/unpause-task.tsnew file mode 100644index 00000000..04c1d4c0--- /dev/null+++ b/ee/features/billing/cancellation/lib/trigger/unpause-task.ts@@ -0,0 +1,70 @@+import { logger, task } from "@trigger.dev/sdk/v3";++export const automaticUnpauseTask = task({+ id: "automatic-unpause-subscription",+ retry: { maxAttempts: 3 },+ run: async (payload: { teamId: string }) => {+ logger.info("Starting automatic unpause", {+ teamId: payload.teamId,+ });++ const internalApiKey = process.env.INTERNAL_API_KEY;+ if (!internalApiKey) {+ logger.error("INTERNAL_API_KEY environment variable not set");+ throw new Error("Internal API key not configured");+ }++ try {+ // Call the internal API endpoint to perform the automatic unpause+ const response = await fetch(+ `${process.env.NEXTAUTH_URL}/api/internal/billing/automatic-unpause`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${internalApiKey}`,+ },+ body: JSON.stringify({+ teamId: payload.teamId,+ }),+ },+ );++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ logger.error("Internal API call failed", {+ teamId: payload.teamId,+ status: response.status,+ statusText: response.statusText,+ errorData,+ });++ // Don't retry if it's a client error (4xx) - these are usually permanent+ if (response.status >= 400 && response.status < 500) {+ logger.info("Skipping retry for client error", {+ teamId: payload.teamId,+ status: response.status,+ });+ return;+ }++ throw new Error(+ `Internal API call failed: ${response.status} ${response.statusText}`,+ );+ }++ const result = await response.json();+ logger.info("Successfully automatically unpaused subscription", {+ teamId: payload.teamId,+ teamName: result.teamName,+ });+ } catch (error) {+ logger.error("Failed to automatically unpause subscription", {+ teamId: payload.teamId,+ error: error instanceof Error ? error.message : String(error),+ });++ throw error; // Re-throw to trigger retry+ }+ },+});diff --git a/package-lock.json b/package-lock.jsonindex c31e4936..196d3e79 100644--- a/package-lock.json+++ b/package-lock.json@@ -17544,6 +17544,21 @@"type": "github","url": "https://github.com/sponsors/wooorm"}+ },+ "node_modules/react-email/node_modules/@next/swc-win32-ia32-msvc": {+ "version": "14.2.32",+ "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.32.tgz",+ "integrity": "sha512-jHUeDPVHrgFltqoAqDB6g6OStNnFxnc7Aks3p0KE0FbwAvRg6qWKYF5mSTdCTxA3axoSAUwxYdILzXJfUwlHhA==",+ "cpu": [+ "ia32"+ ],+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }}}}diff --git a/pages/api/internal/billing/automatic-unpause.ts b/pages/api/internal/billing/automatic-unpause.tsnew file mode 100644index 00000000..f4b028f4--- /dev/null+++ b/pages/api/internal/billing/automatic-unpause.ts@@ -0,0 +1,15 @@+import { NextApiRequest, NextApiResponse } from "next";++import { handleRoute } from "@/ee/features/billing/cancellation/api/automatic-unpause-route";++export const config = {+ // in order to enable `waitUntil` function+ supportsResponseStreaming: true,+};++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ return handleRoute(req, res);+}diff --git a/pages/api/teams/[teamId]/billing/plan.ts b/pages/api/teams/[teamId]/billing/plan.tsindex eba540e6..62817e87 100644--- a/pages/api/teams/[teamId]/billing/plan.ts+++ b/pages/api/teams/[teamId]/billing/plan.ts@@ -71,7 +71,8 @@ export default async function handle(withDiscount &&team?.subscriptionId &&team.plan &&- team.plan !== "free"+ team.plan !== "free" &&+ team.pauseStartsAt === null) {try {const subscriptionData = await getSubscriptionItem(