Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Free Trial (#3644)

Pedro Ladeira9ccba8cc9fd7
diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml
index 14148a72a7..c274aa3074 100644
--- a/.github/workflows/e2e.yaml
+++ b/.github/workflows/e2e.yaml
@@ -39,4 +39,5 @@ jobs:
QSTASH_TOKEN: ${{ secrets.QSTASH_TOKEN }}
QSTASH_CURRENT_SIGNING_KEY: ${{ secrets.QSTASH_CURRENT_SIGNING_KEY }}
NEXT_PUBLIC_NGROK_URL: ${{ github.event.deployment_status.environment_url }}
+ UNSUBSCRIBE_TOKEN_SECRET: "dummy-secret"
run: pnpm test
diff --git a/apps/web/app/(ee)/api/cron/trial-emails/route.ts b/apps/web/app/(ee)/api/cron/trial-emails/route.ts
new file mode 100644
index 0000000000..6d85472c1e
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/trial-emails/route.ts
@@ -0,0 +1,63 @@
+import { qstash } from "@/lib/cron";
+import { withCron } from "@/lib/cron/with-cron";
+import { runTrialEmailCron } from "@/lib/email/run-trial-email-cron";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import * as z from "zod/v4";
+import { logAndRespond } from "../utils";
+
+export const dynamic = "force-dynamic";
+
+const postBodySchema = z.object({
+ startingAfter: z.string(),
+});
+
+/**
+ * Sends the paid-plan trial marketing sequence (see `lib/email/trial-email-schedule.ts`).
+ * Runs on a schedule (cron). Eligibility is `trialEndsAt` in the future + `SentEmail` dedupe.
+ *
+ * Complements the generic welcome email (`/api/cron/welcome-user`): free-only signups get welcome only;
+ * users who start a trial get welcome (QStash) + these emails when due.
+ */
+
+async function executeTrialEmailCronBatch(startingAfter?: string) {
+ const now = new Date();
+ const result = await runTrialEmailCron({
+ now,
+ prisma,
+ startingAfter,
+ });
+
+ if (result.workspaceCount === 0) {
+ if (startingAfter) {
+ return logAndRespond(
+ "Trial email cron: no workspaces on next batch (done).",
+ );
+ }
+
+ return logAndRespond("No workspaces in active trial. Skipping.");
+ }
+
+ if (result.hasMore && result.nextStartingAfter) {
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/trial-emails`,
+ method: "POST",
+ body: {
+ startingAfter: result.nextStartingAfter,
+ },
+ });
+ }
+
+ return logAndRespond(
+ `Trial email cron: sent ${result.sentCount} email(s) for ${result.workspaceCount} workspace(s)${result.hasMore ? "; next batch enqueued." : "."}`,
+ );
+}
+
+// GET /api/cron/trial-emails
+export const GET = withCron(async () => executeTrialEmailCronBatch(undefined));
+
+// POST /api/cron/trial-emails (recursively called by QStash)
+export const POST = withCron(async ({ rawBody }) => {
+ const { startingAfter } = postBodySchema.parse(JSON.parse(rawBody));
+ return await executeTrialEmailCronBatch(startingAfter);
+});
diff --git a/apps/web/app/(ee)/api/cron/welcome-user/route.ts b/apps/web/app/(ee)/api/cron/welcome-user/route.ts
index 794d2e1494..30bf7287a6 100644
--- a/apps/web/app/(ee)/api/cron/welcome-user/route.ts
+++ b/apps/web/app/(ee)/api/cron/welcome-user/route.ts
@@ -1,7 +1,6 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { generateUnsubscribeToken } from "@/lib/email/unsubscribe-token";
-import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { sendEmail } from "@dub/email";
import WelcomeEmail from "@dub/email/templates/welcome-email";
import WelcomeEmailPartner from "@dub/email/templates/welcome-email-partner";
@@ -13,6 +12,9 @@ export const dynamic = "force-dynamic";
/*
This route is used to send a welcome email to new users + subscribe them to the corresponding Resend audience
It is called by QStash 45 minutes after a user is created.
+
+ Trial sequence: users who later start a paid-plan trial also receive marketing emails from
+ `/api/cron/trial-emails` when due; that flow is additive (this welcome is not skipped).
*/
export async function POST(req: Request) {
try {
@@ -29,7 +31,6 @@ export async function POST(req: Request) {
name: true,
email: true,
partners: true,
-
projects: {
select: {
project: {
@@ -38,17 +39,8 @@ export async function POST(req: Request) {
name: true,
logo: true,
plan: true,
- programs: {
- select: {
- slug: true,
- name: true,
- logo: true,
- },
- orderBy: {
- createdAt: "desc",
- },
- take: 1,
- },
+ trialEndsAt: true,
+ defaultProgramId: true,
},
},
},
@@ -73,29 +65,39 @@ export async function POST(req: Request) {
const unsubscribeUrl = `${isPartner ? PARTNERS_DOMAIN : APP_DOMAIN}/unsubscribe/${generateUnsubscribeToken(user.email)}`;
- await Promise.allSettled([
- sendEmail({
+ if (isPartner) {
+ await sendEmail({
+ to: user.email,
+ replyTo: "noreply",
+ subject: "Welcome to Dub Partners!",
+ react: WelcomeEmailPartner({
+ email: user.email,
+ name: user.name,
+ unsubscribeUrl,
+ }),
+ variant: "marketing",
+ });
+
+ // only send WelcomeEmail if the user has a workspace that:
+ // - is not in a trial
+ // - hasn't created a program yet
+ } else if (
+ user.projects.length > 0 &&
+ user.projects[0].project.trialEndsAt === null &&
+ user.projects[0].project.defaultProgramId === null
+ ) {
+ await sendEmail({
to: user.email,
- replyTo: isPartner ? "noreply" : "[email protected]",
- subject: `Welcome to Dub${isPartner ? " Partners" : ""}!`,
- react: isPartner
- ? WelcomeEmailPartner({
- email: user.email,
- name: user.name,
- unsubscribeUrl,
- })
- : WelcomeEmail({
- email: user.email,
- workspace: user.projects?.[0]?.project,
- hasDubPartners: getPlanCapabilities(
- user.projects?.[0]?.project?.plan || "free",
- ).canManageProgram,
- program: user.projects?.[0]?.project?.programs?.[0],
- unsubscribeUrl,
- }),
+ replyTo: "[email protected]",
+ subject: "Welcome to Dub!",
+ react: WelcomeEmail({
+ email: user.email,
+ workspace: user.projects[0].project,
+ unsubscribeUrl,
+ }),
variant: "marketing",
- }),
- ]);
+ });
+ }
return new Response("Welcome email sent and user subscribed.", {
status: 200,
diff --git a/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts
index a427a43c91..22d056f7ed 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts
@@ -8,22 +8,37 @@ import { stripe } from "@/lib/stripe";
import { WorkspaceProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendBatchEmail } from "@dub/email";
+import TrialStartedEmail from "@dub/email/templates/trial/trial-started";
import UpgradeEmail from "@dub/email/templates/upgrade-email";
import { prisma } from "@dub/prisma";
import { Program, User } from "@dub/prisma/client";
-import { getPlanAndTierFromPriceId, log, prettyPrint } from "@dub/utils";
+import {
+ getPlanAndTierFromPriceId,
+ getWorkspaceLimitsForStripeSubscriptionStatus,
+ isWorkspaceBillingTrialActive,
+ log,
+} from "@dub/utils";
import Stripe from "stripe";
+import { getPlanPeriodFromStripeSubscription } from "./utils/stripe-plan-period";
export async function checkoutSessionCompleted(
event: Stripe.CheckoutSessionCompletedEvent,
) {
const checkoutSession = event.data.object;
- if (
- checkoutSession.mode === "setup" ||
- checkoutSession.payment_status !== "paid"
- ) {
- return "Session is setup mode or not paid, skipping...";
+ if (checkoutSession.mode === "setup") {
+ return "Session is setup mode, skipping...";
+ }
+
+ if (checkoutSession.mode === "subscription") {
+ if (
+ checkoutSession.payment_status !== "paid" &&
+ checkoutSession.payment_status !== "no_payment_required"
+ ) {
+ return "Subscription checkout session not completed (payment status), skipping...";
+ }
+ } else {
+ return `Session mode ${checkoutSession.mode} is not handled here, skipping...`;
}
if (
@@ -48,9 +63,20 @@ export async function checkoutSessionCompleted(
return `Invalid price ID in checkout.session.completed event: ${priceId}`;
}
+ const limits = getWorkspaceLimitsForStripeSubscriptionStatus({
+ planLimits: plan.limits,
+ subscriptionStatus: subscription.status,
+ });
+
+ const trialEndsAt =
+ subscription.status === "trialing" && subscription.trial_end
+ ? new Date(subscription.trial_end * 1000)
+ : null;
+
const stripeId = checkoutSession.customer.toString();
const workspaceId = checkoutSession.client_reference_id;
const planName = plan.name.toLowerCase();
+ const planPeriod = getPlanPeriodFromStripeSubscription(subscription);
// when the workspace subscribes to a plan, set their stripe customer ID
// in the database for easy identification in future webhook events
@@ -65,22 +91,28 @@ export async function checkoutSessionCompleted(
billingCycleStart: new Date().getDate(),
plan: planName,
planTier: planTier,
- usageLimit: plan.limits.clicks,
- linksLimit: plan.limits.links,
- payoutsLimit: plan.limits.payouts,
- domainsLimit: plan.limits.domains,
- aiLimit: plan.limits.ai,
- tagsLimit: plan.limits.tags,
- foldersLimit: plan.limits.folders,
- groupsLimit: plan.limits.groups,
- networkInvitesLimit: plan.limits.networkInvites,
- usersLimit: plan.limits.users,
+ usageLimit: limits.clicks,
+ linksLimit: limits.links,
+ payoutsLimit: limits.payouts,
+ domainsLimit: limits.domains,
+ aiLimit: limits.ai,
+ tagsLimit: limits.tags,
+ foldersLimit: limits.folders,
+ groupsLimit: limits.groups,
+ networkInvitesLimit: limits.networkInvites,
+ usersLimit: limits.users,
+ trialEndsAt,
paymentFailedAt: null,
+ ...(planPeriod !== undefined && { planPeriod }),
},
- select: {
- plan: true,
- defaultProgramId: true,
+ include: {
users: {
+ where: {
+ role: "owner",
+ user: {
+ isMachine: false,
+ },
+ },
select: {
user: {
select: {
@@ -90,11 +122,6 @@ export async function checkoutSessionCompleted(
},
},
},
- where: {
- user: {
- isMachine: false,
- },
- },
},
restrictedTokens: {
select: {
@@ -119,20 +146,41 @@ export async function checkoutSessionCompleted(
newPlan: updatedWorkspace.plan,
}) &&
reactivateProgram(updatedWorkspace.defaultProgramId),
- sendBatchEmail(
- users.map((user) => ({
- to: user.email as string,
- replyTo: "[email protected]",
- subject: `Thank you for upgrading to Dub ${plan.name}!`,
- react: UpgradeEmail({
- name: user.name,
- email: user.email as string,
- plan: plan.name,
- planTier: planTier,
- }),
- variant: "marketing",
- })),
- ),
+ // If trial + no program (Links trial), send TrialStartedEmail – for program trial we send it in create-program.ts
+ // else, we send Upgrade thank you email
+ // TODO: Only send TrialStartedEmail once we remove the trial feature flag
+ isWorkspaceBillingTrialActive(trialEndsAt) &&
+ !updatedWorkspace.store?.["programOnboarding"]
+ ? sendBatchEmail(
+ users.map((user) => ({
+ to: user.email as string,
+ replyTo: "[email protected]",
+ subject: "Welcome to your 14-day Dub trial",
+ react: TrialStartedEmail({
+ email: user.email as string,
+ plan: plan.name,
+ workspace: {
+ slug: updatedWorkspace.slug,
+ logo: updatedWorkspace.logo,
+ name: updatedWorkspace.name,
+ },
+ }),
+ variant: "marketing",
+ })),
+ )
+ : sendBatchEmail(
+ users.map((user) => ({
+ to: user.email as string,
+ replyTo: "[email protected]",
+ subject: `Thank you for upgrading to Dub ${plan.name}!`,
+ react: UpgradeEmail({
+ name: user.name,
+ email: user.email as string,
+ plan: plan.name,
+ }),
+ variant: "marketing",
+ })),
+ ),
// expire tokens cache
tokenCache.expireMany({
hashedKeys: updatedWorkspace.restrictedTokens.map(
@@ -162,60 +210,53 @@ async function completeOnboarding({
})) as unknown as (WorkspaceProps & { programs: Program[] }) | null;
if (!workspace) {
- console.error("Failed to complete onboarding for workspace", workspaceId);
+ console.error(
+ "Failed to find workspace in completeOnboarding",
+ workspaceId,
+ );
return;
}
await Promise.allSettled([
- // Complete onboarding for workspace users
onboardingStepCache.mset({
userIds: users.map(({ id }) => id),
step: "completed",
}),
- (async () => {
- // Register saved domain
- const data = await redis.get<{ domain: string; userId: string }>(
- `onboarding-domain:${workspaceId}`,
- );
- if (data && data.domain && data.userId) {
- const { domain, userId } = data;
+ // Create program based on programOnboarding data
+ users.length > 0 &&
+ workspace.programs.length === 0 &&
+ workspace.store?.programOnboarding &&
+ createProgram({
+ workspace,
+ user: users[0],
+ }).catch((error) => {
+ console.error("Failed to create program in completeOnboarding", error);
+ return;
+ }),
+
+ // Claim saved domain (only if not on trial)
+ !isWorkspaceBillingTrialActive(workspace.trialEndsAt) &&
+ (async () => {
+ // Register saved domain
+ const data = await redis.get<{ domain: string; userId: string }>(
+ `onboarding-domain:${workspaceId}`,
+ );
+ if (data && data.domain && data.userId) {
+ const { domain, userId } = data;
- try {
await claimDotLinkDomain({
domain,
userId,
workspace,
+ }).catch((error) => {
+ console.error(
+ "Failed to claim saved domain in completeOnboarding",
+ error,
+ );
+ return;
});
- await redis.del(`onboarding-domain:${workspaceId}`);
- } catch (e) {
- console.error(
- "Failed to register saved domain from onboarding",
- { domain, userId, workspace },
- e,
- );
- }
- }
-
- // Create program
- if (
- users.length > 0 &&
- workspace.programs.length === 0 &&
- workspace.store?.programOnboarding
- ) {
- try {
- await createProgram({
- workspace,
- user: users[0],
- });
- } catch (e) {
- console.error(
- "Failed to create program from onboarding",
- prettyPrint({ workspace, user: users[0] }),
- e,
- );
}
- }
- })(),
+ })(),
]);
}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts
index dbfa3ae87a..17fcfd5ccb 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts
@@ -1,13 +1,18 @@
+import { pauseOrCancelCampaignsForProgramOnPlanDowngrade } from "@/lib/api/campaigns/pause-campaigns-on-plan-downgrade";
import { deleteWorkspaceFolders } from "@/lib/api/folders/delete-workspace-folders";
import { linkCache } from "@/lib/api/links/cache";
import { includeProgramEnrollment } from "@/lib/api/links/include-program-enrollment";
import { includeTags } from "@/lib/api/links/include-tags";
+import { stripAdvancedRewardModifiersForProgram } from "@/lib/api/partners/strip-advanced-reward-modifiers";
import { deactivateProgram } from "@/lib/api/programs/deactivate-program";
import { tokenCache } from "@/lib/auth/token-cache";
import { isBlacklistedEmail } from "@/lib/edge-config/is-blacklisted-email";
+import { wouldLoseAdvancedFeatures } from "@/lib/plans/would-lose-advanced-features";
import { stripe } from "@/lib/stripe";
import { recordLink } from "@/lib/tinybird";
import { webhookCache } from "@/lib/webhook/cache";
+import { sendEmail } from "@dub/email";
+import AdvancedPlanDowngradeNotice from "@dub/email/templates/advanced-plan-downgrade-notice";
import { prisma } from "@dub/prisma";
import { capitalize, FREE_PLAN, log } from "@dub/utils";
import Stripe from "stripe";
@@ -27,15 +32,7 @@ export async function customerSubscriptionDeleted(
where: {
stripeId,
},
- select: {
- id: true,
- slug: true,
- plan: true,
- planTier: true,
- foldersUsage: true,
- paymentFailedAt: true,
- payoutsLimit: true,
- defaultProgramId: true,
+ include: {
links: {
where: {
key: "_root",
@@ -73,22 +70,32 @@ export async function customerSubscriptionDeleted(
return `Workspace with Stripe ID ${stripeId} not found in customer.subscription.deleted callback.`;
}
- // Check if the customer has another active subscription
- const { data: activeSubscriptions } = await stripe.subscriptions.list({
- customer: stripeId,
- status: "active",
- });
+ // Check if the customer has another subscription still in force (active or trialing)
+ const [{ data: activeSubscriptions }, { data: trialingSubscriptions }] =
+ await Promise.all([
+ stripe.subscriptions.list({
+ customer: stripeId,
+ status: "active",
+ }),
+ stripe.subscriptions.list({
+ customer: stripeId,
+ status: "trialing",
+ }),
+ ]);
+
+ const fallbackSubscription =
+ activeSubscriptions[0] ?? trialingSubscriptions[0];
- if (activeSubscriptions.length > 0) {
- const activeSubscription = activeSubscriptions[0];
- const priceId = activeSubscription.items.data[0].price.id;
+ if (fallbackSubscription) {
+ const priceId = fallbackSubscription.items.data[0].price.id;
await updateWorkspacePlan({
workspace,
priceId,
+ subscription: fallbackSubscription,
});
- return `Workspace ${workspace.slug} has another active subscription; updated plan.`;
+ return `Workspace ${workspace.slug} has another subscription; updated plan.`;
}
const workspaceLinks = workspace.links;
@@ -98,26 +105,33 @@ export async function customerSubscriptionDeleted(
workspaceUsers.filter(({ email }) => email).map(({ email }) => email!),
);
+ await prisma.project.update({
+ where: {
+ stripeId,
+ },
+ data: {
+ plan: "free",
+ trialEndsAt: null,
+ planPeriod: null,
+ billingCycleEndsAt: null,
+ subscriptionCanceledAt: workspace.subscriptionCanceledAt
+ ? undefined // skip updating subscriptionCanceledAt if it's already set
+ : new Date(),
+ usageLimit: FREE_PLAN.limits.clicks!,
+ linksLimit: FREE_PLAN.limits.links!,
+ payoutsLimit: FREE_PLAN.limits.payouts!,
+ domainsLimit: FREE_PLAN.limits.domains!,
+ aiLimit: FREE_PLAN.limits.ai!,
+ tagsLimit: FREE_PLAN.limits.tags!,
+ foldersLimit: FREE_PLAN.limits.folders!,
+ groupsLimit: FREE_PLAN.limits.groups!,
+ networkInvitesLimit: FREE_PLAN.limits.networkInvites!,
+ usersLimit: FREE_PLAN.limits.users!,
+ paymentFailedAt: null,
+ },
+ });
+
await Promise.allSettled([
- prisma.project.update({
- where: {
- stripeId,
- },
- data: {
- plan: "free",
- usageLimit: FREE_PLAN.limits.clicks!,
- linksLimit: FREE_PLAN.limits.links!,
- payoutsLimit: FREE_PLAN.limits.payouts!,
- domainsLimit: FREE_PLAN.limits.domains!,
- aiLimit: FREE_PLAN.limits.ai!,
- tagsLimit: FREE_PLAN.limits.tags!,
- foldersLimit: FREE_PLAN.limits.folders!,
- groupsLimit: FREE_PLAN.limits.groups!,
- networkInvitesLimit: FREE_PLAN.limits.networkInvites!,
- usersLimit: FREE_PLAN.limits.users!,
- paymentFailedAt: null,
- },
- }),
// remove logo from all domains for the workspace
prisma.domain.updateMany({
where: {
@@ -220,5 +234,40 @@ export async function customerSubscriptionDeleted(
await deactivateProgram(workspace.defaultProgramId);
}
+ const losesAdvancedFeatures = wouldLoseAdvancedFeatures({
+ currentPlan: workspace.plan,
+ newPlan: "free",
+ });
+
+ if (workspace.defaultProgramId && losesAdvancedFeatures) {
+ await Promise.all([
+ stripAdvancedRewardModifiersForProgram({
+ programId: workspace.defaultProgramId,
+ }),
+ pauseOrCancelCampaignsForProgramOnPlanDowngrade({
+ programId: workspace.defaultProgramId,
+ }),
+ ]);
+ }
+
+ const owner = workspaceUsers[0];
+ if (owner.email && losesAdvancedFeatures) {
+ await sendEmail({
+ to: owner.email,
+ subject: "Your Advanced plan features have been removed",
+ react: AdvancedPlanDowngradeNotice({
+ email: owner.email,
+ workspace: {
+ name: workspace.name,
+ slug: workspace.slug,
+ },
+ }),
+ variant: "notifications",
+ headers: {
+ "Idempotency-Key": `advanced-downgrade-notice:${workspace.id}:${owner.email}`,
+ },
+ });
+ }
+
return `Workspace ${workspace.slug} subscription deleted; downgraded to free.`;
}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts
index f6837c0e88..da1c0b73cc 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts
@@ -7,8 +7,8 @@ import { updateWorkspacePlan } from "./utils/update-workspace-plan";
export async function customerSubscriptionUpdated(
event: Stripe.CustomerSubscriptionUpdatedEvent,
) {
- const subscriptionUpdated = event.data.object;
- const priceId = subscriptionUpdated.items.data[0].price.id;
+ const updatedSubscription = event.data.object;
+ const priceId = updatedSubscription.items.data[0].price.id;
const { plan } = getPlanAndTierFromPriceId({ priceId });
@@ -16,20 +16,13 @@ export async function customerSubscriptionUpdated(
return `Invalid price ID in customer.subscription.updated event: ${priceId}`;
}
- const stripeId = subscriptionUpdated.customer.toString();
+ const stripeId = updatedSubscription.customer.toString();
const workspace = await prisma.project.findUnique({
where: {
stripeId,
},
- select: {
- id: true,
- plan: true,
- planTier: true,
- paymentFailedAt: true,
- payoutsLimit: true,
- foldersUsage: true,
- defaultProgramId: true,
+ include: {
users: {
select: {
user: {
@@ -61,22 +54,24 @@ export async function customerSubscriptionUpdated(
await updateWorkspacePlan({
workspace,
priceId,
+ subscription: updatedSubscription,
});
const subscriptionCanceled =
- subscriptionUpdated.status === "active" &&
- subscriptionUpdated.cancel_at_period_end;
+ (updatedSubscription.status === "active" ||
+ updatedSubscription.status === "trialing") &&
+ updatedSubscription.cancel_at_period_end;
if (subscriptionCanceled) {
const owners = workspace.users.map(({ user }) => user);
- const cancelReason = subscriptionUpdated.cancellation_details?.feedback;
+ const cancelReason = updatedSubscription.cancellation_details?.feedback;
await sendCancellationFeedback({
owners,
reason: cancelReason,
});
- return `Updated workspace ${workspace.id} plan; cancellation at period end requested.`;
+ return `Sent cancellation feedback to ${owners.length} workspace owners for workspace ${workspace.slug}.`;
}
- return `Updated workspace ${workspace.id} plan to ${plan.name}.`;
+ return `Processed customer.subscription.updated event for workspace ${workspace.id}.`;
}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/stripe-plan-period.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/stripe-plan-period.ts
new file mode 100644
index 0000000000..9e80cf1f85
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/stripe-plan-period.ts
@@ -0,0 +1,26 @@
+import { PlanPeriod } from "@dub/prisma/client";
+import type Stripe from "stripe";
+
+export function getPlanPeriodFromStripeSubscription(
+ subscription: Stripe.Subscription,
+): PlanPeriod | undefined {
+ const recurring = subscription.items.data[0]?.price?.recurring;
+ if (!recurring) {
+ return undefined;
+ }
+
+ const { interval, interval_count } = recurring;
+ if (interval === "month" && interval_count === 3) {
+ return PlanPeriod.quarterly;
+ }
+ if (interval === "month" && interval_count === 1) {
+ return PlanPeriod.monthly;
+ }
+ if (interval === "year" && interval_count === 1) {
+ return PlanPeriod.yearly;
+ }
+ if (interval === "week" && interval_count === 2) {
+ return PlanPeriod.biweekly;
+ }
+ return undefined;
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts
index 15b12ec9fe..386f3931d0 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts
@@ -1,4 +1,6 @@
+import { pauseOrCancelCampaignsForProgramOnPlanDowngrade } from "@/lib/api/campaigns/pause-campaigns-on-plan-downgrade";
import { deleteWorkspaceFolders } from "@/lib/api/folders/delete-workspace-folders";
+import { stripAdvancedRewardModifiersForProgram } from "@/lib/api/partners/strip-advanced-reward-modifiers";
import { deactivateProgram } from "@/lib/api/programs/deactivate-program";
import { reactivateProgram } from "@/lib/api/programs/reactivate-program";
import { tokenCache } from "@/lib/auth/token-cache";
@@ -8,25 +10,42 @@ import {
wouldGainPartnerAccess,
wouldLosePartnerAccess,
} from "@/lib/plans/has-partner-access";
+import { wouldLoseAdvancedFeatures } from "@/lib/plans/would-lose-advanced-features";
+import {
+ getSubscriptionCancellationFields,
+ getSubscriptionTrialEndsAt,
+} from "@/lib/stripe/workspace-subscription-fields";
import { WorkspaceProps } from "@/lib/types";
import { webhookCache } from "@/lib/webhook/cache";
+import { sendBatchEmail } from "@dub/email";
+import AdvancedPlanDowngradeNotice from "@dub/email/templates/advanced-plan-downgrade-notice";
+import UpgradeEmail from "@dub/email/templates/upgrade-email";
import { prisma } from "@dub/prisma";
-import { getPlanAndTierFromPriceId } from "@dub/utils";
+import {
+ getPlanAndTierFromPriceId,
+ getWorkspaceLimitsForStripeSubscriptionStatus,
+} from "@dub/utils";
import { NEW_BUSINESS_PRICE_IDS } from "@dub/utils/src";
-import { waitUntil } from "@vercel/functions";
+import type Stripe from "stripe";
+import { getPlanPeriodFromStripeSubscription } from "./stripe-plan-period";
export async function updateWorkspacePlan({
workspace,
priceId,
+ subscription,
}: {
workspace: Pick<
WorkspaceProps,
| "id"
+ | "name"
+ | "slug"
+ | "defaultProgramId"
+ | "planPeriod"
| "planTier"
- | "paymentFailedAt"
+ | "trialEndsAt"
+ | "billingCycleEndsAt"
+ | "subscriptionCanceledAt"
| "payoutsLimit"
- | "foldersUsage"
- | "defaultProgramId"
> & {
plan: string;
restrictedTokens: {
@@ -34,6 +53,7 @@ export async function updateWorkspacePlan({
}[];
};
priceId: string;
+ subscription: Stripe.Subscription;
}) {
const { plan: newPlan, planTier: newPlanTier } = getPlanAndTierFromPriceId({
priceId,
@@ -41,17 +61,35 @@ export async function updateWorkspacePlan({
if (!newPlan) return;
const newPlanName = newPlan.name.toLowerCase();
- const shouldDisableWebhooks = newPlanName === "free" || newPlanName === "pro";
- const { canManageProgram, canMessagePartners } =
+ const { canMessagePartners, canCreateWebhooks, canAddFolder } =
getPlanCapabilities(newPlanName);
- // If a workspace upgrades/downgrades their subscription
- // or if the payouts limit increases and the updated price ID is a new business price ID
- // update their usage limit in the database
+ const limits = getWorkspaceLimitsForStripeSubscriptionStatus({
+ planLimits: newPlan.limits,
+ subscriptionStatus: subscription.status,
+ });
+
+ const trialEndsAt = getSubscriptionTrialEndsAt(subscription);
+ const isPaidPlanActivated =
+ workspace.trialEndsAt !== null && trialEndsAt === null;
+ const cancellationFields = getSubscriptionCancellationFields(subscription);
+ const planPeriod = getPlanPeriodFromStripeSubscription(subscription);
+
+ // Update workspace plan / limits / subscription details if:
+ // - workspace upgrades/downgrades their subscription
+ // - workspace changes their plan period / tier
+ // - trialEndsAt changes (i.e. free trial -> paid subscription)
+ // - cancellationFields changes (billingCycleEndsAt or subscriptionCanceledAt)
+ // - the payouts limit increases and the updated price ID is a new business price ID
if (
workspace.plan !== newPlanName ||
+ workspace.planPeriod !== planPeriod ||
workspace.planTier !== newPlanTier ||
+ isPaidPlanActivated ||
+ workspace.billingCycleEndsAt !== cancellationFields.billingCycleEndsAt ||
+ workspace.subscriptionCanceledAt !==
+ cancellationFields.subscriptionCanceledAt ||
(workspace.payoutsLimit < newPlan.limits.payouts &&
NEW_BUSINESS_PRICE_IDS.includes(priceId))
) {
@@ -63,22 +101,30 @@ export async function updateWorkspacePlan({
data: {
plan: newPlanName,
planTier: newPlanTier,
- usageLimit: newPlan.limits.clicks,
- linksLimit: newPlan.limits.links,
- payoutsLimit: newPlan.limits.payouts,
- domainsLimit: newPlan.limits.domains,
- aiLimit: newPlan.limits.ai,
- tagsLimit: newPlan.limits.tags,
- foldersLimit: newPlan.limits.folders,
- groupsLimit: newPlan.limits.groups,
- networkInvitesLimit: newPlan.limits.networkInvites,
- usersLimit: newPlan.limits.users,
- paymentFailedAt: null,
+ usageLimit: limits.clicks,
+ linksLimit: limits.links,
+ payoutsLimit: limits.payouts,
+ domainsLimit: limits.domains,
+ aiLimit: limits.ai,
+ tagsLimit: limits.tags,
+ foldersLimit: limits.folders,
+ groupsLimit: limits.groups,
+ networkInvitesLimit: limits.networkInvites,
+ usersLimit: limits.users,
+ ...(["active", "trialing"].includes(subscription.status)
+ ? { paymentFailedAt: null }
+ : {}),
+ ...(trialEndsAt !== undefined && { trialEndsAt }),
+ ...cancellationFields,
+ ...(planPeriod !== undefined && { planPeriod }),
},
include: {
users: {
where: {
role: "owner",
+ user: {
+ isMachine: false,
+ },
},
select: {
user: {
@@ -92,7 +138,6 @@ export async function updateWorkspacePlan({
orderBy: {
createdAt: "asc",
},
- take: 1,
},
},
}),
@@ -103,8 +148,6 @@ export async function updateWorkspacePlan({
({ hashedKey }) => hashedKey,
),
}),
-
- // if workspace has a program, need to update deactivatedAt and messagingEnabledAt columns based on the plan capabilities
...(workspace.defaultProgramId
? [
prisma.program.update({
@@ -112,17 +155,19 @@ export async function updateWorkspacePlan({
id: workspace.defaultProgramId,
},
data: {
- deactivatedAt: canManageProgram ? null : undefined,
messagingEnabledAt: canMessagePartners ? new Date() : null,
},
}),
]
: []),
]);
+ console.log(
+ `Updated workspace ${workspace.id} plan / limits / subscription details.`,
+ );
// Disable the webhooks if the new plan does not support webhooks
- if (shouldDisableWebhooks) {
- await Promise.all([
+ if (!canCreateWebhooks) {
+ await Promise.allSettled([
prisma.project.update({
where: {
id: workspace.id,
@@ -157,15 +202,17 @@ export async function updateWorkspacePlan({
});
await webhookCache.mset(webhooks);
+ console.log(`Updated webhooks cache for workspace ${workspace.id}.`);
}
- // Delete the folders if the new plan is free
+ // Delete the folders if the new plan does not support folders
// For downgrade from Business → Pro, it should be fine since we're accounting that to make sure all folders get write access.
- if (newPlanName === "free") {
+ if (!canAddFolder) {
await deleteWorkspaceFolders({
workspaceId: workspace.id,
defaultProgramId: workspace.defaultProgramId,
});
+ console.log(`Deleted folders for workspace ${workspace.id}.`);
}
// Deactivate the program if the workspace loses partner access (Business/Enterprise -> Pro/Free)
@@ -177,6 +224,7 @@ export async function updateWorkspacePlan({
workspace.defaultProgramId
) {
await deactivateProgram(workspace.defaultProgramId);
+ console.log(`Deactivated program for workspace ${workspace.id}.`);
}
// Reactivate all partners if the workspace gains partner access (Pro/Free -> Business/Enterprise)
@@ -188,23 +236,77 @@ export async function updateWorkspacePlan({
workspace.defaultProgramId
) {
await reactivateProgram(workspace.defaultProgramId);
+ console.log(`Reactivated program for workspace ${workspace.id}.`);
}
+ const workspaceOwners =
+ updatedWorkspace.status === "fulfilled"
+ ? updatedWorkspace.value.users.map((user) => user.user)
+ : [];
+
if (
- updatedWorkspace.status === "fulfilled" &&
- updatedWorkspace.value.users.length
+ workspace.defaultProgramId &&
+ wouldLoseAdvancedFeatures({
+ currentPlan: workspace.plan,
+ newPlan: newPlanName,
+ })
) {
- const workspaceOwner = updatedWorkspace.value.users[0].user;
- waitUntil(syncUserPlanToPlain(workspaceOwner));
+ await Promise.allSettled([
+ stripAdvancedRewardModifiersForProgram({
+ programId: workspace.defaultProgramId,
+ }),
+ pauseOrCancelCampaignsForProgramOnPlanDowngrade({
+ programId: workspace.defaultProgramId,
+ }),
+ workspaceOwners.length > 0 &&
+ sendBatchEmail(
+ workspaceOwners.map((owner) => ({
+ to: owner.email!,
+ subject: "Your Advanced plan features have been removed",
+ react: AdvancedPlanDowngradeNotice({
+ email: owner.email!,
+ workspace: {
+ name: workspace.name,
+ slug: workspace.slug,
+ },
+ }),
+ variant: "notifications",
+ headers: {
+ "Idempotency-Key": `advanced-downgrade-notice:${workspace.id}:${owner.email}`,
+ },
+ })),
+ ),
+ ]);
+ console.log(
+ `Stripped advanced reward modifiers for program ${workspace.defaultProgramId}.`,
+ );
+ }
+
+ if (workspaceOwners.length > 0) {
+ await Promise.allSettled([
+ ...(isPaidPlanActivated
+ ? [
+ // send thank you email to workspace owners
+ sendBatchEmail(
+ workspaceOwners.map((user) => ({
+ to: user.email as string,
+ replyTo: "[email protected]",
+ subject: `Thank you for upgrading to Dub ${newPlan.name}!`,
+ react: UpgradeEmail({
+ name: user.name,
+ email: user.email as string,
+ plan: newPlan.name,
+ }),
+ variant: "marketing",
+ })),
+ ),
+ ]
+ : []),
+ ...workspaceOwners.map((owner) => syncUserPlanToPlain(owner)),
+ ]);
+ console.log(
+ `Sent thank you emails to ${workspaceOwners.length} workspace owners for workspace ${workspace.slug}.`,
+ );
}
- } else if (workspace.paymentFailedAt) {
- await prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- paymentFailedAt: null,
- },
- });
}
}
diff --git a/apps/web/app/api/domains/[domain]/validate/route.ts b/apps/web/app/api/domains/[domain]/validate/route.ts
index 40f6f29072..533806e8b4 100644
--- a/apps/web/app/api/domains/[domain]/validate/route.ts
+++ b/apps/web/app/api/domains/[domain]/validate/route.ts
@@ -19,11 +19,14 @@ export const GET = withSession(async ({ params }) => {
status: "conflict",
});
}
- const hasSite = await hasSiteConfigured(domain);
- if (hasSite) {
- return NextResponse.json({
- status: "has site",
- });
+ // skip site check for .dub.link subdomains
+ if (!domain.endsWith(".dub.link")) {
+ const hasSite = await hasSiteConfigured(domain);
+ if (hasSite) {
+ return NextResponse.json({
+ status: "has site",
+ });
+ }
}
return NextResponse.json({
status: "available",
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 2710f6dc25..af4d869c9c 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -182,6 +182,25 @@ export const POST = withWorkspace(
}),
});
}
+
+ if (slug.endsWith(".dub.link")) {
+ const alreadyClaimed = await tx.domain.count({
+ where: {
+ projectId: workspace.id,
+ slug: {
+ endsWith: ".dub.link",
+ },
+ },
+ });
+ if (alreadyClaimed >= 1) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "You can only claim one .dub.link subdomain per workspace.",
+ });
+ }
+ }
+
return await tx.domain.create({
data: {
id: domainId,
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/activate-paid-plan/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/activate-paid-plan/route.ts
new file mode 100644
index 0000000000..c9fa93b854
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/activate-paid-plan/route.ts
@@ -0,0 +1,45 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withWorkspace } from "@/lib/auth";
+import { stripe } from "@/lib/stripe";
+import { NextResponse } from "next/server";
+
+// POST /api/workspaces/[idOrSlug]/billing/activate-paid-plan — end Stripe billing trial now (charge immediately, subscription becomes active)
+export const POST = withWorkspace(
+ async ({ workspace }) => {
+ if (!workspace.stripeId) {
+ return new Response("No Stripe customer ID", { status: 400 });
+ }
+
+ const { data: trialingSubs } = await stripe.subscriptions.list({
+ customer: workspace.stripeId,
+ status: "trialing",
+ limit: 1,
+ });
+ const trialingSubscription = trialingSubs[0];
+
+ if (trialingSubscription) {
+ await stripe.subscriptions.update(trialingSubscription.id, {
+ trial_end: "now",
+ cancel_at_period_end: false,
+ });
+ return NextResponse.json({ ok: true });
+ }
+
+ const { data: activeSubs } = await stripe.subscriptions.list({
+ customer: workspace.stripeId,
+ status: "active",
+ limit: 1,
+ });
+ if (activeSubs.length > 0) {
+ return NextResponse.json({ ok: true });
+ }
+
+ throw new DubApiError({
+ code: "bad_request",
+ message: "No trialing or active subscription found for this workspace.",
+ });
+ },
+ {
+ requiredPermissions: ["billing.write"],
+ },
+);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts
index c59562c41f..99d8cee98b 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/cancel/route.ts
@@ -1,41 +1,51 @@
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
-import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
+import Stripe from "stripe";
-// POST /api/workspaces/[idOrSlug]/billing/cancel - create a Stripe billing portal session in the cancellation flow
+// POST /api/workspaces/[idOrSlug]/billing/cancel — toggle cancel-at-period-end on the workspace subscription (Stripe API)
export const POST = withWorkspace(
async ({ workspace }) => {
- if (!workspace.stripeId)
- return new Response("No Stripe customer ID", { status: 400 });
+ if (!workspace.stripeId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "No Stripe customer ID",
+ });
+ }
try {
- const activeSubscription = await stripe.subscriptions
- .list({
- customer: workspace.stripeId,
- status: "active",
- })
- .then((res) => res.data[0]);
+ const { data } = await stripe.subscriptions.list({
+ customer: workspace.stripeId,
+ limit: 10,
+ });
+ const subscription = data.find(
+ (s) => s.status === "active" || s.status === "trialing",
+ );
+ if (!subscription) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "No active or trialing subscription found.",
+ });
+ }
- if (!activeSubscription)
- return new Response("No active subscription", { status: 400 });
+ const cancelAtPeriodEnd = subscription.cancel_at_period_end ?? false;
- const { url } = await stripe.billingPortal.sessions.create({
- customer: workspace.stripeId,
- return_url: `${APP_DOMAIN}/${workspace.slug}/settings/billing`,
- flow_data: {
- type: "subscription_cancel",
- subscription_cancel: {
- subscription: activeSubscription.id,
- },
- },
+ await stripe.subscriptions.update(subscription.id, {
+ cancel_at_period_end: !cancelAtPeriodEnd,
});
- return NextResponse.json(url);
+
+ return NextResponse.json({ success: true });
} catch (error) {
+ if (error instanceof DubApiError) {
+ throw error;
+ }
throw new DubApiError({
code: "bad_request",
- message: error.raw.message,
+ message:
+ error instanceof Stripe.errors.StripeError
+ ? error.message
+ : "Failed to update subscription.",
});
}
},
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
index 6dd32a932d..477a06f7a0 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
@@ -3,7 +3,7 @@ import { getDubAdminRole, withWorkspace } from "@/lib/auth";
import { getDubCustomer } from "@/lib/dub";
import { stripe } from "@/lib/stripe";
import { booleanQuerySchema } from "@/lib/zod/schemas/misc";
-import { APP_DOMAIN } from "@dub/utils";
+import { APP_DOMAIN, DUB_TRIAL_PERIOD_DAYS } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -15,17 +15,18 @@ const upgradePlanSchema = z.object({
message: "Invalid baseUrl.",
}),
onboarding: booleanQuerySchema.nullish(),
+ isTrialVariant: booleanQuerySchema.nullish(),
});
// POST /api/workspaces/[idOrSlug]/billing/upgrade
export const POST = withWorkspace(
async ({ req, workspace, session }) => {
- let { plan, period, tier, baseUrl, onboarding } = upgradePlanSchema.parse(
- await req.json(),
- );
+ let { plan, period, tier, baseUrl, onboarding, isTrialVariant } =
+ upgradePlanSchema.parse(await req.json());
const lookupKey =
tier > 1 ? `${plan}${tier}_${period}` : `${plan}_${period}`;
+
const prices = await stripe.prices.list({
lookup_keys: [lookupKey],
});
@@ -37,13 +38,19 @@ export const POST = withWorkspace(
});
}
- const activeSubscription = workspace.stripeId
- ? await stripe.subscriptions
- .list({
+ const existingSubscription = workspace.stripeId
+ ? await Promise.all([
+ stripe.subscriptions.list({
customer: workspace.stripeId,
status: "active",
- })
- .then((res) => res.data[0])
+ limit: 1,
+ }),
+ stripe.subscriptions.list({
+ customer: workspace.stripeId,
+ status: "trialing",
+ limit: 1,
+ }),
+ ]).then(([active, trialing]) => active.data[0] ?? trialing.data[0])
: null;
if (process.env.VERCEL === "1" && process.env.VERCEL_ENV === "preview") {
@@ -56,18 +63,18 @@ export const POST = withWorkspace(
}
}
- // if the user has an active subscription, create billing portal to upgrade
- if (workspace.stripeId && activeSubscription) {
+ // if the user has an active or trialing subscription, create billing portal to upgrade
+ if (workspace.stripeId && existingSubscription) {
const { url } = await stripe.billingPortal.sessions.create({
customer: workspace.stripeId,
return_url: baseUrl,
flow_data: {
type: "subscription_update_confirm",
subscription_update_confirm: {
- subscription: activeSubscription.id,
+ subscription: existingSubscription.id,
items: [
{
- id: activeSubscription.items.data[0].id,
+ id: existingSubscription.items.data[0].id,
quantity: 1,
price: prices.data[0].id,
},
@@ -79,7 +86,13 @@ export const POST = withWorkspace(
} else {
const customer = await getDubCustomer(session.user.id);
- // For both new users and users with canceled subscriptions
+ // New Stripe customer + no prior trial on workspace: partner checkout trial.
+ // Returning Stripe customers (e.g. canceled sub) must not get another trial here.
+ const shouldApplyCheckoutTrial =
+ workspace.stripeId == null &&
+ workspace.trialEndsAt == null &&
+ isTrialVariant;
+
const stripeSession = await stripe.checkout.sessions.create({
...(workspace.stripeId
? {
@@ -119,6 +132,13 @@ export const POST = withWorkspace(
enabled: true,
},
mode: "subscription",
+ ...(shouldApplyCheckoutTrial
+ ? {
+ subscription_data: {
+ trial_period_days: DUB_TRIAL_PERIOD_DAYS,
+ },
+ }
+ : {}),
client_reference_id: workspace.id,
metadata: {
dubCustomerId: session.user.id,
diff --git a/apps/web/app/app.dub.co/(auth)/side-panel.tsx b/apps/web/app/app.dub.co/(auth)/side-panel.tsx
index 6c037ff35f..04ed949353 100644
--- a/apps/web/app/app.dub.co/(auth)/side-panel.tsx
+++ b/apps/web/app/app.dub.co/(auth)/side-panel.tsx
@@ -44,7 +44,7 @@ export function SidePanel() {
</div>
<p className="text-content-default max-w-[370px] text-pretty text-xl font-medium">
- Learn how Framer manages $500K+ in monthly affiliate payouts with
+ Learn how Framer manages $900K+ in monthly affiliate payouts with
Dub
</p>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page-client.tsx
deleted file mode 100644
index 06feee6ea1..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page-client.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { CustomersTable } from "@/ui/customers/customers-table/customers-table";
-
-export function CustomersPageClient() {
- return <CustomersTable />;
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx
index d7fb02a972..05492f011a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx
@@ -1,7 +1,7 @@
+import { CustomersTable } from "@/ui/customers/customers-table/customers-table";
import { ExportCustomersButton } from "@/ui/customers/export-customers-button";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
-import { CustomersPageClient } from "./page-client";
export default function CustomersPage() {
return (
@@ -15,7 +15,7 @@ export default function CustomersPage() {
controls={<ExportCustomersButton />}
>
<PageWidthWrapper>
- <CustomersPageClient />
+ <CustomersTable />
</PageWidthWrapper>
</PageContent>
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/layout.tsx
deleted file mode 100644
index 72053141f1..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/layout.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { PageContent } from "@/ui/layout/page-content";
-import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
-import { ReactNode } from "react";
-
-export default function BillingLayout({ children }: { children: ReactNode }) {
- return (
- <PageContent title="Billing">
- <PageWidthWrapper>{children}</PageWidthWrapper>
- </PageContent>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/page.tsx
index 6302320efe..229620c6f9 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/page.tsx
@@ -1,11 +1,15 @@
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import PaymentMethods from "./payment-methods";
import PlanUsage from "./plan-usage";
export default function WorkspaceBilling() {
return (
- <div className="grid gap-8">
- <PlanUsage />
- <PaymentMethods />
- </div>
+ <PageContent title="Billing">
+ <PageWidthWrapper className="grid gap-8">
+ <PlanUsage />
+ <PaymentMethods />
+ </PageWidthWrapper>
+ </PageContent>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
index 130b6258d1..597e4b8427 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
@@ -1,5 +1,6 @@
"use client";
+import { clientAccessCheck } from "@/lib/client-access-check";
import { MEGA_WORKSPACE_LINKS_LIMIT } from "@/lib/constants/misc";
import useGroupsCount from "@/lib/swr/use-groups-count";
import usePartnersCount from "@/lib/swr/use-partners-count";
@@ -8,11 +9,14 @@ import { useUsageTimeseries } from "@/lib/swr/use-usage-timeseries";
import useWorkspace from "@/lib/swr/use-workspace";
import useWorkspaceUsers from "@/lib/swr/use-workspace-users";
import { useManageUsageModal } from "@/ui/modals/manage-usage-modal";
+import { useStartPaidPlanModal } from "@/ui/modals/start-paid-plan-modal";
import SubscriptionMenu from "@/ui/workspaces/subscription-menu";
import {
AnimatedSizeContainer,
Button,
+ DynamicTooltipWrapper,
Icon,
+ Modal,
Tooltip,
useRouterStuff,
} from "@dub/ui";
@@ -34,17 +38,26 @@ import {
getFirstAndLastDay,
INFINITY_NUMBER,
isLegacyBusinessPlan,
+ isWorkspaceBillingTrialActive,
nFormatter,
} from "@dub/utils";
import NumberFlow from "@number-flow/react";
import Link from "next/link";
-import { CSSProperties, ReactNode, useMemo } from "react";
+import { useRouter } from "next/navigation";
+import { CSSProperties, ReactNode, useMemo, useState } from "react";
+import { toast } from "sonner";
import { UsageChart } from "./usage-chart";
export default function PlanUsage() {
+ const router = useRouter();
+ const [showResubscribeModal, setShowResubscribeModal] = useState(false);
+ const [resubscribeLoading, setResubscribeLoading] = useState(false);
+
const {
+ id: workspaceId,
slug,
plan,
+ role,
stripeId,
defaultProgramId,
usage,
@@ -65,8 +78,20 @@ export default function PlanUsage() {
tagsLimit,
usersLimit,
billingCycleStart,
+ trialEndsAt,
+ subscriptionCanceledAt,
+ billingCycleEndsAt,
+ mutate,
} = useWorkspace();
+ const permissionsError = clientAccessCheck({
+ action: "billing.write",
+ role,
+ }).error;
+
+ const { StartPaidPlanModal, setShowStartPaidPlanModal } =
+ useStartPaidPlanModal();
+
const { data: tags } = useTagsCount();
const { users } = useWorkspaceUsers();
@@ -151,121 +176,292 @@ export default function PlanUsage() {
return `${payoutFee * 100}%`;
}, [plan, payoutFee, payoutFeeWaiverLimit, payoutFeeWaiverUsage]);
+ const pendingCancellationEndDate =
+ subscriptionCanceledAt && billingCycleEndsAt && plan !== "free" && stripeId
+ ? billingCycleEndsAt
+ : null;
+
+ const showPendingCancellation = pendingCancellationEndDate != null;
+
+ const confirmResubscribe = async () => {
+ setResubscribeLoading(true);
+ try {
+ const res = await fetch(`/api/workspaces/${workspaceId}/billing/cancel`, {
+ method: "POST",
+ });
+
+ if (res.ok) {
+ // sleep for 2 seconds to make sure Stripe webhook was received, and then mutate
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ await mutate();
+ setShowResubscribeModal(false);
+ toast.success("Your subscription will continue as normal.");
+ } else {
+ try {
+ const body = await res.json();
+ toast.error(body?.error?.message ?? "Failed to resume subscription.");
+ } catch (error) {
+ console.error(error);
+ toast.error("Failed to resume subscription.");
+ }
+ }
+ } catch (error) {
+ console.error(error);
+ toast.error("Failed to resume subscription.");
+ } finally {
+ setResubscribeLoading(false);
+ }
+ };
+
return (
- <div className="rounded-xl border border-neutral-200 bg-white">
- <div className="flex flex-col items-start justify-between gap-y-4 p-6 md:px-8 lg:flex-row">
- <div>
- <h2 className="text-xl font-medium">
- {plan && isLegacyBusinessPlan({ plan, payoutsLimit })
- ? "Business (Legacy)"
- : capitalize(plan)}{" "}
- Plan
- </h2>
- {billingStart && billingEnd && (
- <p className="mt-1.5 text-balance text-sm font-medium leading-normal text-neutral-700">
- <>
- Current billing cycle:{" "}
- <span className="font-normal">
- {billingStart} - {billingEnd}
- </span>
- </>
- </p>
- )}
+ <>
+ <StartPaidPlanModal />
+ <Modal
+ showModal={showResubscribeModal}
+ setShowModal={setShowResubscribeModal}
+ className="max-w-md"
+ >
+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">
+ <h3 className="text-content-emphasis text-lg font-medium">
+ Resume subscription
+ </h3>
</div>
- <div className="flex items-center gap-2">
- {plan !== "enterprise" && (
- <Link href={`/${slug}/settings/billing/upgrade`}>
+ <div className="flex flex-col gap-4 px-4 py-6 text-left text-sm text-neutral-600 sm:px-6">
+ <p>
+ Your subscription is scheduled to end on{" "}
+ <span className="font-medium text-neutral-900">
+ {pendingCancellationEndDate
+ ? new Date(pendingCancellationEndDate).toLocaleDateString(
+ "en-US",
+ {
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+ },
+ )
+ : "—"}
+ </span>
+ . Resuming removes that cancellation and your plan will continue as
+ before.
+ </p>
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Not now"
+ className="h-8 w-fit"
+ onClick={() => setShowResubscribeModal(false)}
+ disabled={resubscribeLoading}
+ />
+ <Button
+ type="button"
+ variant="primary"
+ text="Resume subscription"
+ className="h-8 w-fit"
+ loading={resubscribeLoading}
+ onClick={() => void confirmResubscribe()}
+ />
+ </div>
+ </Modal>
+ <div className="rounded-xl border border-neutral-200 bg-white">
+ {showPendingCancellation ? (
+ <div className="mx-1 mt-1 flex items-center justify-center rounded-lg bg-amber-100/50 px-3 py-2">
+ <p className="text-center text-xs text-amber-900">
+ Your subscription will be canceled on{" "}
+ <span className="font-medium">
+ {new Date(pendingCancellationEndDate).toLocaleDateString(
+ "en-US",
+ {
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+ },
+ )}
+ </span>
+ .
+ </p>
+ </div>
+ ) : trialEndsAt != null &&
+ isWorkspaceBillingTrialActive(trialEndsAt) ? (
+ <div className="mx-1 mt-1 flex items-center justify-center rounded-lg bg-blue-50/50 px-3 py-2">
+ <p className="text-xs font-medium text-blue-600">
+ Trial ends on{" "}
+ <span className="font-semibold">
+ {new Date(trialEndsAt).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}
+ </span>
+ . Your card will be charged when the trial ends unless you cancel.
+ </p>
+ </div>
+ ) : null}
+
+ <div className="flex flex-col items-start justify-between gap-y-4 p-6 md:px-8 lg:flex-row">
+ <div>
+ <h2 className="text-xl font-medium">
+ {plan && isLegacyBusinessPlan({ plan, payoutsLimit })
+ ? "Business (Legacy)"
+ : capitalize(plan)}{" "}
+ Plan
+ </h2>
+ {billingStart && billingEnd && (
+ <p className="mt-1.5 text-balance text-sm font-medium leading-normal text-neutral-700">
+ <>
+ Current billing cycle:{" "}
+ <span className="font-normal">
+ {billingStart} - {billingEnd}
+ </span>
+ </>
+ </p>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {plan !== "enterprise" &&
+ (plan === "free" ? (
+ <Link href={`/${slug}/settings/billing/upgrade`}>
+ <Button text="Upgrade" variant="primary" className="h-9" />
+ </Link>
+ ) : isWorkspaceBillingTrialActive(trialEndsAt) ? (
+ <DynamicTooltipWrapper
+ tooltipProps={
+ permissionsError ? { content: permissionsError } : undefined
+ }
+ >
+ <Button
+ text="Start paid plan"
+ variant="primary"
+ className="h-9"
+ disabled={Boolean(permissionsError)}
+ onClick={() => setShowStartPaidPlanModal(true)}
+ />
+ </DynamicTooltipWrapper>
+ ) : showPendingCancellation ? (
+ <DynamicTooltipWrapper
+ tooltipProps={
+ permissionsError ? { content: permissionsError } : undefined
+ }
+ >
+ <Button
+ text="Resume subscription"
+ variant="primary"
+ className="h-9"
+ disabled={Boolean(permissionsError)}
+ onClick={() => setShowResubscribeModal(true)}
+ />
+ </DynamicTooltipWrapper>
+ ) : (
+ <Link href={`/${slug}/settings/billing/upgrade`}>
+ <Button
+ text="Manage plan"
+ variant="primary"
+ className="h-9"
+ />
+ </Link>
+ ))}
+
+ <Link
+ href={
+ isWorkspaceBillingTrialActive(trialEndsAt)
+ ? `/${slug}/settings/billing/upgrade`
+ : `/${slug}/settings/billing/invoices`
+ }
+ >
<Button
- text={plan === "free" ? "Upgrade" : "Manage plan"}
- variant="primary"
+ text={
+ isWorkspaceBillingTrialActive(trialEndsAt)
+ ? "View plans"
+ : "View invoices"
+ }
+ variant="secondary"
className="h-9"
/>
</Link>
- )}
- <Link href={`/${slug}/settings/billing/invoices`}>
- <Button text="View invoices" variant="secondary" className="h-9" />
- </Link>
- {stripeId && plan !== "free" && <SubscriptionMenu />}
+
+ {stripeId && plan !== "free" && <SubscriptionMenu />}
+ </div>
</div>
- </div>
- <div className="grid grid-cols-[minmax(0,1fr)] divide-y divide-neutral-200 border-t border-neutral-200">
- <div>
- <div className="grid gap-4 p-6 pb-0 sm:grid-cols-2 md:p-8 md:pb-0 lg:gap-6">
- {usageTabs.map((tab) => (
- <UsageTabCard key={tab.resource} {...tab} />
- ))}
+ <div className="grid grid-cols-[minmax(0,1fr)] divide-y divide-neutral-200 border-t border-neutral-200">
+ <div>
+ <div className="grid gap-4 p-6 pb-0 sm:grid-cols-2 md:p-8 md:pb-0 lg:gap-6">
+ {usageTabs.map((tab) => (
+ <UsageTabCard key={tab.resource} {...tab} />
+ ))}
+ </div>
+ <div className="w-full px-2 pb-8 md:px-8">
+ <UsageChart />
+ </div>
</div>
- <div className="w-full px-2 pb-8 md:px-8">
- <UsageChart />
+ <div
+ className={cn(
+ "grid grid-cols-1 gap-[1px] overflow-hidden rounded-b-lg bg-neutral-200 md:grid-cols-3",
+ "md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-4",
+ )}
+ >
+ <UsageCategory
+ title="Custom Domains"
+ icon={Globe}
+ usage={domains?.length}
+ usageLimit={domainsLimit}
+ href={`/${slug}/settings/domains`}
+ />
+ <UsageCategory
+ title="Folders"
+ icon={Folder5}
+ usage={foldersUsage}
+ usageLimit={foldersLimit}
+ href={`/${slug}/settings/library/folders`}
+ />
+ <UsageCategory
+ title="Tags"
+ icon={Tag}
+ usage={tags}
+ usageLimit={tagsLimit}
+ href={`/${slug}/settings/library/tags`}
+ />
+ <UsageCategory
+ title="Teammates"
+ icon={Users}
+ usage={users?.filter((user) => !user.isMachine).length}
+ usageLimit={usersLimit}
+ href={`/${slug}/settings/people`}
+ />
+ </div>
+ <div className="grid grid-cols-1 gap-[1px] overflow-hidden rounded-b-xl bg-neutral-200 md:grid-cols-4">
+ <UsageCategory
+ title="Partners"
+ icon={Users}
+ usage={partnersCount ?? 0}
+ usageLimit={INFINITY_NUMBER}
+ href={`/${slug}/program/partners`}
+ />
+ <UsageCategory
+ title="Partner Groups"
+ icon={Users6}
+ usage={groupsCount ?? 0}
+ usageLimit={groupsLimit}
+ href={`/${slug}/program/groups`}
+ />
+ <UsageCategory
+ title="Partner payouts"
+ icon={CreditCard}
+ usage={payoutsUsage}
+ usageLimit={payoutsLimit}
+ unit="$"
+ href={`/${slug}/program/payouts`}
+ />
+ <UsageCategory
+ title="Payout fees"
+ icon={CirclePercentage}
+ usage={payoutFeeDisplay}
+ href="https://dub.co/help/article/partner-payouts#payout-fees-and-timing"
+ />
</div>
- </div>
- <div
- className={cn(
- "grid grid-cols-1 gap-[1px] overflow-hidden rounded-b-lg bg-neutral-200 md:grid-cols-3",
- "md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-4",
- )}
- >
- <UsageCategory
- title="Custom Domains"
- icon={Globe}
- usage={domains?.length}
- usageLimit={domainsLimit}
- href={`/${slug}/settings/domains`}
- />
- <UsageCategory
- title="Folders"
- icon={Folder5}
- usage={foldersUsage}
- usageLimit={foldersLimit}
- href={`/${slug}/settings/library/folders`}
- />
- <UsageCategory
- title="Tags"
- icon={Tag}
- usage={tags}
- usageLimit={tagsLimit}
- href={`/${slug}/settings/library/tags`}
- />
- <UsageCategory
- title="Teammates"
- icon={Users}
- usage={users?.filter((user) => !user.isMachine).length}
- usageLimit={usersLimit}
- href={`/${slug}/settings/people`}
- />
- </div>
- <div className="grid grid-cols-1 gap-[1px] overflow-hidden rounded-b-xl bg-neutral-200 md:grid-cols-4">
- <UsageCategory
- title="Partners"
- icon={Users}
- usage={partnersCount ?? 0}
- usageLimit={INFINITY_NUMBER}
- href={`/${slug}/program/partners`}
- />
- <UsageCategory
- title="Partner Groups"
- icon={Users6}
- usage={groupsCount ?? 0}
- usageLimit={groupsLimit}
- href={`/${slug}/program/groups`}
- />
- <UsageCategory
- title="Partner payouts"
- icon={CreditCard}
- usage={payoutsUsage}
- usageLimit={payoutsLimit}
- unit="$"
- href={`/${slug}/program/payouts`}
- />
- <UsageCategory
- title="Payout fees"
- icon={CirclePercentage}
- usage={payoutFeeDisplay}
- href="https://dub.co/help/article/partner-payouts#payout-fees-and-timing"
- />
</div>
</div>
- </div>
+ </>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsx
deleted file mode 100644
index c9099bf62c..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsx
+++ /dev/null
@@ -1,448 +0,0 @@
-"use client";
-
-import { clientAccessCheck } from "@/lib/client-access-check";
-import useWorkspace from "@/lib/swr/use-workspace";
-import { usePartnersUpgradeModal } from "@/ui/partners/partners-upgrade-modal";
-import { UpgradePlanButton } from "@/ui/workspaces/upgrade-plan-button";
-import {
- ChartLine,
- Check,
- CircleQuestion,
- ConnectedDots4,
- Globe,
- Hyperlink,
- Icon,
- Plug2,
- ToggleGroup,
- Users2,
-} from "@dub/ui";
-import {
- cn,
- getSuggestedPlan,
- isDowngradePlan,
- isLegacyBusinessPlan,
- PlanDetails,
- PLANS,
- PRICING_PLAN_COMPARE_FEATURES,
-} from "@dub/utils";
-import NumberFlow from "@number-flow/react";
-import { ChevronLeft, ChevronRight } from "lucide-react";
-import { motion } from "motion/react";
-import Link from "next/link";
-import { useSearchParams } from "next/navigation";
-import { CSSProperties, useEffect, useMemo, useState } from "react";
-import { AdjustUsageRow } from "./adjust-usage-row";
-
-const COMPARE_FEATURE_ICONS: Record<
- (typeof PRICING_PLAN_COMPARE_FEATURES)[number]["category"],
- Icon
-> = {
- Links: Hyperlink,
- Analytics: ChartLine,
- Partners: ConnectedDots4,
- Domains: Globe,
- Workspace: Users2,
- Support: CircleQuestion,
- API: Plug2,
-};
-
-export function WorkspaceBillingUpgradePageClient() {
- const {
- slug,
- role,
- plan: currentPlan,
- planTier: currentPlanTier = 1,
- stripeId,
- payoutsLimit,
- } = useWorkspace();
-
- const { error: permissionsError } = clientAccessCheck({
- action: "billing.write",
- role,
- });
-
- const [mobilePlanIndex, setMobilePlanIndex] = useState(0);
- const [period, setPeriod] = useState<"monthly" | "yearly">("monthly");
-
- const { partnersUpgradeModal, setShowPartnersUpgradeModal } =
- usePartnersUpgradeModal();
-
- const searchParams = useSearchParams();
- useEffect(() => {
- if (searchParams.get("showPartnersUpgradeModal")) {
- setShowPartnersUpgradeModal(true);
- }
- }, [searchParams]);
-
- const [eventsUsage, setEventsUsage] = useState<number | null>(null);
- const [linksUsage, setLinksUsage] = useState<number | null>(null);
-
- const recommendedPlan = useMemo(() => {
- if (!eventsUsage || !linksUsage) return null;
-
- return getSuggestedPlan({
- events: eventsUsage,
- links: linksUsage,
- });
- }, [linksUsage, eventsUsage]);
-
- const plans: { plan: PlanDetails; planTier: number }[] = useMemo(
- () =>
- ["Pro", "Business", "Advanced", "Enterprise"].map((p) => {
- const planDetails = PLANS.find(({ name }) => name === p)!;
- if (
- recommendedPlan &&
- recommendedPlan.plan.name.toLowerCase() === p.toLowerCase()
- ) {
- return recommendedPlan;
- }
- return { plan: planDetails, planTier: 1 };
- }),
- [recommendedPlan],
- );
-
- return (
- <div>
- {partnersUpgradeModal}
- <div className="flex flex-wrap items-start justify-between gap-4">
- <Link
- href={`/${slug}/settings/billing`}
- title="Back to billing"
- className="group flex items-center gap-2"
- >
- <ChevronLeft
- className="mt-px size-5 text-neutral-500 transition-transform duration-100 group-hover:-translate-x-0.5"
- strokeWidth={2}
- />
- <h1 className="text-2xl font-semibold tracking-tight text-neutral-900">
- Plans
- </h1>
- </Link>
- <ToggleGroup
- options={[
- { label: "Monthly", value: "monthly" },
- { label: "Yearly (Save 17%)", value: "yearly" },
- ]}
- selected={period}
- selectAction={(option) => setPeriod(option as "monthly" | "yearly")}
- className="rounded-lg border-neutral-300 bg-neutral-100 p-0.5"
- optionClassName="text-xs text-neutral-800 data-[selected=true]:text-neutral-800 px-3 sm:px-5 py-2 leading-none"
- indicatorClassName="bg-white border-neutral-200 rounded-md"
- />
- </div>
-
- <div className="mt-6">
- <div className="sticky -top-px z-10">
- <div className="overflow-x-hidden rounded-b-[12px] from-neutral-200 [container-type:inline-size] lg:bg-gradient-to-t lg:p-px">
- <div
- className={cn(
- "grid grid-cols-4 gap-px overflow-hidden rounded-b-[11px] text-sm text-neutral-800 [&_strong]:font-medium",
-
- // Mobile
- "max-lg:w-[calc(400cqw+3*32px)] max-lg:translate-x-[calc(-1*var(--index)*(100cqw+32px))] max-lg:gap-x-8 max-lg:transition-transform",
- )}
- style={
- {
- "--index": mobilePlanIndex,
- } as CSSProperties
- }
- >
- {plans.map(({ plan, planTier }, idx) => {
- // disable upgrade button if user has a Stripe ID and is on the current plan
- // (if there's no stripe id, they could be on a free trial so they should be able to upgrade)
- // edge case:
- // if the user is on the business plan and has a payout limit of 0,
- // it means they're on the legacy business plan – prompt them to upgrade to the new business plan
- const disableCurrentPlan = Boolean(
- stripeId &&
- plan.name.toLowerCase() === currentPlan &&
- planTier === currentPlanTier &&
- !isLegacyBusinessPlan({
- plan: currentPlan,
- payoutsLimit,
- }),
- );
-
- // show downgrade button if user has a stripe id and is on the current plan
- const isDowngrade = Boolean(
- stripeId &&
- isDowngradePlan({
- currentPlan: currentPlan || "free",
- currentTier: currentPlanTier,
- newPlan: plan.name,
- newTier: planTier,
- }),
- );
-
- return (
- <div
- key={plan.name}
- className={cn(
- "relative top-0 flex h-full flex-col gap-6 bg-white p-5 lg:p-3 xl:p-5",
- "max-lg:rounded-xl max-lg:border max-lg:border-neutral-200",
-
- idx !== mobilePlanIndex && "max-lg:opacity-0",
- )}
- >
- <div>
- <div className="flex items-start justify-between gap-2">
- <h3 className="py-1 text-base font-semibold leading-none text-neutral-800">
- {plan.name}
- </h3>
- {recommendedPlan &&
- !isDowngrade &&
- plan.name === recommendedPlan.plan.name &&
- planTier === recommendedPlan.planTier &&
- !disableCurrentPlan && (
- <div className="animate-fade-in flex h-6 min-w-0 items-center rounded-lg border border-blue-100 bg-blue-50 px-1.5 text-xs font-medium text-blue-600">
- <span className="truncate">Recommended</span>
- </div>
- )}
- </div>
- <div className="relative mt-0.5 flex items-center gap-1">
- {plan.name === "Enterprise" ? (
- <span className="text-sm font-medium text-neutral-900">
- Custom
- </span>
- ) : (
- <>
- <NumberFlow
- value={plan.price[period]!}
- className="text-sm font-medium tabular-nums text-neutral-700"
- format={{
- style: "currency",
- currency: "USD",
- minimumFractionDigits: 0,
- }}
- continuous
- />
- <span className="text-sm font-medium text-neutral-400">
- per month
- {period === "yearly" && ", billed yearly"}
- </span>
- </>
- )}
- </div>
- </div>
- <div className="flex gap-3">
- <button
- type="button"
- className="h-full w-fit rounded-lg bg-neutral-100 px-2.5 transition-colors duration-75 hover:bg-neutral-200/80 enabled:active:bg-neutral-200 disabled:opacity-30 lg:hidden"
- disabled={mobilePlanIndex === 0}
- onClick={() => setMobilePlanIndex(mobilePlanIndex - 1)}
- >
- <ChevronLeft className="size-5 text-neutral-800" />
- </button>
- {plan.name === "Enterprise" && !disableCurrentPlan ? (
- <Link
- href="https://dub.co/contact/sales"
- target="_blank"
- className={cn(
- "flex h-8 w-full items-center justify-center rounded-md text-center text-sm ring-gray-200 transition-all duration-200 ease-in-out",
- "border border-neutral-200 bg-white text-neutral-900 shadow-sm hover:bg-neutral-50",
- )}
- >
- Contact us
- </Link>
- ) : (
- <UpgradePlanButton
- plan={plan.name.toLowerCase()}
- tier={planTier > 1 ? planTier : undefined}
- period={period}
- disabled={
- disableCurrentPlan || currentPlan === "enterprise"
- }
- disabledTooltip={permissionsError || undefined}
- text={
- currentPlan === "enterprise"
- ? "Contact support"
- : disableCurrentPlan
- ? "Current plan"
- : isDowngrade
- ? "Downgrade"
- : "Upgrade"
- }
- variant={isDowngrade ? "secondary" : "primary"}
- className="h-8 shadow-sm"
- />
- )}
- <button
- type="button"
- className="h-full w-fit rounded-lg bg-neutral-100 px-2.5 transition-colors duration-75 hover:bg-neutral-200/80 active:bg-neutral-200 disabled:opacity-30 lg:hidden"
- disabled={mobilePlanIndex >= plans.length - 1}
- onClick={() => setMobilePlanIndex(mobilePlanIndex + 1)}
- >
- <ChevronRight className="size-5 text-neutral-800" />
- </button>
- </div>
- </div>
- );
- })}
- </div>
- </div>
-
- <div className="relative -z-10 bg-white">
- <div className="bg-bg-muted border-subtle absolute inset-x-0 -top-2.5 bottom-0 rounded-b-[12px] border" />
-
- <AdjustUsageRow
- onLinksUsageChange={(value) => setLinksUsage(value)}
- onEventsUsageChange={(value) => setEventsUsage(value)}
- />
- </div>
-
- <div className="h-4 bg-gradient-to-b from-white" />
- </div>
- <div className="flex flex-col pb-12">
- {PRICING_PLAN_COMPARE_FEATURES.map((section) => (
- <BillingCompareSection
- key={section.category}
- category={section.category}
- href={section.href}
- features={section.features}
- mobilePlanIndex={mobilePlanIndex}
- plans={plans}
- />
- ))}
- </div>
- </div>
- </div>
- );
-}
-
-function BillingCompareSection({
- category,
- href,
- features,
- mobilePlanIndex,
- plans,
-}: (typeof PRICING_PLAN_COMPARE_FEATURES)[number] & {
- mobilePlanIndex: number;
- plans: { plan: PlanDetails; planTier: number }[];
-}) {
- const [isExpanded, setIsExpanded] = useState(true);
- const { defaultProgramId } = useWorkspace();
-
- useEffect(() => {
- if (category === "Links") {
- // If there's a default program, collapse Links. Otherwise expand.
- setIsExpanded(!defaultProgramId);
- } else if (category === "Partners") {
- // If there's no default program, collapse Partners. Otherwise expand.
- setIsExpanded(Boolean(defaultProgramId));
- } else {
- setIsExpanded(true);
- }
- }, [category, defaultProgramId]);
-
- const Icon = COMPARE_FEATURE_ICONS[category];
-
- return (
- <div className="w-full overflow-x-hidden [container-type:inline-size]">
- <div className="flex items-center justify-between border-b border-neutral-200">
- <button
- type="button"
- className="group flex grow items-center gap-2 px-5 py-4 text-left"
- onClick={() => setIsExpanded((e) => !e)}
- >
- <Icon className="size-4 text-neutral-600" />
- <h3 className="text-base font-medium text-black">{category}</h3>
- <ChevronRight
- className={cn(
- "size-4 text-neutral-400 transition-[transform,color] group-hover:text-neutral-500 [&_*]:stroke-2",
- isExpanded && "rotate-90",
- )}
- />
- </button>
- {href && (
- <Link
- href={href}
- target="_blank"
- className="mr-5 cursor-alias text-xs font-medium text-neutral-500 underline decoration-dotted underline-offset-2"
- >
- Learn more ↗
- </Link>
- )}
- </div>
- <motion.div
- initial={false}
- animate={{ height: isExpanded ? "auto" : 0 }}
- className={cn(
- "overflow-clip transition-opacity",
- !isExpanded && "opacity-0",
- )}
- inert={!isExpanded}
- >
- <table
- className={cn(
- "grid grid-cols-4 overflow-hidden text-sm text-neutral-800 [&_strong]:font-medium",
-
- // Mobile
- "max-lg:w-[calc(400cqw+3*32px)] max-lg:translate-x-[calc(-1*var(--index)*(100cqw+32px))] max-lg:gap-x-8 max-lg:transition-transform",
- )}
- style={
- {
- "--index": mobilePlanIndex,
- } as CSSProperties
- }
- >
- <thead className="sr-only">
- <tr>
- {plans.map(({ plan }) => (
- <th key={plan.name}>{plan.name}</th>
- ))}
- </tr>
- </thead>
- <tbody className="contents">
- {features.map(({ check, text, href }, idx) => {
- const As = href ? "a" : "span";
-
- return (
- <tr key={idx} className="contents bg-white">
- {plans.map(({ plan }) => {
- const id = plan.name.toLowerCase();
- const isChecked =
- typeof check === "boolean"
- ? check
- : check === undefined ||
- (check[id] ?? check.default ?? false);
-
- return (
- <td
- key={id}
- className={cn(
- "flex items-center gap-2 border-b border-neutral-200 bg-white px-5 py-4",
- !isChecked && "text-neutral-300",
- )}
- >
- {isChecked ? (
- <Check className="size-3 text-neutral-500" />
- ) : (
- <span className="w-3">&bull;</span>
- )}
- <As
- href={href}
- target="_blank"
- {...(href && {
- className:
- "cursor-help underline decoration-dotted underline-offset-2",
- })}
- >
- {typeof text === "function"
- ? (text({
- id,
- plan,
- }) as React.ReactNode)
- : text}
- </As>
- </td>
- );
- })}
- </tr>
- );
- })}
- </tbody>
- </table>
- </motion.div>
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx
index 3f853deb8b..228688f5ee 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx
@@ -1,10 +1,464 @@
-import { MaxWidthWrapper } from "@dub/ui";
-import { WorkspaceBillingUpgradePageClient } from "./page-client";
+"use client";
+
+import { clientAccessCheck } from "@/lib/client-access-check";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { usePartnersUpgradeModal } from "@/ui/partners/partners-upgrade-modal";
+import { UpgradePlanButton } from "@/ui/workspaces/upgrade-plan-button";
+import {
+ ChartLine,
+ Check,
+ CircleQuestion,
+ ConnectedDots4,
+ Globe,
+ Hyperlink,
+ Icon,
+ Plug2,
+ ToggleGroup,
+ Users2,
+} from "@dub/ui";
+import {
+ cn,
+ getSuggestedPlan,
+ isDowngradePlan,
+ isLegacyBusinessPlan,
+ isWorkspaceBillingTrialActive,
+ PlanDetails,
+ PLANS,
+ PRICING_PLAN_COMPARE_FEATURES,
+} from "@dub/utils";
+import NumberFlow from "@number-flow/react";
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import { motion } from "motion/react";
+import Link from "next/link";
+import { useSearchParams } from "next/navigation";
+import { CSSProperties, useEffect, useMemo, useState } from "react";
+import { AdjustUsageRow } from "./adjust-usage-row";
+
+const COMPARE_FEATURE_ICONS: Record<
+ (typeof PRICING_PLAN_COMPARE_FEATURES)[number]["category"],
+ Icon
+> = {
+ Links: Hyperlink,
+ Analytics: ChartLine,
+ Partners: ConnectedDots4,
+ Domains: Globe,
+ Workspace: Users2,
+ Support: CircleQuestion,
+ API: Plug2,
+};
+
+export default function WorkspaceBillingUpgradePage() {
+ const {
+ slug,
+ role,
+ plan: currentPlan,
+ planTier: currentPlanTier = 1,
+ planPeriod: currentPlanPeriod,
+ stripeId,
+ payoutsLimit,
+ trialEndsAt,
+ } = useWorkspace();
+
+ const { error: permissionsError } = clientAccessCheck({
+ action: "billing.write",
+ role,
+ });
+
+ const [mobilePlanIndex, setMobilePlanIndex] = useState(0);
+ const [period, setPeriod] = useState<"monthly" | "yearly">(
+ currentPlanPeriod === "yearly" ? "yearly" : "monthly",
+ );
+
+ const { partnersUpgradeModal, setShowPartnersUpgradeModal } =
+ usePartnersUpgradeModal();
+
+ const searchParams = useSearchParams();
+ useEffect(() => {
+ if (searchParams.get("showPartnersUpgradeModal")) {
+ setShowPartnersUpgradeModal(true);
+ }
+ }, [searchParams]);
+
+ const [eventsUsage, setEventsUsage] = useState<number | null>(null);
+ const [linksUsage, setLinksUsage] = useState<number | null>(null);
+
+ const recommendedPlan = useMemo(() => {
+ if (!eventsUsage || !linksUsage) return null;
+
+ return getSuggestedPlan({
+ events: eventsUsage,
+ links: linksUsage,
+ });
+ }, [linksUsage, eventsUsage]);
+
+ const plans: { plan: PlanDetails; planTier: number }[] = useMemo(
+ () =>
+ ["Pro", "Business", "Advanced", "Enterprise"].map((p) => {
+ const planDetails = PLANS.find(({ name }) => name === p)!;
+ if (
+ recommendedPlan &&
+ recommendedPlan.plan.name.toLowerCase() === p.toLowerCase()
+ ) {
+ return recommendedPlan;
+ }
+ return { plan: planDetails, planTier: 1 };
+ }),
+ [recommendedPlan],
+ );
+
+ return (
+ <PageContent
+ title={
+ <div className="flex items-center gap-1.5">
+ <Link
+ href={`/${slug}/settings/billing`}
+ className="transition-all duration-150 hover:text-neutral-600 active:scale-95"
+ >
+ Billing
+ </Link>
+ <ChevronRight className="text-content-muted size-4" />
+ <h1>Plans</h1>
+ </div>
+ }
+ controls={
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <ToggleGroup
+ options={[
+ { label: "Monthly", value: "monthly" },
+ { label: "Yearly (Save 17%)", value: "yearly" },
+ ]}
+ selected={period}
+ selectAction={(option) => setPeriod(option as "monthly" | "yearly")}
+ className="rounded-lg border-neutral-300 bg-neutral-100 p-0.5"
+ optionClassName="text-xs text-neutral-800 data-[selected=true]:text-neutral-800 px-3 sm:px-5 py-2 leading-none"
+ indicatorClassName="bg-white border-neutral-200 rounded-md"
+ />
+ </div>
+ }
+ >
+ {partnersUpgradeModal}
+ <PageWidthWrapper className="grid gap-8">
+ <div className="sticky -top-px z-10">
+ <div className="overflow-x-hidden rounded-b-[12px] from-neutral-200 [container-type:inline-size] lg:bg-gradient-to-t lg:p-px">
+ <div
+ className={cn(
+ "grid grid-cols-4 gap-px overflow-hidden rounded-b-[11px] text-sm text-neutral-800 [&_strong]:font-medium",
+
+ // Mobile
+ "max-lg:w-[calc(400cqw+3*32px)] max-lg:translate-x-[calc(-1*var(--index)*(100cqw+32px))] max-lg:gap-x-8 max-lg:transition-transform",
+ )}
+ style={
+ {
+ "--index": mobilePlanIndex,
+ } as CSSProperties
+ }
+ >
+ {plans.map(({ plan, planTier }, idx) => {
+ // disable upgrade button if user has a Stripe ID and is on the current plan
+ // (trialing subscriptions still use Checkout in some edge cases; portal handles plan changes)
+ // edge case:
+ // if the user is on the business plan and has a payout limit of 0,
+ // it means they're on the legacy business plan – prompt them to upgrade to the new business plan
+ const isCurrentPlan = Boolean(
+ stripeId &&
+ plan.name.toLowerCase() === currentPlan &&
+ planTier === currentPlanTier &&
+ !isLegacyBusinessPlan({
+ plan: currentPlan,
+ payoutsLimit,
+ }),
+ );
+ const isCurrentPlanAndPeriod =
+ isCurrentPlan && period === currentPlanPeriod;
+
+ // show downgrade button if user has a stripe id and is on the current plan
+ const isDowngrade = Boolean(
+ stripeId &&
+ isDowngradePlan({
+ currentPlan: currentPlan || "free",
+ currentTier: currentPlanTier,
+ newPlan: plan.name,
+ newTier: planTier,
+ }),
+ );
+
+ return (
+ <div
+ key={plan.name}
+ className={cn(
+ "relative top-0 flex h-full flex-col gap-6 bg-white p-5 lg:p-3 xl:p-5",
+ "max-lg:rounded-xl max-lg:border max-lg:border-neutral-200",
+
+ idx !== mobilePlanIndex && "max-lg:opacity-0",
+ )}
+ >
+ <div>
+ <div className="flex items-start justify-between gap-2">
+ <h3 className="py-1 text-base font-semibold leading-none text-neutral-800">
+ {plan.name}
+ </h3>
+ {recommendedPlan &&
+ !isDowngrade &&
+ plan.name === recommendedPlan.plan.name &&
+ planTier === recommendedPlan.planTier &&
+ !isCurrentPlan && (
+ <div className="animate-fade-in flex h-6 min-w-0 items-center rounded-lg border border-blue-100 bg-blue-50 px-1.5 text-xs font-medium text-blue-600">
+ <span className="truncate">Recommended</span>
+ </div>
+ )}
+ </div>
+ <div className="relative mt-0.5 flex items-center gap-1">
+ {plan.name === "Enterprise" ? (
+ <span className="text-sm font-medium text-neutral-900">
+ Custom
+ </span>
+ ) : (
+ <>
+ <NumberFlow
+ value={plan.price[period]!}
+ className="text-sm font-medium tabular-nums text-neutral-700"
+ format={{
+ style: "currency",
+ currency: "USD",
+ minimumFractionDigits: 0,
+ }}
+ continuous
+ />
+ <span className="text-sm font-medium text-neutral-400">
+ per month
+ {period === "yearly" && ", billed yearly"}
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ <div className="flex gap-3">
+ <button
+ type="button"
+ className="h-full w-fit rounded-lg bg-neutral-100 px-2.5 transition-colors duration-75 hover:bg-neutral-200/80 enabled:active:bg-neutral-200 disabled:opacity-30 lg:hidden"
+ disabled={mobilePlanIndex === 0}
+ onClick={() => setMobilePlanIndex(mobilePlanIndex - 1)}
+ >
+ <ChevronLeft className="size-5 text-neutral-800" />
+ </button>
+ {plan.name === "Enterprise" && !isCurrentPlan ? (
+ <Link
+ href="https://dub.co/contact/sales"
+ target="_blank"
+ className={cn(
+ "flex h-8 w-full items-center justify-center rounded-md text-center text-sm ring-gray-200 transition-all duration-200 ease-in-out",
+ "border border-neutral-200 bg-white text-neutral-900 shadow-sm hover:bg-neutral-50",
+ )}
+ >
+ Contact us
+ </Link>
+ ) : (
+ <UpgradePlanButton
+ plan={plan.name.toLowerCase()}
+ tier={planTier > 1 ? planTier : undefined}
+ period={period}
+ disabled={
+ (isCurrentPlanAndPeriod &&
+ !isWorkspaceBillingTrialActive(trialEndsAt)) ||
+ currentPlan === "enterprise"
+ }
+ disabledTooltip={permissionsError || undefined}
+ text={
+ currentPlan === "enterprise"
+ ? "Contact support"
+ : isCurrentPlanAndPeriod
+ ? isWorkspaceBillingTrialActive(trialEndsAt)
+ ? "Activate plan"
+ : "Current plan"
+ : isCurrentPlan
+ ? `Switch to ${period}`
+ : isDowngrade
+ ? "Downgrade"
+ : "Upgrade"
+ }
+ variant={isDowngrade ? "secondary" : "primary"}
+ className="h-8 shadow-sm"
+ />
+ )}
+ <button
+ type="button"
+ className="h-full w-fit rounded-lg bg-neutral-100 px-2.5 transition-colors duration-75 hover:bg-neutral-200/80 active:bg-neutral-200 disabled:opacity-30 lg:hidden"
+ disabled={mobilePlanIndex >= plans.length - 1}
+ onClick={() => setMobilePlanIndex(mobilePlanIndex + 1)}
+ >
+ <ChevronRight className="size-5 text-neutral-800" />
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="relative -z-10 bg-white">
+ <div className="bg-bg-muted border-subtle absolute inset-x-0 -top-2.5 bottom-0 rounded-b-[12px] border" />
+
+ <AdjustUsageRow
+ onLinksUsageChange={(value) => setLinksUsage(value)}
+ onEventsUsageChange={(value) => setEventsUsage(value)}
+ />
+ </div>
+
+ <div className="h-4 bg-gradient-to-b from-white" />
+ </div>
+ <div className="flex flex-col pb-12">
+ {PRICING_PLAN_COMPARE_FEATURES.map((section) => (
+ <BillingCompareSection
+ key={section.category}
+ category={section.category}
+ href={section.href}
+ features={section.features}
+ mobilePlanIndex={mobilePlanIndex}
+ plans={plans}
+ />
+ ))}
+ </div>
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
+
+function BillingCompareSection({
+ category,
+ href,
+ features,
+ mobilePlanIndex,
+ plans,
+}: (typeof PRICING_PLAN_COMPARE_FEATURES)[number] & {
+ mobilePlanIndex: number;
+ plans: { plan: PlanDetails; planTier: number }[];
+}) {
+ const [isExpanded, setIsExpanded] = useState(true);
+ const { defaultProgramId } = useWorkspace();
+
+ useEffect(() => {
+ if (category === "Links") {
+ // If there's a default program, collapse Links. Otherwise expand.
+ setIsExpanded(!defaultProgramId);
+ } else if (category === "Partners") {
+ // If there's no default program, collapse Partners. Otherwise expand.
+ setIsExpanded(Boolean(defaultProgramId));
+ } else {
+ setIsExpanded(true);
+ }
+ }, [category, defaultProgramId]);
+
+ const Icon = COMPARE_FEATURE_ICONS[category];
-export default function WorkspaceBillingUpgrade() {
return (
- <MaxWidthWrapper className="grid gap-8">
- <WorkspaceBillingUpgradePageClient />
- </MaxWidthWrapper>
+ <div className="w-full overflow-x-hidden [container-type:inline-size]">
+ <div className="flex items-center justify-between border-b border-neutral-200">
+ <button
+ type="button"
+ className="group flex grow items-center gap-2 px-5 py-4 text-left"
+ onClick={() => setIsExpanded((e) => !e)}
+ >
+ <Icon className="size-4 text-neutral-600" />
+ <h3 className="text-base font-medium text-black">{category}</h3>
+ <ChevronRight
+ className={cn(
+ "size-4 text-neutral-400 transition-[transform,color] group-hover:text-neutral-500 [&_*]:stroke-2",
+ isExpanded && "rotate-90",
+ )}
+ />
+ </button>
+ {href && (
+ <Link
+ href={href}
+ target="_blank"
+ className="mr-5 cursor-alias text-xs font-medium text-neutral-500 underline decoration-dotted underline-offset-2"
+ >
+ Learn more ↗
+ </Link>
+ )}
+ </div>
+ <motion.div
+ initial={false}
+ animate={{ height: isExpanded ? "auto" : 0 }}
+ className={cn(
+ "overflow-clip transition-opacity",
+ !isExpanded && "opacity-0",
+ )}
+ inert={!isExpanded}
+ >
+ <table
+ className={cn(
+ "grid grid-cols-4 overflow-hidden text-sm text-neutral-800 [&_strong]:font-medium",
+
+ // Mobile
+ "max-lg:w-[calc(400cqw+3*32px)] max-lg:translate-x-[calc(-1*var(--index)*(100cqw+32px))] max-lg:gap-x-8 max-lg:transition-transform",
+ )}
+ style={
+ {
+ "--index": mobilePlanIndex,
+ } as CSSProperties
+ }
+ >
+ <thead className="sr-only">
+ <tr>
+ {plans.map(({ plan }) => (
+ <th key={plan.name}>{plan.name}</th>
+ ))}
+ </tr>
+ </thead>
+ <tbody className="contents">
+ {features.map(({ check, text, href }, idx) => {
+ const As = href ? "a" : "span";
+
+ return (
+ <tr key={idx} className="contents bg-white">
+ {plans.map(({ plan }) => {
+ const id = plan.name.toLowerCase();
+ const isChecked =
+ typeof check === "boolean"
+ ? check
+ : check === undefined ||
+ (check[id] ?? check.default ?? false);
+
+ return (
+ <td
+ key={id}
+ className={cn(
+ "flex items-center gap-2 border-b border-neutral-200 bg-white px-5 py-4",
+ !isChecked && "text-neutral-300",
+ )}
+ >
+ {isChecked ? (
+ <Check className="size-3 text-neutral-500" />
+ ) : (
+ <span className="w-3">&bull;</span>
+ )}
+ <As
+ href={href}
+ target="_blank"
+ {...(href && {
+ className:
+ "cursor-help underline decoration-dotted underline-offset-2",
+ })}
+ >
+ {typeof text === "function"
+ ? (text({
+ id,
+ plan,
+ }) as React.ReactNode)
+ : text}
+ </As>
+ </td>
+ );
+ })}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </motion.div>
+ </div>
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/links/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/links/page-client.tsx
index ffcdf055b0..49e2e6cff0 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/links/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/links/page-client.tsx
@@ -24,6 +24,7 @@ import { useAddEditTagModal } from "@/ui/modals/add-edit-tag-modal";
import { useDotLinkOfferModal } from "@/ui/modals/dot-link-offer-modal";
import { useExportLinksModal } from "@/ui/modals/export-links-modal";
import { useLinkBuilder } from "@/ui/modals/link-builder";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import { ThreeDots } from "@/ui/shared/icons";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
import {
@@ -36,6 +37,10 @@ import {
useRouterStuff,
} from "@dub/ui";
import { Download, Globe, TableIcon, Tag } from "@dub/ui/icons";
+import {
+ isWorkspaceBillingTrialActive,
+ type TrialLimitResource,
+} from "@dub/utils";
import { useRouter, useSearchParams } from "next/navigation";
import { ReactNode, useEffect, useState } from "react";
@@ -119,6 +124,7 @@ function WorkspaceLinks() {
// We show the .link offer modal if:
// - The upgraded modal is not open
// - The user has a paid plan (and valid stripe ID)
+ // - The user is not in a billing trial (.link cannot be claimed until trial ends)
// - The user has no custom domains
// - The user has not claimed their .link domain
// - The user has not dismissed the .link offer modal
@@ -127,6 +133,7 @@ function WorkspaceLinks() {
workspace.stripeId &&
workspace.plan &&
workspace.plan !== "free" &&
+ !isWorkspaceBillingTrialActive(workspace.trialEndsAt) &&
workspace.domains?.length === 0 &&
!workspace.dotLinkClaimed &&
!loadingDotLinkOfferDismissed &&
@@ -272,6 +279,8 @@ const MoreLinkOptions = () => {
const [openPopover, setOpenPopover] = useState(false);
const [_state, setState] = useState<"default" | "import">("default");
const { ExportLinksModal, setShowExportLinksModal } = useExportLinksModal();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
useEffect(() => {
if (!openPopover) setState("default");
@@ -279,6 +288,7 @@ const MoreLinkOptions = () => {
return (
<>
+ <TrialLimitActivateModal />
<ExportLinksModal />
<Popover
content={
@@ -288,6 +298,7 @@ const MoreLinkOptions = () => {
Import Links
</p>
<ImportOption
+ openTrialLimitModal={openTrialLimitModal}
onClick={() => {
setOpenPopover(false);
queryParams({
@@ -309,6 +320,7 @@ const MoreLinkOptions = () => {
/>
</ImportOption>
<ImportOption
+ openTrialLimitModal={openTrialLimitModal}
onClick={() => {
setOpenPopover(false);
queryParams({
@@ -330,6 +342,7 @@ const MoreLinkOptions = () => {
/>
</ImportOption>
<ImportOption
+ openTrialLimitModal={openTrialLimitModal}
onClick={() => {
setOpenPopover(false);
queryParams({
@@ -351,6 +364,7 @@ const MoreLinkOptions = () => {
/>
</ImportOption>
<ImportOption
+ openTrialLimitModal={openTrialLimitModal}
onClick={() => {
setOpenPopover(false);
queryParams({
@@ -404,20 +418,31 @@ const MoreLinkOptions = () => {
function ImportOption({
children,
onClick,
+ openTrialLimitModal,
}: {
children: ReactNode;
onClick: () => void;
+ openTrialLimitModal: (resource: TrialLimitResource) => void;
}) {
- const { slug, exceededLinks, plan, nextPlan } = useWorkspace();
+ const { slug, exceededLinks, plan, nextPlan, trialEndsAt } = useWorkspace();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
return exceededLinks && plan !== "enterprise" ? (
<Tooltip
content={
- <TooltipContent
- title="Your workspace has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to create more links."
- cta={nextPlan ? `Upgrade to ${nextPlan.name}` : "Contact support"}
- href={`/${slug}/upgrade`}
- />
+ trialActive ? (
+ <TooltipContent
+ title="Your workspace has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to create more links."
+ cta="Start paid plan"
+ onClick={() => openTrialLimitModal("links")}
+ />
+ ) : (
+ <TooltipContent
+ title="Your workspace has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to create more links."
+ cta={nextPlan ? `Upgrade to ${nextPlan.name}` : "Contact support"}
+ href={`/${slug}/upgrade`}
+ />
+ )
}
>
<div className="flex w-full cursor-not-allowed items-center justify-between space-x-2 rounded-md p-2 text-sm text-neutral-400 [&_img]:grayscale">
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx
index 6792380e6a..ce1b644236 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx
@@ -1,25 +1,23 @@
"use client";
import { AddEditDomainForm } from "@/ui/domains/add-edit-domain-form";
-import { LaterButton } from "../../../later-button";
+import { useSearchParams } from "next/navigation";
import { useOnboardingProduct } from "../../../use-onboarding-product";
import { useOnboardingProgress } from "../../../use-onboarding-progress";
export function Form() {
+ const searchParams = useSearchParams();
+ const workspaceSlug = searchParams.get("workspace") ?? "company";
const product = useOnboardingProduct();
-
const { continueTo } = useOnboardingProgress();
return (
- <div>
- <AddEditDomainForm
- onSuccess={() => {
- continueTo(product === "partners" ? "program" : "plan");
- }}
- enableDomainConfig={false}
- />
-
- {product !== "partners" && <LaterButton next="plan" className="mt-4" />}
- </div>
+ <AddEditDomainForm
+ onSuccess={() => {
+ continueTo(product === "partners" ? "program" : "plan");
+ }}
+ enableDomainConfig={false}
+ initialDomain={`${workspaceSlug}.com`}
+ />
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/default-domain-selector.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/default-domain-selector.tsx
index 2104e3da54..932fc2c9b7 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/default-domain-selector.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/default-domain-selector.tsx
@@ -1,22 +1,54 @@
"use client";
import { OnboardingStep } from "@/lib/onboarding/types";
-import { Button, Crown } from "@dub/ui";
+import { BoltFill, Button, Crown, Icon } from "@dub/ui";
import Image from "next/image";
import { useSearchParams } from "next/navigation";
import { ReactNode } from "react";
import { LaterButton } from "../../later-button";
import { useOnboardingProduct } from "../../use-onboarding-product";
import { useOnboardingProgress } from "../../use-onboarding-progress";
+import { useOnboardingTrialVariant } from "../../use-onboarding-trial-variant";
export function DefaultDomainSelector() {
const searchParams = useSearchParams();
+ const { isTrialVariant } = useOnboardingTrialVariant();
const workspaceSlug = searchParams.get("workspace");
const product = useOnboardingProduct();
return (
<>
<div className="animate-fade-in mx-auto grid w-full gap-4 sm:max-w-[600px] sm:grid-cols-2">
+ {isTrialVariant && (
+ <DomainOption
+ step="domain/subdomain"
+ icon="https://assets.dub.co/icons/gift.webp"
+ title={
+ <>
+ Free{" "}
+ <span className="rounded border border-neutral-800/10 bg-neutral-100 px-1 py-0.5 font-mono text-xs">
+ .dub.link
+ </span>{" "}
+ subdomain
+ </>
+ }
+ description={
+ <>
+ Get a free custom domain like{" "}
+ <span className="font-mono font-semibold text-neutral-900">
+ {workspaceSlug && workspaceSlug.length < 8
+ ? workspaceSlug
+ : "company"}
+ .dub.link
+ </span>{" "}
+ for your links.
+ </>
+ }
+ cta="Claim .dub.link subdomain"
+ bannerIcon={BoltFill}
+ bannerText="Instant setup"
+ />
+ )}
<DomainOption
step="domain/custom"
icon="https://assets.dub.co/icons/domain-sign.webp"
@@ -24,33 +56,36 @@ export function DefaultDomainSelector() {
description="Already have a domain? Connect it to your Dub workspace."
cta="Connect domain"
/>
- <DomainOption
- step="domain/register"
- icon="https://assets.dub.co/icons/gift.webp"
- title={
- <>
- Claim a free{" "}
- <span className="rounded border border-neutral-800/10 bg-neutral-100 px-1 py-0.5 font-mono text-xs">
- .link
- </span>{" "}
- domain
- </>
- }
- description={
- <>
- Register a domain like{" "}
- <span className="font-mono font-semibold text-neutral-900">
- {workspaceSlug && workspaceSlug.length < 8
- ? workspaceSlug
- : "company"}
- .link
- </span>{" "}
- – free for 1 year
- </>
- }
- cta="Claim .link domain"
- paidPlanRequired={product !== "partners"}
- />
+ {!isTrialVariant && (
+ <DomainOption
+ step="domain/register"
+ icon="https://assets.dub.co/icons/gift.webp"
+ title={
+ <>
+ Claim a free{" "}
+ <span className="rounded border border-neutral-800/10 bg-neutral-100 px-1 py-0.5 font-mono text-xs">
+ .link
+ </span>{" "}
+ domain
+ </>
+ }
+ description={
+ <>
+ Register a domain like{" "}
+ <span className="font-mono font-semibold text-neutral-900">
+ {workspaceSlug && workspaceSlug.length < 8
+ ? workspaceSlug
+ : "company"}
+ .link
+ </span>{" "}
+ – free for 1 year
+ </>
+ }
+ cta="Claim .link domain"
+ bannerIcon={Crown}
+ bannerText="Paid plan required"
+ />
+ )}
</div>
{product === "links" && (
<div className="mx-auto mt-8 w-full max-w-sm">
@@ -67,22 +102,24 @@ function DomainOption({
title,
description,
cta,
- paidPlanRequired,
+ bannerIcon: BannerIcon,
+ bannerText,
}: {
step: OnboardingStep;
icon: string;
title: ReactNode;
description: ReactNode;
cta: string;
- paidPlanRequired?: boolean;
+ bannerIcon?: Icon;
+ bannerText?: string;
}) {
const { continueTo, isLoading, isSuccessful } = useOnboardingProgress();
return (
<div className="relative flex h-full flex-col items-center gap-6 rounded-xl border border-neutral-300 p-6 pt-12 transition-all">
- {paidPlanRequired && (
+ {BannerIcon && bannerText && (
<div className="absolute inset-x-2 top-2 flex items-center justify-center gap-2 rounded-md border border-neutral-200 bg-neutral-100 px-2.5 py-1 text-xs font-medium text-neutral-600">
- <Crown className="size-3" />
- Paid plan required
+ <BannerIcon className="size-3" />
+ {bannerText}
</div>
)}
<div className="relative size-36">
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx
index cda907bb42..be490c206d 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx
@@ -1,24 +1,19 @@
"use client";
import { RegisterDomainForm } from "@/ui/domains/register-domain-form";
-import { LaterButton } from "../../../later-button";
import { useOnboardingProduct } from "../../../use-onboarding-product";
import { useOnboardingProgress } from "../../../use-onboarding-progress";
export function Form() {
- const { continueTo } = useOnboardingProgress();
const product = useOnboardingProduct();
+ const { continueTo } = useOnboardingProgress();
return (
- <div>
- <RegisterDomainForm
- saveOnly
- onSuccess={() => {
- continueTo(product === "partners" ? "program" : "plan");
- }}
- />
-
- {product !== "partners" && <LaterButton next="plan" className="mt-4" />}
- </div>
+ <RegisterDomainForm
+ saveOnly
+ onSuccess={() => {
+ continueTo(product === "partners" ? "program" : "plan");
+ }}
+ />
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx
index 22ecdeedba..28d7433e8c 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx
@@ -11,16 +11,12 @@ export default function Register() {
return (
<StepPage
title="Claim your free .link domain"
- paidPlanRequired={true}
- badge={
- product === "partners"
- ? {
- icon: BoltFill,
- label: "Instant setup",
- }
- : undefined
- }
+ badge={{
+ icon: BoltFill,
+ label: "Instant setup",
+ }}
description="Exclusively free for one year"
+ paidPlanRequired
>
<Form />
</StepPage>
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/subdomain/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/subdomain/form.tsx
new file mode 100644
index 0000000000..0aea69afbf
--- /dev/null
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/subdomain/form.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { AddEditDomainForm } from "@/ui/domains/add-edit-domain-form";
+import { useSearchParams } from "next/navigation";
+import { useOnboardingProduct } from "../../../use-onboarding-product";
+import { useOnboardingProgress } from "../../../use-onboarding-progress";
+
+export function Form() {
+ const searchParams = useSearchParams();
+ const workspaceSlug = searchParams.get("workspace") ?? "company";
+ const product = useOnboardingProduct();
+ const { continueTo } = useOnboardingProgress();
+
+ return (
+ <AddEditDomainForm
+ initialDomain={`${workspaceSlug}.dub.link`}
+ fixedDomainSuffix="dub.link"
+ enableDomainConfig={false}
+ onSuccess={() => {
+ continueTo(product === "partners" ? "program" : "plan");
+ }}
+ />
+ );
+}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/subdomain/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/subdomain/page.tsx
new file mode 100644
index 0000000000..a47105c462
--- /dev/null
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/subdomain/page.tsx
@@ -0,0 +1,18 @@
+import { BoltFill } from "@dub/ui";
+import { StepPage } from "../../step-page";
+import { Form } from "./form";
+
+export default function Subdomain() {
+ return (
+ <StepPage
+ title="Claim your free .dub.link subdomain"
+ description="Set up your branded short-link domain in one click."
+ badge={{
+ icon: BoltFill,
+ label: "Instant setup",
+ }}
+ >
+ <Form />
+ </StepPage>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx
index 1645e76e53..8f0955f9e3 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx
@@ -44,7 +44,7 @@ export default function Layout({ children }: PropsWithChildren) {
))}
</div>
- <div className="relative flex min-h-[100dvh] min-h-screen w-full flex-col items-center overflow-hidden md:justify-between">
+ <div className="relative flex min-h-[100dvh] w-full flex-col items-center overflow-hidden md:justify-between">
<div className="w-full px-4 pt-4 md:grow md:basis-0 md:px-0">
<div className="flex justify-center pt-4">
<Link href="https://dub.co/home" target="_blank" className="block">
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx
index a74f1271ed..6e70675f86 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx
@@ -117,7 +117,6 @@ export function PlanSelector({ product }: { product: OnboardingProduct }) {
</>
)}
</div>
-
{plan.name === "Enterprise" ? (
<div className="mt-4 flex items-center gap-1.5 text-neutral-400">
<CalendarRefresh className="size-4 shrink-0" />
@@ -182,8 +181,8 @@ export function PlanSelector({ product }: { product: OnboardingProduct }) {
<UpgradePlanButton
plan={plan.name.toLowerCase()}
period={period}
- text="Get started"
className="h-10 rounded-lg shadow-sm"
+ data-testid={`onboarding-plan-cta-${plan.name.toLowerCase()}`}
/>
)}
<button
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/products/product-selector.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/products/product-selector.tsx
index fd0c5c6b70..4f6a7bca25 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/products/product-selector.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/products/product-selector.tsx
@@ -1,7 +1,7 @@
"use client";
import { MarkdownDescription } from "@/ui/shared/markdown-description";
-import { Button, Crown, DubProductIcon } from "@dub/ui";
+import { Button, DubProductIcon } from "@dub/ui";
import Image from "next/image";
import { ReactNode } from "react";
import { useOnboardingProgress } from "../../use-onboarding-progress";
@@ -13,7 +13,6 @@ const products = {
href: "https://dub.co/partners",
description:
"Modern [affiliate programs](https://dub.co/partners) with [global payouts](https://dub.co/help/article/partner-payouts) and [accurate attribution](https://dub.co/help/article/program-analytics).",
- paidPlanRequired: true,
},
links: {
image: "https://assets.dub.co/icons/link.webp",
@@ -21,7 +20,6 @@ const products = {
href: "https://dub.co/links",
description:
"[Short links](https://dub.co/help/category/link-management), [QR codes](https://dub.co/help/article/custom-qr-codes), [real-time analytics](https://dub.co/help/article/dub-analytics), and [conversion tracking](https://dub.co/docs/conversions/quickstart).",
- paidPlanRequired: false,
},
};
@@ -48,7 +46,6 @@ export function ProductSelector() {
}
description={product.description}
cta={`Continue with ${product.title}`}
- paidPlanRequired={product.paidPlanRequired}
/>
))}
</div>
@@ -61,24 +58,16 @@ function ProductOption({
title,
description,
cta,
- paidPlanRequired,
}: {
product: "links" | "partners";
icon: string;
title: ReactNode;
description: string;
cta: string;
- paidPlanRequired?: boolean;
}) {
const { continueTo, isLoading, isSuccessful } = useOnboardingProgress();
return (
<div className="relative flex h-full flex-col items-center gap-6 rounded-xl border border-neutral-300 p-6 pt-12 transition-all">
- {paidPlanRequired && (
- <div className="absolute inset-x-2 top-2 flex items-center justify-center gap-2 rounded-md border border-neutral-200 bg-neutral-100 px-2.5 py-1 text-xs font-medium text-neutral-600">
- <Crown className="size-3" />
- Paid plan required
- </div>
- )}
<div className="relative size-36">
<Image
src={icon}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx
index 234a929adb..ae1231fc40 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx
@@ -156,6 +156,7 @@ export function Form() {
render={({ field }) => (
<Input
value={field.value || ""}
+ required
onChange={(e) => field.onChange(e.target.value)}
type="url"
placeholder="https://"
@@ -182,6 +183,7 @@ export function Form() {
render={({ field }) => (
<Input
value={field.value || ""}
+ required
onChange={(e) => field.onChange(e.target.value)}
type="email"
className="max-w-full"
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/success/page-client.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/success/page-client.tsx
index ec185d9940..c7c1125b03 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/success/page-client.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/success/page-client.tsx
@@ -24,8 +24,10 @@ import {
Plug2,
Users,
} from "@dub/ui";
-import { cn } from "@dub/utils";
+import { capitalize, cn } from "@dub/utils";
+import { usePlausible } from "next-plausible";
import Link from "next/link";
+import { useEffect } from "react";
import { useOnboardingProgress } from "../../use-onboarding-progress";
export function SuccessPageClient({
@@ -36,7 +38,12 @@ export function SuccessPageClient({
"name" | "slug" | "logo" | "defaultProgramId"
>;
}) {
- const { loading: isLoadingWorkspace } = useWorkspace();
+ const {
+ plan,
+ planPeriod,
+ planTier,
+ loading: isLoadingWorkspace,
+ } = useWorkspace();
const { finish, isLoading, isSuccessful } = useOnboardingProgress();
@@ -54,6 +61,19 @@ export function SuccessPageClient({
DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(pm.type),
);
+ const plausible = usePlausible();
+ useEffect(() => {
+ if (plan && plan !== "free") {
+ plausible(`Upgraded to ${capitalize(plan)}`);
+ plausible("Upgraded Plan", {
+ props: {
+ plan: capitalize(plan),
+ planPeriod: capitalize(planPeriod),
+ },
+ });
+ }
+ }, [plan]);
+
return (
<div className="mx-auto flex w-full max-w-sm flex-col items-center pb-10">
<div
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/workspace/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/workspace/page.tsx
index a1da0f42ef..9030c76af9 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/workspace/page.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/workspace/page.tsx
@@ -7,7 +7,8 @@ export default function Workspace() {
title="Create your workspace"
description={
<>
- Your shared space for links, partners, and your team.{" "}
+ Where you'll work with your team to recruit, manage, and payout your
+ partners.{" "}
<a
href="https://dub.co/help/article/what-is-a-workspace"
target="_blank"
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-product.ts b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-product.ts
index c2737940d3..2764eea217 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-product.ts
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-product.ts
@@ -3,7 +3,8 @@
import { useSearchParams } from "next/navigation";
import { useMemo } from "react";
-export const ONBOARDING_PRODUCTS = ["links", "partners"] as const;
+export const ONBOARDING_PRODUCTS = ["partners", "links"] as const;
+
export type OnboardingProduct = (typeof ONBOARDING_PRODUCTS)[number];
export function useOnboardingProduct(): OnboardingProduct {
@@ -11,7 +12,7 @@ export function useOnboardingProduct(): OnboardingProduct {
const param = searchParams.get("product");
return useMemo(
- () => ONBOARDING_PRODUCTS.find((p) => p === param) || "links",
+ () => ONBOARDING_PRODUCTS.find((p) => p === param) || "partners",
[param],
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts
index bda93f1055..3c146c6d0b 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts
@@ -5,7 +5,10 @@ import { useAction } from "next-safe-action/hooks";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
import { toast } from "sonner";
-import { useOnboardingProduct } from "./use-onboarding-product";
+import {
+ ONBOARDING_PRODUCTS,
+ useOnboardingProduct,
+} from "./use-onboarding-product";
const PRE_WORKSPACE_STEPS = ["workspace"];
@@ -42,7 +45,7 @@ export function useOnboardingProgress() {
});
const queryParams = new URLSearchParams({
- ...(product && ["links", "partners"].includes(product)
+ ...(product && ONBOARDING_PRODUCTS.includes(product)
? { product }
: {}),
...(params || {}),
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-trial-variant.ts b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-trial-variant.ts
new file mode 100644
index 0000000000..9f573c46bb
--- /dev/null
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-trial-variant.ts
@@ -0,0 +1,21 @@
+import { useSyncedLocalStorage } from "@/lib/hooks/use-synced-local-storage";
+import { useEffect } from "react";
+
+export function useOnboardingTrialVariant() {
+ const [trialVariant, setTrialVariant] = useSyncedLocalStorage<
+ "control" | "trial_d1d6f8671832d7a30e805a7fa01f968b" | undefined
+ >("dub_onboarding_trial_variant", undefined);
+
+ useEffect(() => {
+ if (trialVariant !== undefined) return;
+ setTrialVariant(
+ Math.random() > 0.5
+ ? "trial_d1d6f8671832d7a30e805a7fa01f968b"
+ : "control",
+ );
+ }, [trialVariant]);
+
+ return {
+ isTrialVariant: trialVariant === "trial_d1d6f8671832d7a30e805a7fa01f968b",
+ };
+}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx
index 6d6227be31..4c2b55add5 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx
@@ -9,7 +9,7 @@ export default function Welcome() {
<>
<TrackSignup />
<NewBackground showAnimation showGradient={false} />
- <div className="relative flex min-h-[100dvh] min-h-screen flex-col items-center justify-center">
+ <div className="relative flex min-h-[100dvh] flex-col items-center justify-center">
<div className="flex max-w-sm flex-col items-center px-4 py-16 text-center">
<div className="animate-slide-up-fade relative flex w-auto items-center justify-center px-6 py-2 [--offset:20px] [animation-duration:1.3s] [animation-fill-mode:both]">
<Gradient className="opacity-10 mix-blend-overlay" />
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/track-signup.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/track-signup.tsx
index 7cbe73d929..e9d1d37cae 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/track-signup.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/track-signup.tsx
@@ -9,7 +9,9 @@ export default function TrackSignup() {
const { data: session } = useSession();
useEffect(() => {
- plausible("Signed Up");
+ if (session?.user) {
+ plausible("Signed Up");
+ }
}, [session?.user]);
return null;
diff --git a/apps/web/app/providers.tsx b/apps/web/app/providers.tsx
index 6bbc8a6721..cc28cb9628 100644
--- a/apps/web/app/providers.tsx
+++ b/apps/web/app/providers.tsx
@@ -5,24 +5,36 @@ import { KeyboardShortcutProvider, TooltipProvider } from "@dub/ui";
import PlausibleProvider from "next-plausible";
import { ReactNode } from "react";
import { Toaster } from "sonner";
+import { useOnboardingTrialVariant } from "./app.dub.co/(onboarding)/onboarding/use-onboarding-trial-variant";
export default function RootProviders({ children }: { children: ReactNode }) {
+ const { isTrialVariant } = useOnboardingTrialVariant();
+
return (
<TooltipProvider>
- <PlausibleProvider domain="dub.co" revenue />
- <KeyboardShortcutProvider>
- <Toaster className="pointer-events-auto" closeButton />
- {children}
- <DubAnalytics
- apiHost="/_proxy/dub"
- cookieOptions={{
- domain: process.env.VERCEL === "1" ? ".dub.co" : "localhost",
- }}
- domainsConfig={{
- refer: "refer.dub.co",
- }}
- />
- </KeyboardShortcutProvider>
+ <PlausibleProvider
+ enabled
+ init={{
+ captureOnLocalhost: true,
+ customProperties: {
+ trialVariant: isTrialVariant ? "Trial" : "Control",
+ },
+ }}
+ >
+ <KeyboardShortcutProvider>
+ <Toaster className="pointer-events-auto" closeButton />
+ {children}
+ <DubAnalytics
+ apiHost="/_proxy/dub"
+ cookieOptions={{
+ domain: process.env.VERCEL === "1" ? ".dub.co" : "localhost",
+ }}
+ domainsConfig={{
+ refer: "refer.dub.co",
+ }}
+ />
+ </KeyboardShortcutProvider>
+ </PlausibleProvider>
</TooltipProvider>
);
}
diff --git a/apps/web/lib/actions/partners/accept-program-invite.ts b/apps/web/lib/actions/partners/accept-program-invite.ts
index 01838fd1ed..f19bba6246 100644
--- a/apps/web/lib/actions/partners/accept-program-invite.ts
+++ b/apps/web/lib/actions/partners/accept-program-invite.ts
@@ -43,7 +43,6 @@ export const acceptProgramInviteAction = authPartnerActionClient
},
});
- // TODO: Move these into a workflow similar to `/api/workflows/partner-approved/route.ts`
waitUntil(
(async () => {
const workspace = await prisma.project.findUnique({
diff --git a/apps/web/lib/actions/partners/bulk-approve-partners.ts b/apps/web/lib/actions/partners/bulk-approve-partners.ts
index ff912cc40d..726b40c008 100644
--- a/apps/web/lib/actions/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-approve-partners.ts
@@ -4,6 +4,7 @@ import { trackActivityLog } from "@/lib/api/activity-log/track-activity-log";
import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { triggerWorkflows } from "@/lib/cron/qstash-workflow";
+import { throwIfTrialProgramEnrollmentLimitExceeded } from "@/lib/partners/throw-if-trial-program-enrollment-exceeded";
import { bulkApprovePartnersSchema } from "@/lib/zod/schemas/partners";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
@@ -49,6 +50,13 @@ export const bulkApprovePartnersAction = authActionClient
const now = new Date();
await prisma.$transaction(async (tx) => {
+ await throwIfTrialProgramEnrollmentLimitExceeded({
+ programId: program.id,
+ additionalEnrollments: programEnrollments.length,
+ trialEndsAt: workspace.trialEndsAt,
+ tx,
+ });
+
await tx.programEnrollment.updateMany({
where: {
id: {
diff --git a/apps/web/lib/actions/partners/bulk-invite-partners.ts b/apps/web/lib/actions/partners/bulk-invite-partners.ts
index ecf1670652..c3c9cc97fd 100644
--- a/apps/web/lib/actions/partners/bulk-invite-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-invite-partners.ts
@@ -6,6 +6,7 @@ import { bulkCreateLinks } from "@/lib/api/links";
import { getGroupRewardsAndBounties } from "@/lib/api/partners/get-group-rewards-and-bounties";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { extractUtmParams } from "@/lib/api/utm/extract-utm-params";
+import { throwIfTrialProgramEnrollmentLimitExceeded } from "@/lib/partners/throw-if-trial-program-enrollment-exceeded";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import { bulkInvitePartnersSchema } from "@/lib/zod/schemas/partners";
import { sendBatchEmail } from "@dub/email";
@@ -91,14 +92,25 @@ export const bulkInvitePartnersAction = authActionClient
throw new Error("Invalid group ID provided.");
}
- const { count: createdPartnersCount } = await prisma.partner.createMany({
- data: emailsToInvite.map((email) => ({
- id: createId({ prefix: "pn_" }),
- email,
- name: email,
- })),
- skipDuplicates: true,
- });
+ const { count: createdPartnersCount } = await prisma.$transaction(
+ async (tx) => {
+ await throwIfTrialProgramEnrollmentLimitExceeded({
+ programId,
+ additionalEnrollments: emailsToInvite.length,
+ trialEndsAt: workspace.trialEndsAt,
+ tx,
+ });
+
+ return tx.partner.createMany({
+ data: emailsToInvite.map((email) => ({
+ id: createId({ prefix: "pn_" }),
+ email,
+ name: email,
+ })),
+ skipDuplicates: true,
+ });
+ },
+ );
console.log(
`Created ${createdPartnersCount} out of ${emailsToInvite.length} provided partners (${emailsToInvite.length - createdPartnersCount} already exist on Dub)`,
diff --git a/apps/web/lib/actions/partners/create-program.ts b/apps/web/lib/actions/partners/create-program.ts
index 2d322f53bd..1d9cd89214 100644
--- a/apps/web/lib/actions/partners/create-program.ts
+++ b/apps/web/lib/actions/partners/create-program.ts
@@ -17,32 +17,33 @@ import { REWARD_EVENT_COLUMN_MAPPING } from "@/lib/zod/schemas/rewards";
import { sendEmail } from "@dub/email";
import ProgramInvite from "@dub/email/templates/program-invite";
import ProgramWelcome from "@dub/email/templates/program-welcome";
+import TrialStartedEmail from "@dub/email/templates/trial/trial-started";
import { prisma } from "@dub/prisma";
import { Program, Project, User } from "@dub/prisma/client";
import { getDomainWithoutWWW, isLegacyBusinessPlan, nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { redirect } from "next/navigation";
-// Create a program from the onboarding data
export const createProgram = async ({
workspace,
user,
- redirectTo,
- sendProgramWelcomeEmail = false,
+ isProgramOnboarding = false,
}: {
workspace: Pick<
Project,
| "id"
| "slug"
+ | "logo"
+ | "name"
| "plan"
| "payoutsLimit"
+ | "trialEndsAt"
| "store"
| "webhookEnabled"
| "invoicePrefix"
>;
user: Pick<User, "id" | "email">;
- redirectTo?: string;
- sendProgramWelcomeEmail?: boolean;
+ isProgramOnboarding?: boolean;
}) => {
const { canManageProgram, canMessagePartners } = getPlanCapabilities(
workspace.plan,
@@ -238,17 +239,44 @@ export const createProgram = async ({
)
: []),
- // send email about the new program
- sendProgramWelcomeEmail &&
- sendEmail({
- subject: `Your program ${program.name} is created and ready to share with your partners.`,
- to: user.email!,
- react: ProgramWelcome({
- email: user.email!,
- workspace,
- program,
- }),
- }),
+ // for individual program onboarding flow, send ProgramWelcomeEmail
+ ...(isProgramOnboarding
+ ? [
+ sendEmail({
+ subject: `Your program ${program.name} is created and ready to share with your partners.`,
+ to: user.email!,
+ react: ProgramWelcome({
+ email: user.email!,
+ workspace,
+ program,
+ }),
+ }),
+ ]
+ : // for workspace trial, send TrialStartedEmail
+ workspace.trialEndsAt
+ ? [
+ sendEmail({
+ to: user.email!,
+ replyTo: "[email protected]",
+ subject: "Welcome to your 14-day Dub trial",
+ react: TrialStartedEmail({
+ email: user.email!,
+ plan: workspace.plan,
+ workspace: {
+ slug: workspace.slug,
+ logo: workspace.logo,
+ name: workspace.name,
+ },
+ program: {
+ slug: program.slug,
+ name: program.name,
+ logo: program.logo,
+ },
+ }),
+ variant: "marketing",
+ }),
+ ]
+ : []),
// delete the workspace product cache
redis.del(`workspace:product:${workspace.slug}`),
@@ -271,7 +299,8 @@ export const createProgram = async ({
]),
);
- if (redirectTo) redirect(redirectTo);
+ if (isProgramOnboarding)
+ redirect(`/${workspace.slug}/program?onboarded-program=true`);
};
// Invite a partner to the program
diff --git a/apps/web/lib/actions/partners/invite-partner-from-network.ts b/apps/web/lib/actions/partners/invite-partner-from-network.ts
index ba61f41e59..c0adbfa5f7 100644
--- a/apps/web/lib/actions/partners/invite-partner-from-network.ts
+++ b/apps/web/lib/actions/partners/invite-partner-from-network.ts
@@ -27,10 +27,11 @@ export const invitePartnerFromNetworkAction = authActionClient
const networkInvitesUsage = await getNetworkInvitesUsage(workspace);
- if (networkInvitesUsage >= workspace.networkInvitesLimit)
+ if (networkInvitesUsage >= workspace.networkInvitesLimit) {
throw new Error(
"You have reached your partner network invitations limit.",
);
+ }
const { partnerId, groupId } = parsedInput;
diff --git a/apps/web/lib/actions/partners/invite-partner.ts b/apps/web/lib/actions/partners/invite-partner.ts
index e359cf1bb9..477929b46b 100644
--- a/apps/web/lib/actions/partners/invite-partner.ts
+++ b/apps/web/lib/actions/partners/invite-partner.ts
@@ -4,6 +4,7 @@ import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { createAndEnrollPartner } from "@/lib/api/partners/create-and-enroll-partner";
import { getGroupRewardsAndBounties } from "@/lib/api/partners/get-group-rewards-and-bounties";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { throwIfTrialProgramEnrollmentLimitExceeded } from "@/lib/partners/throw-if-trial-program-enrollment-exceeded";
import { invitePartnerSchema } from "@/lib/zod/schemas/partners";
import { sendEmail } from "@dub/email";
import ProgramInvite from "@dub/email/templates/program-invite";
@@ -64,6 +65,11 @@ export const invitePartnerAction = authActionClient
throw new Error("No group ID provided and no default group ID found.");
}
+ await throwIfTrialProgramEnrollmentLimitExceeded({
+ programId,
+ trialEndsAt: workspace.trialEndsAt,
+ });
+
const enrolledPartner = await createAndEnrollPartner({
workspace,
program,
diff --git a/apps/web/lib/actions/partners/onboard-program.ts b/apps/web/lib/actions/partners/onboard-program.ts
index f86362017f..678d3c7737 100644
--- a/apps/web/lib/actions/partners/onboard-program.ts
+++ b/apps/web/lib/actions/partners/onboard-program.ts
@@ -30,8 +30,7 @@ export const onboardProgramAction = authActionClient
await createProgram({
workspace,
user,
- redirectTo: `/${workspace.slug}/program?onboarded-program=true`,
- sendProgramWelcomeEmail: true,
+ isProgramOnboarding: true,
});
return;
}
diff --git a/apps/web/lib/api/campaigns/pause-campaigns-on-plan-downgrade.ts b/apps/web/lib/api/campaigns/pause-campaigns-on-plan-downgrade.ts
new file mode 100644
index 0000000000..2e6686750e
--- /dev/null
+++ b/apps/web/lib/api/campaigns/pause-campaigns-on-plan-downgrade.ts
@@ -0,0 +1,84 @@
+import { scheduleTransactionalCampaign } from "@/lib/api/campaigns/schedule-campaigns";
+import { qstash } from "@/lib/cron";
+import { prisma } from "@dub/prisma";
+import { CampaignStatus, CampaignType } from "@dub/prisma/client";
+
+export async function pauseOrCancelCampaignsForProgramOnPlanDowngrade({
+ programId,
+}: {
+ programId: string;
+}): Promise<void> {
+ const marketingCampaigns = await prisma.campaign.findMany({
+ where: {
+ programId,
+ type: CampaignType.marketing,
+ status: {
+ in: [CampaignStatus.scheduled, CampaignStatus.sending],
+ },
+ },
+ });
+
+ for (const campaign of marketingCampaigns) {
+ let qstashDeleteSucceeded = !campaign.qstashMessageId;
+
+ if (campaign.qstashMessageId) {
+ try {
+ await qstash.messages.delete(campaign.qstashMessageId);
+ qstashDeleteSucceeded = true;
+ } catch (error) {
+ console.warn(
+ `Failed to delete QStash message ${campaign.qstashMessageId} for campaign ${campaign.id}:`,
+ error,
+ );
+ }
+ }
+
+ await prisma.campaign.update({
+ where: { id: campaign.id },
+ data: {
+ status: CampaignStatus.canceled,
+ ...(qstashDeleteSucceeded ? { qstashMessageId: null } : {}),
+ },
+ });
+ }
+
+ const transactionalCampaigns = await prisma.campaign.findMany({
+ where: {
+ programId,
+ type: CampaignType.transactional,
+ status: CampaignStatus.active,
+ },
+ include: {
+ workflow: true,
+ },
+ });
+
+ for (const campaign of transactionalCampaigns) {
+ try {
+ const updatedCampaign = await prisma.$transaction(async (tx) => {
+ if (campaign.workflowId) {
+ await tx.workflow.update({
+ where: { id: campaign.workflowId },
+ data: { disabledAt: new Date() },
+ });
+ }
+
+ return tx.campaign.update({
+ where: { id: campaign.id },
+ data: { status: CampaignStatus.paused },
+ include: { workflow: true },
+ });
+ });
+
+ await scheduleTransactionalCampaign({
+ campaign,
+ updatedCampaign,
+ });
+ } catch (error) {
+ console.warn(
+ `Failed to pause transactional campaign ${campaign.id} on plan downgrade:`,
+ error,
+ );
+ }
+ }
+}
diff --git a/apps/web/lib/api/domains/claim-dot-link-domain.ts b/apps/web/lib/api/domains/claim-dot-link-domain.ts
index 5dc11ff5f5..f1322f7c52 100644
--- a/apps/web/lib/api/domains/claim-dot-link-domain.ts
+++ b/apps/web/lib/api/domains/claim-dot-link-domain.ts
@@ -5,7 +5,7 @@ import { WorkspaceWithUsers } from "@/lib/types";
import { sendBatchEmail } from "@dub/email";
import DomainClaimed from "@dub/email/templates/domain-claimed";
import { prisma } from "@dub/prisma";
-import { DEFAULT_LINK_PROPS } from "@dub/utils";
+import { DEFAULT_LINK_PROPS, isWorkspaceBillingTrialActive } from "@dub/utils";
import { get } from "@vercel/edge-config";
import { waitUntil } from "@vercel/functions";
import { addDomainToVercel } from "./add-domain-vercel";
@@ -33,7 +33,8 @@ export async function claimDotLinkDomain({
if (!workspace.stripeId) {
throw new DubApiError({
code: "forbidden",
- message: "You cannot register a .link domain on a free trial.",
+ message:
+ "You cannot register a .link domain until you add a payment method.",
});
}
@@ -45,6 +46,13 @@ export async function claimDotLinkDomain({
}
}
+ if (isWorkspaceBillingTrialActive(workspace.trialEndsAt)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You cannot register a .link domain during your free trial.",
+ });
+ }
+
const customDomainTerms = await get("customDomainTerms");
if (customDomainTerms && Array.isArray(customDomainTerms)) {
diff --git a/apps/web/lib/api/get-ratelimit-for-plan.ts b/apps/web/lib/api/get-ratelimit-for-plan.ts
index 2e4a87ae19..2c7c98491e 100644
--- a/apps/web/lib/api/get-ratelimit-for-plan.ts
+++ b/apps/web/lib/api/get-ratelimit-for-plan.ts
@@ -1,8 +1,27 @@
-import { FREE_PLAN, PLANS } from "@dub/utils";
+import {
+ FREE_PLAN,
+ PLANS,
+ TRIAL_LIMITS,
+ isWorkspaceBillingTrialActive,
+} from "@dub/utils";
-export const getRatelimitForPlan = (plan: string) => {
+export const getRatelimitForPlan = (
+ plan: string,
+ options?: { trialEndsAt?: Date | null },
+) => {
const currentPlanName = plan.toLowerCase().split(" ")[0]; // to account for old Business plans (e.g. "Business Plus")
- return (
- PLANS.find((p) => p.name.toLowerCase() === currentPlanName) || FREE_PLAN
- );
+ const base =
+ PLANS.find((p) => p.name.toLowerCase() === currentPlanName) || FREE_PLAN;
+
+ if (isWorkspaceBillingTrialActive(options?.trialEndsAt)) {
+ return {
+ ...base,
+ limits: {
+ ...base.limits,
+ api: TRIAL_LIMITS.api,
+ analyticsApi: TRIAL_LIMITS.analyticsApi,
+ },
+ };
+ }
+ return base;
};
diff --git a/apps/web/lib/api/partners/strip-advanced-reward-modifiers.ts b/apps/web/lib/api/partners/strip-advanced-reward-modifiers.ts
new file mode 100644
index 0000000000..e89f9f4b1a
--- /dev/null
+++ b/apps/web/lib/api/partners/strip-advanced-reward-modifiers.ts
@@ -0,0 +1,20 @@
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+
+export async function stripAdvancedRewardModifiersForProgram({
+ programId,
+}: {
+ programId: string;
+}): Promise<void> {
+ await prisma.reward.updateMany({
+ where: {
+ programId,
+ modifiers: {
+ not: Prisma.DbNull,
+ },
+ },
+ data: {
+ modifiers: Prisma.DbNull,
+ },
+ });
+}
diff --git a/apps/web/lib/auth/token-cache.ts b/apps/web/lib/auth/token-cache.ts
index 7f24886615..a97159155c 100644
--- a/apps/web/lib/auth/token-cache.ts
+++ b/apps/web/lib/auth/token-cache.ts
@@ -20,6 +20,7 @@ const tokenCacheItemSchema = z.object({
project: z
.object({
plan: z.string().nullish(),
+ trialEndsAt: z.coerce.date().nullish(),
})
.nullish(),
installationId: z.string().nullish(),
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index 3380c1f858..674dfd0494 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -194,6 +194,7 @@ export const withWorkspace = (
project: {
select: {
plan: true,
+ trialEndsAt: true,
},
},
}),
@@ -239,7 +240,9 @@ export const withWorkspace = (
? "1 s"
: "1 m";
- const planLimit = getRatelimitForPlan(token.project?.plan || "free");
+ const planLimit = getRatelimitForPlan(token.project?.plan || "free", {
+ trialEndsAt: token.project?.trialEndsAt ?? null,
+ });
limit = planLimit.limits[isAnalytics ? "analyticsApi" : "api"];
const { success, headers } = await rateLimitRequest({
diff --git a/apps/web/lib/edge-config/get-feature-flags.ts b/apps/web/lib/edge-config/get-feature-flags.ts
index 95d219d69b..ce05812779 100644
--- a/apps/web/lib/edge-config/get-feature-flags.ts
+++ b/apps/web/lib/edge-config/get-feature-flags.ts
@@ -10,7 +10,7 @@ export const getFeatureFlags = async ({
}: {
workspaceId?: string;
workspaceSlug?: string;
-}) => {
+}): Promise<Record<BetaFeatures, boolean>> => {
if (workspaceId) {
workspaceId = prefixWorkspaceId(workspaceId);
}
@@ -23,7 +23,7 @@ export const getFeatureFlags = async ({
// return all features as true if edge config is not available
return Object.fromEntries(
Object.entries(workspaceFeatures).map(([key, _v]) => [key, true]),
- );
+ ) as Record<BetaFeatures, boolean>;
} else if (!workspaceId && !workspaceSlug) {
return workspaceFeatures;
}
diff --git a/apps/web/lib/email/render-trial-email.tsx b/apps/web/lib/email/render-trial-email.tsx
new file mode 100644
index 0000000000..f796826913
--- /dev/null
+++ b/apps/web/lib/email/render-trial-email.tsx
@@ -0,0 +1,27 @@
+import {
+ TRIAL_EMAIL_TYPE,
+ type TrialEmailType,
+} from "@/lib/email/trial-email-schedule";
+import Trial3DaysRemainingEmail from "@dub/email/templates/trial/trial-3-days-remaining";
+import Trial7DaysRemainingEmail from "@dub/email/templates/trial/trial-7-days-remaining";
+
+export function renderTrialEmail(
+ type: TrialEmailType,
+ props: {
+ email: string;
+ name: string | null;
+ plan: string;
+ workspaceSlug: string;
+ },
+) {
+ switch (type) {
+ case TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING:
+ return Trial7DaysRemainingEmail(props);
+ case TRIAL_EMAIL_TYPE.THREE_DAYS_REMAINING:
+ return Trial3DaysRemainingEmail(props);
+ default: {
+ const _exhaustive: never = type;
+ return _exhaustive;
+ }
+ }
+}
diff --git a/apps/web/lib/email/run-trial-email-cron.ts b/apps/web/lib/email/run-trial-email-cron.ts
new file mode 100644
index 0000000000..5ddea0ef77
--- /dev/null
+++ b/apps/web/lib/email/run-trial-email-cron.ts
@@ -0,0 +1,217 @@
+import { renderTrialEmail } from "@/lib/email/render-trial-email";
+import {
+ getDueTrialEmailTypes,
+ getTrialEmailSubject,
+} from "@/lib/email/trial-email-schedule";
+import { sendBatchEmail as defaultSendBatchEmail } from "@dub/email";
+import type { PrismaClient } from "@dub/prisma/client";
+import { chunk, log } from "@dub/utils";
+import { createHash } from "crypto";
+
+const CRON_BATCH_SIZE = 50;
+const EMAIL_BATCH_SIZE = 100;
+
+export type RunTrialEmailCronResult = {
+ sentCount: number;
+ workspaceCount: number;
+ hasMore: boolean;
+ nextStartingAfter?: string;
+};
+
+/** Only the Prisma methods this cron uses (easy to mock in tests). */
+export type TrialEmailCronPrisma = {
+ project: Pick<PrismaClient["project"], "findMany">;
+ sentEmail: Pick<PrismaClient["sentEmail"], "create">;
+};
+
+type SendBatchEmail = typeof defaultSendBatchEmail;
+
+function dedupeRecipients(
+ users: { user: { email: string | null; name: string | null } }[],
+): { email: string; name: string | null }[] {
+ const byEmail = new Map<string, { email: string; name: string | null }>();
+
+ for (const { user } of users) {
+ if (!user.email) {
+ continue;
+ }
+
+ const key = user.email.toLowerCase();
+ if (!byEmail.has(key)) {
+ byEmail.set(key, { email: user.email, name: user.name });
+ }
+ }
+
+ return [...byEmail.values()].sort((a, b) =>
+ a.email.toLowerCase().localeCompare(b.email.toLowerCase()),
+ );
+}
+
+export async function runTrialEmailCron({
+ now,
+ prisma,
+ startingAfter,
+ sendBatchEmail = defaultSendBatchEmail,
+}: {
+ now: Date;
+ prisma: TrialEmailCronPrisma;
+ startingAfter?: string;
+ sendBatchEmail?: SendBatchEmail;
+}): Promise<RunTrialEmailCronResult> {
+ const workspaces = await prisma.project.findMany({
+ where: {
+ trialEndsAt: {
+ gt: now,
+ },
+ plan: {
+ not: "free",
+ },
+ },
+ take: CRON_BATCH_SIZE,
+ skip: startingAfter ? 1 : 0,
+ ...(startingAfter && {
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ orderBy: {
+ id: "asc",
+ },
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ plan: true,
+ trialEndsAt: true,
+ programs: {
+ select: {
+ name: true,
+ },
+ },
+ sentEmails: {
+ select: {
+ type: true,
+ },
+ },
+ users: {
+ where: {
+ user: {
+ isMachine: false,
+ },
+ },
+ select: {
+ user: {
+ select: {
+ email: true,
+ name: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const hasMore = workspaces.length === CRON_BATCH_SIZE;
+ const nextStartingAfter = hasMore
+ ? workspaces[workspaces.length - 1]?.id
+ : undefined;
+
+ let sentCount = 0;
+
+ for (const workspace of workspaces) {
+ const trialEndsAt = workspace.trialEndsAt;
+ if (!trialEndsAt) {
+ continue;
+ }
+
+ const recipients = dedupeRecipients(workspace.users);
+ if (recipients.length === 0) {
+ continue;
+ }
+
+ const sent = new Set(workspace.sentEmails.map((s) => s.type));
+ const due = getDueTrialEmailTypes({
+ trialEndsAt,
+ sent,
+ now,
+ });
+ if (due.length === 0) {
+ continue;
+ }
+
+ for (const type of due) {
+ const payloads = recipients.map((recipient) => ({
+ to: recipient.email,
+ replyTo: "[email protected]",
+ subject: getTrialEmailSubject({
+ type,
+ companyName: workspace.programs?.[0]?.name ?? workspace.name,
+ }),
+ react: renderTrialEmail(type, {
+ email: recipient.email,
+ name: recipient.name,
+ plan: workspace.plan,
+ workspaceSlug: workspace.slug,
+ }),
+ variant: "marketing" as const,
+ }));
+
+ let groupFailed = false;
+ const batches = chunk(payloads, EMAIL_BATCH_SIZE);
+ for (const batch of batches) {
+ const batchKey = createHash("sha256")
+ .update(
+ batch
+ .map(({ to }) => to.toLowerCase())
+ .sort()
+ .join(","),
+ )
+ .digest("hex");
+ const idempotencyKey = `trial-emails/${workspace.id}/${type}/${batchKey}`;
+
+ try {
+ const { error } = await sendBatchEmail(batch, { idempotencyKey });
+ if (error) {
+ groupFailed = true;
+ await log({
+ message: `Failed to send trial email batch *${type}* for workspace ${workspace.id}: ${String(error)}`,
+ type: "errors",
+ });
+ break;
+ }
+ } catch (error) {
+ groupFailed = true;
+ await log({
+ message: `Failed to send trial email batch *${type}* for workspace ${workspace.id}: ${error instanceof Error ? error.message : String(error)}`,
+ type: "errors",
+ });
+ break;
+ }
+ }
+
+ if (!groupFailed) {
+ try {
+ await prisma.sentEmail.create({
+ data: {
+ projectId: workspace.id,
+ type,
+ },
+ });
+ sentCount += payloads.length;
+ } catch (error) {
+ await log({
+ message: `Failed to record SentEmail for *${type}* workspace ${workspace.id}: ${error instanceof Error ? error.message : String(error)}`,
+ type: "errors",
+ });
+ }
+ }
+ }
+ }
+
+ return {
+ sentCount,
+ workspaceCount: workspaces.length,
+ hasMore,
+ ...(nextStartingAfter ? { nextStartingAfter } : {}),
+ };
+}
diff --git a/apps/web/lib/email/trial-email-schedule.ts b/apps/web/lib/email/trial-email-schedule.ts
new file mode 100644
index 0000000000..08e1614d2a
--- /dev/null
+++ b/apps/web/lib/email/trial-email-schedule.ts
@@ -0,0 +1,83 @@
+export const TRIAL_EMAIL_TYPE = {
+ SEVEN_DAYS_REMAINING: "trial7DaysRemaining",
+ THREE_DAYS_REMAINING: "trial3DaysRemaining",
+} as const;
+
+export type TrialEmailType =
+ (typeof TRIAL_EMAIL_TYPE)[keyof typeof TRIAL_EMAIL_TYPE];
+
+export const ALL_TRIAL_EMAIL_TYPES: TrialEmailType[] = [
+ TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING,
+ TRIAL_EMAIL_TYPE.THREE_DAYS_REMAINING,
+];
+
+function utcCalendarDate(d: Date): Date {
+ return new Date(
+ Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()),
+ );
+}
+
+function differenceInCalendarDaysUTC(left: Date, right: Date): number {
+ const l = utcCalendarDate(left).getTime();
+ const r = utcCalendarDate(right).getTime();
+ return Math.round((l - r) / (24 * 60 * 60 * 1000));
+}
+const COUNTDOWN_GRACE_DAYS = 1;
+
+export function getDueTrialEmailTypes({
+ trialEndsAt,
+ sent,
+ now,
+}: {
+ trialEndsAt: Date;
+ sent: Set<string>;
+ now: Date;
+}): TrialEmailType[] {
+ const due: TrialEmailType[] = [];
+
+ if (now.getTime() > trialEndsAt.getTime()) {
+ return due;
+ }
+
+ const daysUntilEnd = differenceInCalendarDaysUTC(trialEndsAt, now);
+
+ const tryAdd = (type: TrialEmailType) => {
+ if (!sent.has(type) && !due.includes(type)) {
+ due.push(type);
+ }
+ };
+
+ if (
+ daysUntilEnd <= 7 &&
+ daysUntilEnd >= 7 - COUNTDOWN_GRACE_DAYS &&
+ daysUntilEnd >= 0
+ ) {
+ tryAdd(TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING);
+ }
+ if (
+ daysUntilEnd <= 3 &&
+ daysUntilEnd >= 3 - COUNTDOWN_GRACE_DAYS &&
+ daysUntilEnd >= 0
+ ) {
+ tryAdd(TRIAL_EMAIL_TYPE.THREE_DAYS_REMAINING);
+ }
+
+ return due;
+}
+
+export function getTrialEmailSubject({
+ type,
+ companyName,
+}: {
+ type: TrialEmailType;
+ companyName?: string;
+}): string {
+ const prefix =
+ companyName && companyName.length <= 12 ? `Dub + ${companyName}: ` : "";
+
+ const subjects: Record<TrialEmailType, string> = {
+ [TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING]: `${prefix}Mid-trial check-in`,
+ [TRIAL_EMAIL_TYPE.THREE_DAYS_REMAINING]: `${prefix}3 days left in trial`,
+ };
+ return subjects[type];
+}
diff --git a/apps/web/lib/onboarding/types.ts b/apps/web/lib/onboarding/types.ts
index 639d276f5e..e4a82ef0e6 100644
--- a/apps/web/lib/onboarding/types.ts
+++ b/apps/web/lib/onboarding/types.ts
@@ -3,6 +3,7 @@ export const ONBOARDING_STEPS = [
"products",
"domain",
"domain/custom",
+ "domain/subdomain",
"domain/register",
"program",
"program/reward",
diff --git a/apps/web/lib/partners/approve-partner-enrollment.ts b/apps/web/lib/partners/approve-partner-enrollment.ts
index 0ee3726c9d..f714f86cea 100644
--- a/apps/web/lib/partners/approve-partner-enrollment.ts
+++ b/apps/web/lib/partners/approve-partner-enrollment.ts
@@ -3,6 +3,7 @@ import { waitUntil } from "@vercel/functions";
import { trackActivityLog } from "../api/activity-log/track-activity-log";
import { getGroupOrThrow } from "../api/groups/get-group-or-throw";
import { triggerWorkflows } from "../cron/qstash-workflow";
+import { throwIfTrialProgramEnrollmentLimitExceeded } from "./throw-if-trial-program-enrollment-exceeded";
export async function approvePartnerEnrollment({
programId,
@@ -36,6 +37,12 @@ export async function approvePartnerEnrollment({
});
const programEnrollment = await prisma.$transaction(async (tx) => {
+ await throwIfTrialProgramEnrollmentLimitExceeded({
+ programId,
+ trialEndsAt: program.workspace.trialEndsAt,
+ tx,
+ });
+
const enrollment = await tx.programEnrollment.update({
where: {
partnerId_programId: {
diff --git a/apps/web/lib/partners/throw-if-trial-program-enrollment-exceeded.ts b/apps/web/lib/partners/throw-if-trial-program-enrollment-exceeded.ts
new file mode 100644
index 0000000000..221cde4124
--- /dev/null
+++ b/apps/web/lib/partners/throw-if-trial-program-enrollment-exceeded.ts
@@ -0,0 +1,46 @@
+import { DubApiError } from "@/lib/api/errors";
+import { prisma } from "@dub/prisma";
+import type { Prisma } from "@dub/prisma/client";
+import {
+ isWorkspaceBillingTrialActive,
+ TRIAL_PROGRAM_ENROLLMENT_LIMIT,
+} from "@dub/utils";
+
+/**
+ * Limits total enrollments per program while the workspace billing trial is active.
+ * Pass `trialEndsAt` from an already-loaded workspace so non-trial paths skip the count query.
+ * Pass `tx` when calling inside `prisma.$transaction` so the count and enrollment write are atomic.
+ */
+export async function throwIfTrialProgramEnrollmentLimitExceeded({
+ programId,
+ additionalEnrollments = 1,
+ trialEndsAt,
+ tx,
+}: {
+ programId: string;
+ additionalEnrollments?: number;
+ trialEndsAt: Date | null | undefined;
+ tx?: Prisma.TransactionClient;
+}) {
+ if (!isWorkspaceBillingTrialActive(trialEndsAt)) {
+ return;
+ }
+
+ const db = tx ?? prisma;
+
+ const totalEnrollments = await db.programEnrollment.count({
+ where: {
+ programId,
+ },
+ });
+
+ if (
+ totalEnrollments + additionalEnrollments >
+ TRIAL_PROGRAM_ENROLLMENT_LIMIT
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: `During your free trial you can have at most ${TRIAL_PROGRAM_ENROLLMENT_LIMIT} partners in your program. Start a paid plan to add more.`,
+ });
+ }
+}
diff --git a/apps/web/lib/plans/would-lose-advanced-features.ts b/apps/web/lib/plans/would-lose-advanced-features.ts
new file mode 100644
index 0000000000..3a72a6864d
--- /dev/null
+++ b/apps/web/lib/plans/would-lose-advanced-features.ts
@@ -0,0 +1,12 @@
+export function wouldLoseAdvancedFeatures({
+ currentPlan,
+ newPlan,
+}: {
+ currentPlan: string;
+ newPlan: string;
+}): boolean {
+ return (
+ currentPlan.toLowerCase() === "advanced" &&
+ newPlan.toLowerCase() !== "advanced"
+ );
+}
diff --git a/apps/web/lib/stripe/workspace-subscription-fields.ts b/apps/web/lib/stripe/workspace-subscription-fields.ts
new file mode 100644
index 0000000000..1a018de22f
--- /dev/null
+++ b/apps/web/lib/stripe/workspace-subscription-fields.ts
@@ -0,0 +1,53 @@
+import type Stripe from "stripe";
+
+/**
+ * Derives workspace `trialEndsAt` from a Stripe subscription (platform billing).
+ */
+export function getSubscriptionTrialEndsAt(
+ subscription?: Pick<Stripe.Subscription, "status" | "trial_end">,
+): Date | null | undefined {
+ if (!subscription) {
+ return undefined;
+ }
+ if (subscription.status === "trialing" && subscription.trial_end) {
+ return new Date(subscription.trial_end * 1000);
+ }
+ return null;
+}
+
+/**
+ * Derives `subscriptionCanceledAt` and `billingCycleEndsAt` from Stripe.
+ * When cancel-at-period-end is set, `subscriptionCanceledAt` uses Stripe's Unix
+ * timestamps (`cancel_at`, then `canceled_at`) so the value is stable across webhooks.
+ * `billingCycleEndsAt` uses subscription item `current_period_end` (Basil API).
+ */
+export function getSubscriptionCancellationFields(
+ subscription?: Pick<
+ Stripe.Subscription,
+ "cancel_at_period_end" | "cancel_at" | "canceled_at" | "items"
+ >,
+): {
+ subscriptionCanceledAt: Date | null;
+ billingCycleEndsAt: Date | null;
+} {
+ if (!subscription) {
+ return {
+ subscriptionCanceledAt: null,
+ billingCycleEndsAt: null,
+ };
+ }
+ const cancelAtPeriodEnd = subscription.cancel_at_period_end ?? false;
+ const currentPeriodEnd = subscription.items.data[0]?.current_period_end;
+ const cancelAtUnix =
+ subscription.cancel_at ?? subscription.canceled_at ?? null;
+ return {
+ subscriptionCanceledAt:
+ cancelAtPeriodEnd && cancelAtUnix != null
+ ? new Date(Number(cancelAtUnix) * 1000)
+ : null,
+ billingCycleEndsAt:
+ currentPeriodEnd != null
+ ? new Date(Number(currentPeriodEnd) * 1000)
+ : null,
+ };
+}
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 7ea0a99494..98a927fa7d 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -1,5 +1,5 @@
import { workspaceSiteVisitTrackingSettingsFieldSchema } from "@/lib/sitemaps/site-visit-tracking";
-import { WorkspaceRole } from "@dub/prisma/client";
+import { PlanPeriod, WorkspaceRole } from "@dub/prisma/client";
import { DEFAULT_REDIRECTS, RESERVED_SLUGS, validSlugRegex } from "@dub/utils";
import slugify from "@sindresorhus/slugify";
import * as z from "zod/v4";
@@ -38,7 +38,31 @@ export const WorkspaceSchema = z
.number()
.nullable()
.describe("The tier of the workspace's plan."),
+ planPeriod: z
+ .enum(PlanPeriod)
+ .nullish()
+ .describe(
+ "Billing cadence for the Stripe subscription (monthly, yearly, quarterly, biweekly), when applicable.",
+ ),
stripeId: z.string().nullable().describe("The Stripe ID of the workspace."),
+ trialEndsAt: z
+ .date()
+ .nullish()
+ .describe(
+ "When the current Stripe subscription billing trial ends, if applicable.",
+ ),
+ subscriptionCanceledAt: z
+ .date()
+ .nullish()
+ .describe(
+ "When the workspace's subscription was canceled (or set to cancel).",
+ ),
+ billingCycleEndsAt: z
+ .date()
+ .nullish()
+ .describe(
+ "When the current Stripe subscription period ends (derived from Stripe current_period_end).",
+ ),
billingCycleStart: z
.number()
.describe(
diff --git a/apps/web/next.config.js b/apps/web/next.config.js
index a34ca9b29f..6a9352d9bf 100644
--- a/apps/web/next.config.js
+++ b/apps/web/next.config.js
@@ -1,4 +1,5 @@
const { PrismaPlugin } = require("@prisma/nextjs-monorepo-workaround-plugin");
+const { withPlausibleProxy } = require("next-plausible");
// Suppress specific external package warnings
const originalConsoleWarn = console.warn;
@@ -18,7 +19,11 @@ console.warn = (...args) => {
};
/** @type {import('next').NextConfig} */
-module.exports = {
+module.exports = withPlausibleProxy({
+ src: "https://plausible.io/js/pa-T9BPIqC3D0XQFZnP1vHfN.js",
+ scriptPath: "/_proxy/plausible/script.js",
+ apiPath: "/_proxy/plausible/event",
+})({
reactStrictMode: false,
transpilePackages: [
"prettier",
@@ -199,9 +204,13 @@ module.exports = {
return [
// for dub proxy
{
- source: "/_proxy/dub/track/click",
- destination: "https://api.dub.co/track/click",
+ source: "/_proxy/dub/script.js",
+ destination: "https://www.dubcdn.com/analytics/script.js",
+ },
+ {
+ source: "/_proxy/dub/track/:path*",
+ destination: "https://api.dub.co/track/:path*",
},
];
},
-};
+});
diff --git a/apps/web/package.json b/apps/web/package.json
index 9d8263e0dd..9a8cff376d 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -107,7 +107,7 @@
"nanoid": "^5.0.1",
"next": "15.5.8",
"next-auth": "4.24.11",
- "next-plausible": "^3.12.0",
+ "next-plausible": "^4.0.0",
"next-safe-action": "^8.0.11",
"node-html-parser": "^6.1.4",
"openapi-types": "^12.1.3",
diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts
index 9cb1707426..aad4e8abcf 100644
--- a/apps/web/playwright.config.ts
+++ b/apps/web/playwright.config.ts
@@ -1,3 +1,5 @@
+import "dotenv-flow/config";
+
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
@@ -39,6 +41,9 @@ export default defineConfig({
{
name: "workspace-setup",
testMatch: /workspaces\/auth\.setup\.ts/,
+ use: {
+ baseURL: "http://app.localhost:8888",
+ },
},
{
name: "workspaces",
@@ -48,9 +53,20 @@ export default defineConfig({
storageState: "playwright/.auth/workspace.json",
},
testDir: "./playwright/workspaces",
- testIgnore: /auth\.setup\.ts/,
+ testIgnore: /auth\.setup\.ts|billing-trial\.spec\.ts/,
dependencies: ["workspace-setup"],
},
+ // Billing tests — runs after workspace onboarding so the workspace exists
+ {
+ name: "chromium-workspace",
+ testMatch: /workspaces\/billing-trial\.spec\.ts/,
+ use: {
+ ...devices["Desktop Chrome"],
+ storageState: "playwright/.auth/workspace.json",
+ baseURL: "http://app.localhost:8888",
+ },
+ dependencies: ["workspaces"],
+ },
],
webServer: process.env.CI
? {
diff --git a/apps/web/playwright/workspaces/auth.setup.ts b/apps/web/playwright/workspaces/auth.setup.ts
index 428547239f..3dd239a049 100644
--- a/apps/web/playwright/workspaces/auth.setup.ts
+++ b/apps/web/playwright/workspaces/auth.setup.ts
@@ -11,7 +11,7 @@ test("sign up new user for workspace onboarding", async ({ page }) => {
const email = `${nanoid(10)}@dub-internal-test.com`;
// Go to registration page on the app subdomain
- await page.goto(`http://app.localhost:8888/register`);
+ await page.goto("http://app.localhost:8888/register");
// Step 1: Enter email and reveal password field
await page.locator('input[name="email"]').fill(email);
diff --git a/apps/web/playwright/workspaces/billing-mocks.ts b/apps/web/playwright/workspaces/billing-mocks.ts
new file mode 100644
index 0000000000..0458125237
--- /dev/null
+++ b/apps/web/playwright/workspaces/billing-mocks.ts
@@ -0,0 +1,262 @@
+import "dotenv-flow/config";
+
+import { prisma } from "@dub/prisma";
+import type { Prisma } from "@dub/prisma/client";
+import {
+ BUSINESS_PLAN,
+ DUB_TRIAL_PERIOD_DAYS,
+ getWorkspaceLimitsForStripeSubscriptionStatus,
+} from "@dub/utils";
+import type { Page, Request } from "@playwright/test";
+
+const MOCK_CHECKOUT_SESSION_ID = "cs_test_e2e_mock_session";
+
+/** Synthetic path used in the browser before Hosted Checkout is mocked (see redirectToCheckout stub). */
+const MOCK_CHECKOUT_PATH_TOKEN = "cs_test_e2e_redirect";
+
+/**
+ * Ensures `window.Stripe` short-circuits @stripe/stripe-js and redirects to our mock checkout URL.
+ * Call again immediately before clicking "Start trial" if anything may have replaced `window.Stripe`.
+ */
+export async function patchStripeRedirectStubForE2E(page: Page) {
+ await page.evaluate((pathToken) => {
+ const w = window as Window & { Stripe?: unknown };
+ w.Stripe = function Stripe() {
+ return {
+ redirectToCheckout(opts: { sessionId?: string }) {
+ const id = opts?.sessionId ? String(opts.sessionId) : "";
+ window.location.href = `https://checkout.stripe.com/c/pay/${pathToken}#${encodeURIComponent(id)}`;
+ },
+ };
+ };
+ }, MOCK_CHECKOUT_PATH_TOKEN);
+}
+
+function parseBillingUpgradeCheckoutContext(req: Request): {
+ onboarding: boolean;
+ plan: string;
+ period: string;
+} {
+ try {
+ const raw = req.postData();
+ if (!raw) {
+ return { onboarding: false, plan: "business", period: "monthly" };
+ }
+ const body = JSON.parse(raw) as {
+ onboarding?: string | boolean;
+ plan?: string;
+ period?: string;
+ };
+ const onboarding = body.onboarding === true || body.onboarding === "true";
+ return {
+ onboarding,
+ plan: typeof body.plan === "string" ? body.plan : "business",
+ period: typeof body.period === "string" ? body.period : "monthly",
+ };
+ } catch {
+ return { onboarding: false, plan: "business", period: "monthly" };
+ }
+}
+
+/** Columns overwritten by {@link applyMockTrialToWorkspace} — snapshot/restore must stay in sync. */
+const mockTrialWorkspaceColumns = {
+ plan: true,
+ subscriptionCanceledAt: true,
+ billingCycleEndsAt: true,
+ planTier: true,
+ planPeriod: true,
+ trialEndsAt: true,
+ billingCycleStart: true,
+ stripeId: true,
+ usageLimit: true,
+ linksLimit: true,
+ payoutsLimit: true,
+ domainsLimit: true,
+ aiLimit: true,
+ tagsLimit: true,
+ foldersLimit: true,
+ groupsLimit: true,
+ networkInvitesLimit: true,
+ usersLimit: true,
+ paymentFailedAt: true,
+} as const;
+
+export type BillingMockTrialWorkspaceSnapshot = Prisma.ProjectGetPayload<{
+ select: typeof mockTrialWorkspaceColumns;
+}>;
+
+export async function captureWorkspaceBillingTrialSnapshot(
+ slug: string,
+): Promise<BillingMockTrialWorkspaceSnapshot> {
+ return prisma.project.findUniqueOrThrow({
+ where: { slug },
+ select: mockTrialWorkspaceColumns,
+ });
+}
+
+export async function restoreWorkspaceBillingTrialSnapshot(
+ slug: string,
+ snapshot: BillingMockTrialWorkspaceSnapshot,
+): Promise<void> {
+ await prisma.project.update({
+ where: { slug },
+ data: {
+ plan: snapshot.plan,
+ subscriptionCanceledAt: snapshot.subscriptionCanceledAt,
+ billingCycleEndsAt: snapshot.billingCycleEndsAt,
+ planTier: snapshot.planTier,
+ planPeriod: snapshot.planPeriod,
+ trialEndsAt: snapshot.trialEndsAt,
+ billingCycleStart: snapshot.billingCycleStart,
+ stripeId: snapshot.stripeId,
+ usageLimit: snapshot.usageLimit,
+ linksLimit: snapshot.linksLimit,
+ payoutsLimit: snapshot.payoutsLimit,
+ domainsLimit: snapshot.domainsLimit,
+ aiLimit: snapshot.aiLimit,
+ tagsLimit: snapshot.tagsLimit,
+ foldersLimit: snapshot.foldersLimit,
+ groupsLimit: snapshot.groupsLimit,
+ networkInvitesLimit: snapshot.networkInvitesLimit,
+ usersLimit: snapshot.usersLimit,
+ paymentFailedAt: snapshot.paymentFailedAt,
+ },
+ });
+}
+
+/**
+ * Writes trialing Business state directly to the DB (mock path — no Stripe API or webhooks).
+ */
+export async function applyMockTrialToWorkspace(slug: string) {
+ const limits = getWorkspaceLimitsForStripeSubscriptionStatus({
+ planLimits: BUSINESS_PLAN.limits,
+ subscriptionStatus: "trialing",
+ });
+
+ const trialEndsAt = new Date();
+ trialEndsAt.setDate(trialEndsAt.getDate() + DUB_TRIAL_PERIOD_DAYS);
+
+ await prisma.project.update({
+ where: { slug },
+ data: {
+ plan: "business",
+ subscriptionCanceledAt: null,
+ billingCycleEndsAt: null,
+ planTier: 1,
+ planPeriod: "monthly",
+ trialEndsAt,
+ billingCycleStart: new Date().getDate(),
+ stripeId: `cus_e2e_mock_${slug}`,
+ usageLimit: limits.clicks,
+ linksLimit: limits.links,
+ payoutsLimit: limits.payouts,
+ domainsLimit: limits.domains,
+ aiLimit: limits.ai,
+ tagsLimit: limits.tags,
+ foldersLimit: limits.folders,
+ groupsLimit: limits.groups,
+ networkInvitesLimit: limits.networkInvites,
+ usersLimit: limits.users,
+ paymentFailedAt: null,
+ },
+ });
+}
+
+/**
+ * Use after a mocked `POST .../billing/upgrade` during onboarding when the app would call
+ * `redirectToCheckout`. Real Stripe.js over HTTP logs warnings and can block redirects when
+ * live publishable keys are loaded; this matches the checkout mock: trial in DB + success URL.
+ */
+export async function finishOnboardingCheckoutWithoutStripeRedirect(
+ page: Page,
+ options: { slug: string; baseURL: string },
+) {
+ const { slug, baseURL } = options;
+ const origin = baseURL.replace(/\/$/, "");
+ await applyMockTrialToWorkspace(slug);
+ await page.goto(
+ `${origin}/onboarding/success?workspace=${encodeURIComponent(slug)}`,
+ { waitUntil: "load" },
+ );
+}
+
+/**
+ * Intercepts the upgrade API so the dev server never calls Stripe, and
+ * intercepts Hosted Checkout navigation so Stripe never loads a fake session id
+ * (which throws CheckoutInitError). Trial state is applied with Prisma — no
+ * Stripe keys or webhooks needed.
+ */
+export async function installBillingCheckoutMocks(
+ page: Page,
+ options: { slug: string; baseURL: string },
+) {
+ const { slug, baseURL } = options;
+ const origin = baseURL.replace(/\/$/, "");
+ /** Mirrors last POST to billing/upgrade — used when Hosted Checkout redirects (no body). */
+ let pendingCheckout = {
+ onboarding: false,
+ plan: "business",
+ period: "monthly",
+ };
+
+ await patchStripeRedirectStubForE2E(page);
+
+ await page.route("https://js.stripe.com/**", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/javascript; charset=utf-8",
+ body: `
+ window.Stripe = function Stripe() {
+ return {
+ redirectToCheckout: function (opts) {
+ var id = opts && opts.sessionId ? String(opts.sessionId) : "";
+ window.location.href =
+ "https://checkout.stripe.com/c/pay/cs_test_e2e_redirect#" +
+ encodeURIComponent(id);
+ },
+ };
+ };
+ `,
+ });
+ });
+
+ await page.route(
+ (url) => url.pathname === `/api/workspaces/${slug}/billing/upgrade`,
+ async (route) => {
+ if (route.request().method() !== "POST") {
+ await route.continue();
+ return;
+ }
+ pendingCheckout = parseBillingUpgradeCheckoutContext(route.request());
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ id: MOCK_CHECKOUT_SESSION_ID }),
+ });
+ },
+ );
+
+ await page.route("https://checkout.stripe.com/**", async (route) => {
+ const req = route.request();
+ const url = req.url();
+ // Do not rely on isNavigationRequest() — client-side location.assign to checkout can be flaky.
+ if (!url.includes(MOCK_CHECKOUT_PATH_TOKEN)) {
+ await route.continue();
+ return;
+ }
+ await applyMockTrialToWorkspace(slug);
+ const { onboarding, plan, period } = pendingCheckout;
+ // Same path/query shape as stripe.checkout.sessions.create success_url in
+ // app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts — origin from baseURL
+ // keeps Playwright on the app host (cookies), unlike APP_DOMAIN in local dev.
+ const successUrl = onboarding
+ ? `${origin}/onboarding/success?workspace=${encodeURIComponent(slug)}`
+ : `${origin}/${slug}?upgraded=true&plan=${encodeURIComponent(plan)}&period=${encodeURIComponent(period)}`;
+ await route.fulfill({
+ status: 302,
+ headers: { Location: successUrl },
+ });
+ });
+
+ await patchStripeRedirectStubForE2E(page);
+}
diff --git a/apps/web/playwright/workspaces/billing-trial.spec.ts b/apps/web/playwright/workspaces/billing-trial.spec.ts
new file mode 100644
index 0000000000..cac657d0d8
--- /dev/null
+++ b/apps/web/playwright/workspaces/billing-trial.spec.ts
@@ -0,0 +1,180 @@
+import { DUB_TRIAL_PERIOD_DAYS } from "@dub/utils";
+import { expect, test } from "@playwright/test";
+import {
+ applyMockTrialToWorkspace,
+ captureWorkspaceBillingTrialSnapshot,
+ installBillingCheckoutMocks,
+ restoreWorkspaceBillingTrialSnapshot,
+ type BillingMockTrialWorkspaceSnapshot,
+} from "./billing-mocks";
+
+function matchesDashboardOrigin(url: URL, baseURL: string) {
+ const base = new URL(baseURL);
+ return url.hostname === base.hostname && url.port === base.port;
+}
+
+test.skip("Billing trial checkout", () => {
+ test("select Pro, success redirect, trial state and UI", async ({
+ page,
+ baseURL,
+ }) => {
+ const dashboardOrigin = baseURL ?? "http://app.localhost:8888";
+
+ // Discover the workspace created during onboarding
+ const res = await page.request.get("/api/workspaces");
+ expect(res.ok()).toBeTruthy();
+ const workspaces = (await res.json()) as { plan: string; slug: string }[];
+ // find the free workspace (from onboarding-dub-links.spec.ts)
+ const freeWorkspace = workspaces.find((w) => w.plan === "free");
+ if (!freeWorkspace) {
+ throw new Error("No free workspace found");
+ }
+ const slug = freeWorkspace.slug;
+
+ await installBillingCheckoutMocks(page, {
+ slug,
+ baseURL: dashboardOrigin,
+ });
+
+ await page.goto(`/${slug}/settings/billing/upgrade`);
+ await expect(
+ page.getByRole("heading", { name: "Plans", exact: true }),
+ ).toBeVisible({ timeout: 30_000 });
+
+ // CTA: billing may show "Upgrade" or checkout trial copy from UpgradePlanButton.
+ const upgradeButton = page.getByRole("button", { name: "Upgrade" }).or(
+ page.getByRole("button", {
+ name: new RegExp(`Start ${DUB_TRIAL_PERIOD_DAYS}-day trial`),
+ }),
+ );
+
+ await expect(upgradeButton.first()).toBeVisible();
+ await upgradeButton.first().click();
+
+ await page.waitForURL(
+ (u) => {
+ const url = new URL(u);
+ return (
+ matchesDashboardOrigin(url, dashboardOrigin) &&
+ url.searchParams.get("upgraded") === "true"
+ );
+ },
+ { timeout: 30_000, waitUntil: "domcontentloaded" },
+ );
+
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(`/api/workspaces/${slug}`);
+ if (!res.ok()) return null;
+ const body = (await res.json()) as { trialEndsAt?: string | null };
+ return body.trialEndsAt ?? null;
+ },
+ {
+ timeout: 90_000,
+ intervals: [500, 1000, 2000],
+ },
+ )
+ .not.toBeNull();
+
+ await expect(
+ page.getByRole("heading", {
+ name: /Dub Pro looks good on you/i,
+ }),
+ ).toBeVisible({ timeout: 15_000 });
+
+ await page.getByRole("button", { name: "View dashboard" }).click();
+
+ await expect(page.getByText("Free trial", { exact: true })).toBeVisible({
+ timeout: 15_000,
+ });
+ });
+});
+
+test.skip("Free trial user navigation", () => {
+ let slug: string;
+ let workspaceId: string;
+ let preMockTrialWorkspace: BillingMockTrialWorkspaceSnapshot | undefined;
+
+ test.beforeAll(async ({ request }) => {
+ const res = await request.get("/api/workspaces");
+ expect(res.ok()).toBeTruthy();
+ const [workspace] = (await res.json()) as { id: string; slug: string }[];
+ slug = workspace.slug;
+ workspaceId = workspace.id;
+
+ preMockTrialWorkspace = await captureWorkspaceBillingTrialSnapshot(slug);
+ await applyMockTrialToWorkspace(slug);
+ });
+
+ test.afterAll(async () => {
+ if (slug && preMockTrialWorkspace) {
+ await restoreWorkspaceBillingTrialSnapshot(slug, preMockTrialWorkspace);
+ }
+ });
+
+ test("billing settings page shows trial banner and CTAs", async ({
+ page,
+ }) => {
+ await page.goto(`/${slug}/settings/billing`);
+
+ await expect(page.getByText(/Trial ends on/)).toBeVisible({
+ timeout: 15_000,
+ });
+ await expect(
+ page.getByRole("button", { name: "Start paid plan" }),
+ ).toBeVisible();
+ await expect(page.getByRole("link", { name: "View plans" })).toBeVisible();
+ });
+
+ test("upgrade page shows Activate plan for current Pro plan", async ({
+ page,
+ }) => {
+ await page.goto(`/${slug}/settings/billing/upgrade`);
+
+ await expect(
+ page.getByRole("heading", { name: "Plans", exact: true }),
+ ).toBeVisible({ timeout: 30_000 });
+ await expect(
+ page.getByRole("button", { name: "Activate plan" }),
+ ).toBeVisible();
+ });
+
+ test("activating plan from billing page shows upgraded modal", async ({
+ page,
+ }) => {
+ await page.route(
+ (url) =>
+ url.pathname ===
+ `/api/workspaces/${workspaceId}/billing/activate-paid-plan`,
+ async (route) => {
+ if (route.request().method() !== "POST") return route.continue();
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ ok: true }),
+ });
+ },
+ );
+
+ await page.goto(`/${slug}/settings/billing`);
+
+ // Open the confirmation modal
+ await page.getByRole("button", { name: "Start paid plan" }).click();
+ await expect(
+ page.getByRole("heading", { name: "Plan start confirmation" }),
+ ).toBeVisible();
+ await expect(
+ page.getByText("You'll be charged today and your trial will end."),
+ ).toBeVisible();
+
+ // Confirm — triggers the mocked activate-paid-plan POST.
+ // Two "Start paid plan" buttons exist: the page-level CTA and the modal confirm.
+ await page.getByRole("button", { name: "Start paid plan" }).last().click();
+
+ // Upgraded modal appears when ?upgraded=true lands in the URL
+ await expect(
+ page.getByRole("heading", { name: /Dub Pro looks good on you/i }),
+ ).toBeVisible({ timeout: 15_000 });
+ });
+});
diff --git a/apps/web/playwright/workspaces/onboarding-dub-links.spec.ts b/apps/web/playwright/workspaces/onboarding-dub-links.spec.ts
new file mode 100644
index 0000000000..c21d9d4c60
--- /dev/null
+++ b/apps/web/playwright/workspaces/onboarding-dub-links.spec.ts
@@ -0,0 +1,108 @@
+import { nanoid } from "@dub/utils";
+import { expect, test } from "@playwright/test";
+
+/** Client navigations can finish before a sequential waitForURL runs; pair clicks with URL assertions. */
+const STEP_NAV_TIMEOUT = 60_000;
+
+test("complete workspace onboarding with Dub Links product", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+
+ const workspaceName = `Test WS ${nanoid(6)}`;
+
+ // Welcome page
+ await page.goto("/onboarding");
+ await expect(
+ page.getByRole("heading", { name: "Welcome to Dub" }),
+ ).toBeVisible();
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/workspace/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Get started" }).click(),
+ ]);
+
+ // Workspace creation step
+ await expect(
+ page.getByRole("heading", { name: "Create your workspace" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ // Fill workspace name (slug auto-generates)
+ await page.locator('input[id="name"]').fill(workspaceName);
+
+ // Read the auto-generated slug for later assertions
+ const slug = await page.locator('input[id="slug"]').inputValue();
+ expect(slug).toBeTruthy();
+
+ const productsHeading = page.getByRole("heading", {
+ name: "What do you want to do with Dub?",
+ });
+
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/products/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Create workspace" }).click(),
+ ]);
+ await expect(productsHeading).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/domain/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Continue with Dub Links" }).click(),
+ ]);
+
+ // Domain step — skip it
+ await expect(
+ page.getByRole("heading", { name: "Add a custom domain" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ const skipDomainCta = page.getByRole("button", {
+ name: "I'll do this later",
+ });
+ await expect(skipDomainCta).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/plan/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ skipDomainCta.click(),
+ ]);
+
+ // Plan step — use free plan
+ const freePlanCta = page.getByRole("button", {
+ name: "Start for free, pick a plan later",
+ });
+ await expect(freePlanCta).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/success/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ freePlanCta.click(),
+ ]);
+
+ // Success page
+ await expect(
+ page.locator("h1").filter({ hasText: workspaceName }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await expect(
+ page.locator("h3").filter({ hasText: /^Complete setup$/ }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ // Go to dashboard
+ const dashboardCta = page.getByRole("button", {
+ name: "Go to your dashboard",
+ });
+ await expect(dashboardCta).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ const slugPathPattern = new RegExp(
+ `/${slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/|$)`,
+ );
+ await Promise.all([
+ expect(page).toHaveURL(slugPathPattern, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ dashboardCta.click(),
+ ]);
+
+ expect(page.url()).toContain(`/${slug}`);
+});
diff --git a/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts b/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts
new file mode 100644
index 0000000000..f1d33a1d77
--- /dev/null
+++ b/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts
@@ -0,0 +1,221 @@
+import { nanoid } from "@dub/utils";
+import { expect, test } from "@playwright/test";
+import {
+ finishOnboardingCheckoutWithoutStripeRedirect,
+ installBillingCheckoutMocks,
+} from "./billing-mocks";
+
+const MINIMAL_PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
+ "base64",
+);
+
+function randomOnboardingDomain() {
+ const id = nanoid(10).replace(/_/g, "-").toLowerCase();
+ return `e2e-${id}.invalid`;
+}
+
+/** Client navigations can finish before a sequential waitForURL runs; pair clicks with URL assertions. */
+const STEP_NAV_TIMEOUT = 60_000;
+
+test.describe("Dub Partners onboarding", () => {
+ /**
+ * Retries must be off: a failed run may already own 2 free workspaces (links + this flow); retrying
+ * POST /api/workspaces hits FREE_WORKSPACES_LIMIT (403).
+ */
+ test.describe.configure({ retries: 0 });
+
+ test("complete workspace onboarding with Dub Partners product", async ({
+ page,
+ baseURL: baseURLParam,
+ }) => {
+ test.setTimeout(180_000);
+
+ const workspaceName = `Test WS ${nanoid(6)}`;
+ const customDomain = randomOnboardingDomain();
+ const baseURL = baseURLParam ?? "http://app.localhost:8888";
+
+ // Welcome page
+ await page.goto("/onboarding");
+ await expect(
+ page.getByRole("heading", { name: "Welcome to Dub" }),
+ ).toBeVisible();
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/workspace/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Get started" }).click(),
+ ]);
+
+ // Workspace creation step
+ await expect(
+ page.getByRole("heading", { name: "Create your workspace" }),
+ ).toBeVisible();
+
+ // Fill workspace name (slug auto-generates)
+ await page.locator('input[id="name"]').fill(workspaceName);
+
+ // Read the auto-generated slug for later assertions
+ const slug = await page.locator('input[id="slug"]').inputValue();
+ expect(slug).toBeTruthy();
+
+ const productsHeading = page.getByRole("heading", {
+ name: "What do you want to do with Dub?",
+ });
+
+ // Navigation runs in onSuccess after POST + SWR mutate + session.update(); wait for API first (CI).
+ const createWorkspacePost = page.waitForResponse(
+ (r) =>
+ r.request().method() === "POST" &&
+ new URL(r.url()).pathname === "/api/workspaces",
+ { timeout: STEP_NAV_TIMEOUT },
+ );
+ await page.getByRole("button", { name: "Create workspace" }).click();
+ const createWsRes = await createWorkspacePost;
+ if (!createWsRes.ok()) {
+ throw new Error(
+ `Create workspace failed: HTTP ${createWsRes.status()} ${await createWsRes.text()}`,
+ );
+ }
+ await expect(page).toHaveURL(/\/onboarding\/products/, {
+ timeout: STEP_NAV_TIMEOUT,
+ });
+ await expect(productsHeading).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ // Select "Dub Partners" product
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/domain/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Continue with Dub Partners" }).click(),
+ ]);
+
+ // Domain step — connect a custom domain
+ await expect(
+ page.getByRole("heading", { name: "Add a custom domain" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/domain\/custom/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Connect domain" }).click(),
+ ]);
+
+ await expect(
+ page.getByRole("heading", { name: "Connect a custom domain" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ await page.getByPlaceholder("go.acme.com").fill(customDomain);
+ await expect(page.getByText(/is ready to connect/i)).toBeVisible({
+ timeout: 30_000,
+ });
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/program/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Add domain" }).click(),
+ ]);
+
+ // Partner program step
+ await expect(
+ page.getByRole("heading", { name: "Create your partner program" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ await page.getByLabel("Company name").fill(`Test Program ${nanoid(4)}`);
+ await page.locator('input[type="file"]').setInputFiles({
+ name: "logo.png",
+ mimeType: "image/png",
+ buffer: MINIMAL_PNG,
+ });
+ await expect
+ .poll(async () => page.locator('img[alt="Preview"]').count(), {
+ timeout: 30_000,
+ })
+ .toBeGreaterThan(0);
+
+ await page.getByLabel("Destination URL").fill("https://acme.com");
+ await page.getByLabel("Support email").fill("[email protected]");
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/program\/reward/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Continue" }).click(),
+ ]);
+
+ // Default reward — keep Sale / recurring / percentage defaults, set 30%
+ await expect(
+ page.getByRole("heading", { name: "Create your default reward" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ const pctInput = page.getByLabel(/Percentage per sale/i);
+ await expect(pctInput).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await page.waitForTimeout(2000);
+ await pctInput.fill("30", { force: true });
+ await Promise.all([
+ expect(page).toHaveURL(/\/onboarding\/plan/, {
+ timeout: STEP_NAV_TIMEOUT,
+ }),
+ page.getByRole("button", { name: "Continue" }).click(),
+ ]);
+
+ // Plan step — mocked checkout trial (no Stripe)
+ await expect(
+ page
+ .locator("h1")
+ .filter({ hasText: /Partners/i })
+ .filter({ hasText: /plan/i }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ await installBillingCheckoutMocks(page, {
+ slug,
+ baseURL,
+ });
+
+ // use testId instead (since plan-selector overrides UpgradePlanButton text)
+ const advancedPaidCta = page.getByTestId("onboarding-plan-cta-advanced");
+ await expect(advancedPaidCta).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await expect(advancedPaidCta).toBeEnabled({ timeout: STEP_NAV_TIMEOUT });
+
+ const billingUpgradePost = page.waitForResponse(
+ (r) =>
+ r.request().method() === "POST" &&
+ r.url().includes(`/api/workspaces/${slug}/billing/upgrade`),
+ { timeout: STEP_NAV_TIMEOUT },
+ );
+
+ await advancedPaidCta.click();
+
+ const upgradeRes = await billingUpgradePost;
+ expect(upgradeRes.ok()).toBeTruthy();
+ await finishOnboardingCheckoutWithoutStripeRedirect(page, {
+ slug,
+ baseURL,
+ });
+
+ await expect(
+ page.getByRole("heading", {
+ name: `The ${workspaceName} workspace has been created`,
+ }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await expect(
+ page.getByRole("button", { name: "Go to your dashboard" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+ await expect(
+ page.getByRole("heading", { name: "Complete setup" }),
+ ).toBeVisible({ timeout: STEP_NAV_TIMEOUT });
+
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(`/api/workspaces/${slug}`);
+ if (!res.ok()) return null;
+ const body = (await res.json()) as { trialEndsAt?: string | null };
+ return body.trialEndsAt ?? null;
+ },
+ {
+ timeout: 90_000,
+ intervals: [500, 1000, 2000],
+ },
+ )
+ .not.toBeNull();
+ });
+});
diff --git a/apps/web/playwright/workspaces/onboarding.spec.ts b/apps/web/playwright/workspaces/onboarding.spec.ts
deleted file mode 100644
index 842e567a10..0000000000
--- a/apps/web/playwright/workspaces/onboarding.spec.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { nanoid } from "@dub/utils";
-import { expect, test } from "@playwright/test";
-
-test("complete workspace onboarding", async ({ page }) => {
- const workspaceName = `Test WS ${nanoid(6)}`;
-
- // Welcome page
- await page.goto("/onboarding");
- await expect(
- page.getByRole("heading", { name: "Welcome to Dub" }),
- ).toBeVisible();
- await page.getByRole("button", { name: "Get started" }).click();
-
- // Workspace creation step
- await page.waitForURL(/\/onboarding\/workspace/);
- await expect(
- page.getByRole("heading", { name: "Create your workspace" }),
- ).toBeVisible();
-
- // Fill workspace name (slug auto-generates)
- await page.locator('input[id="name"]').fill(workspaceName);
-
- // Read the auto-generated slug for later assertions
- const slug = await page.locator('input[id="slug"]').inputValue();
- expect(slug).toBeTruthy();
-
- // Submit workspace creation
- await page.getByRole("button", { name: "Create workspace" }).click();
-
- // Products step
- await page.waitForURL(/\/onboarding\/products/, { timeout: 15_000 });
- await expect(
- page.getByRole("heading", {
- name: "What do you want to do with Dub?",
- }),
- ).toBeVisible();
-
- // Select "Dub Links" product
- await page.getByRole("button", { name: "Continue with Dub Links" }).click();
-
- // Domain step — skip it
- await page.waitForURL(/\/onboarding\/domain/);
- await expect(
- page.getByRole("heading", { name: "Add a custom domain" }),
- ).toBeVisible();
- await page.getByRole("button", { name: "I'll do this later" }).click();
-
- // Plan step — use free plan
- await page.waitForURL(/\/onboarding\/plan/);
- await page
- .getByRole("button", { name: "Start for free, pick a plan later" })
- .click();
-
- // Success page
- await page.waitForURL(/\/onboarding\/success/);
- await expect(
- page.getByText(`The ${workspaceName} workspace has been created`),
- ).toBeVisible();
- await expect(page.getByText("Complete setup")).toBeVisible();
-
- // Go to dashboard
- await page.getByRole("button", { name: "Go to your dashboard" }).click();
-
- // Verify redirect to workspace dashboard
- await page.waitForURL(new RegExp(`/${slug}`), {
- timeout: 15_000,
- waitUntil: "domcontentloaded",
- });
- expect(page.url()).toContain(`/${slug}`);
-});
diff --git a/apps/web/scripts/dev/seed.ts b/apps/web/scripts/dev/seed.ts
index fe066b7b64..31735a349d 100644
--- a/apps/web/scripts/dev/seed.ts
+++ b/apps/web/scripts/dev/seed.ts
@@ -498,6 +498,9 @@ const truncate = async () => {
"Bounty",
"CampaignGroup",
"Campaign",
+ "FraudEvent",
+ "FraudEventGroup",
+ "FraudRule",
"ProgramApplication",
"ProgramEnrollment",
"PartnerGroup",
diff --git a/apps/web/scripts/fix-usage-count.ts b/apps/web/scripts/fix-usage-count.ts
deleted file mode 100644
index d5f6ddefd7..0000000000
--- a/apps/web/scripts/fix-usage-count.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-
-function getLastMonthDate(billingCycleStart: number) {
- const today = new Date();
- const year = today.getFullYear();
- const month = today.getMonth();
-
- // Set to the previous month
- const lastMonthDate = new Date(year, month - 1, billingCycleStart);
-
- return lastMonthDate;
-}
-
-function getThisMonthDate(billingCycleStart: number) {
- const today = new Date();
- const year = today.getFullYear();
- const month = today.getMonth();
-
- // Set to the current month
- const thisMonthDate = new Date(year, month, billingCycleStart);
-
- return thisMonthDate;
-}
-
-async function main() {
- const projects = await prisma.project.findMany({
- where: {
- plan: {
- not: "free",
- },
- linksUsage: {
- gt: 0,
- },
- billingCycleStart: {
- lt: 7,
- },
- },
- select: {
- id: true,
- slug: true,
- linksUsage: true,
- billingCycleStart: true,
- },
- });
-
- const finalProjects = await Promise.all(
- projects.map(async (project) => {
- const links = await prisma.link.count({
- where: {
- projectId: project.id,
- createdAt: {
- gte: getThisMonthDate(project.billingCycleStart),
- },
- },
- });
- // if (links !== project.linksUsage) {
- // await prisma.project.update({
- // where: {
- // id: project.id,
- // },
- // data: {
- // linksUsage: links,
- // },
- // });
- // }
- return {
- ...project,
- links,
- };
- }),
- );
-
- console.table(finalProjects);
-}
-
-main();
diff --git a/apps/web/scripts/migrations/backfill-workspace-stripe-billing-fields.ts b/apps/web/scripts/migrations/backfill-workspace-stripe-billing-fields.ts
new file mode 100644
index 0000000000..678e020c36
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-workspace-stripe-billing-fields.ts
@@ -0,0 +1,406 @@
+/**
+ * Backfills workspace (`Project`) billing fields from the platform Stripe account:
+ * `planPeriod`, `subscriptionCanceledAt`, `billingCycleEndsAt`.
+ *
+ * Requires:
+ * - `STRIPE_SECRET_KEY` (platform Stripe — same as webhooks)
+ * - Database URL env vars as used elsewhere (`DATABASE_URL`, etc.)
+ *
+ *
+ * Usage:
+ * pnpm exec tsx scripts/migrations/backfill-workspace-stripe-billing-fields.ts
+ * pnpm exec tsx scripts/migrations/backfill-workspace-stripe-billing-fields.ts --dry-run
+ * pnpm exec tsx scripts/migrations/backfill-workspace-stripe-billing-fields.ts --limit 50
+ * pnpm exec tsx scripts/migrations/backfill-workspace-stripe-billing-fields.ts --slug my-workspace --dry-run
+ * pnpm exec tsx scripts/migrations/backfill-workspace-stripe-billing-fields.ts --project-id clxxx...
+ */
+import { prisma } from "@dub/prisma";
+import type { PlanPeriod } from "@dub/prisma/client";
+import { chunk } from "@dub/utils";
+import "dotenv-flow/config";
+import Stripe from "stripe";
+import { getPlanPeriodFromStripeSubscription } from "../../app/(ee)/api/stripe/webhook/utils/stripe-plan-period";
+import { stripe } from "../../lib/stripe";
+import { getSubscriptionCancellationFields } from "../../lib/stripe/workspace-subscription-fields";
+
+const SUBSCRIPTION_LIST_LIMIT = 100;
+const PAGE_SIZE = 50;
+const PARALLEL_BATCH = 8;
+const BATCH_DELAY_MS = 150;
+
+const STATUS_PRIORITY = [
+ "active",
+ "trialing",
+ "past_due",
+ "unpaid",
+ "canceled",
+] as const;
+
+function argValue(argv: string[], flag: string): string | undefined {
+ const i = argv.indexOf(flag);
+ if (i === -1) {
+ return undefined;
+ }
+ const value = argv[i + 1];
+ if (value == null || value === "" || value.startsWith("--")) {
+ throw new Error(`${flag} requires a value`);
+ }
+ return value;
+}
+
+function parseArgs() {
+ const argv = process.argv.slice(2);
+
+ let limit: number | undefined;
+ if (argv.includes("--limit")) {
+ const rawLimit = argValue(argv, "--limit");
+ const n = Number(rawLimit);
+ if (!Number.isInteger(n) || n <= 0) {
+ throw new Error("--limit must be a positive integer");
+ }
+ limit = n;
+ }
+
+ const slug = argv.includes("--slug") ? argValue(argv, "--slug") : undefined;
+ const projectId = argv.includes("--project-id")
+ ? argValue(argv, "--project-id")
+ : undefined;
+
+ return {
+ dryRun: argv.includes("--dry-run"),
+ limit,
+ slug,
+ projectId,
+ };
+}
+
+function isStripeMissingCustomerError(e: unknown): boolean {
+ if (e instanceof Stripe.errors.StripeInvalidRequestError) {
+ return (
+ e.code === "resource_missing" &&
+ (e.param === "customer" || /no such customer/i.test(e.message))
+ );
+ }
+ return e instanceof Error && /no such customer/i.test(e.message);
+}
+
+function pickSubscription(
+ subscriptions: Stripe.Subscription[],
+): Stripe.Subscription | null {
+ if (subscriptions.length === 0) {
+ return null;
+ }
+ for (const status of STATUS_PRIORITY) {
+ const found = subscriptions.find((s) => s.status === status);
+ if (found) {
+ return found;
+ }
+ }
+ return [...subscriptions].sort((a, b) => b.created - a.created)[0] ?? null;
+}
+
+async function listCustomerSubscriptions(
+ customerId: string,
+): Promise<Stripe.Subscription[]> {
+ const subscriptions: Stripe.Subscription[] = [];
+ let startingAfter: string | undefined;
+
+ while (true) {
+ const page = await stripe.subscriptions.list({
+ customer: customerId,
+ status: "all",
+ limit: SUBSCRIPTION_LIST_LIMIT,
+ ...(startingAfter ? { starting_after: startingAfter } : {}),
+ });
+
+ subscriptions.push(...page.data);
+
+ if (!page.has_more) {
+ return subscriptions;
+ }
+
+ startingAfter = page.data[page.data.length - 1]?.id;
+ if (!startingAfter) {
+ return subscriptions;
+ }
+ }
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function sameInstant(
+ a: Date | null | undefined,
+ b: Date | null | undefined,
+): boolean {
+ if (a == null && b == null) {
+ return true;
+ }
+ if (a == null || b == null) {
+ return false;
+ }
+ return a.getTime() === b.getTime();
+}
+
+type ProjectBillingRow = {
+ id: string;
+ slug: string;
+ stripeId: string | null;
+ planPeriod: PlanPeriod | null;
+ subscriptionCanceledAt: Date | null;
+ billingCycleEndsAt: Date | null;
+};
+
+type BackfillCounters = {
+ updated: number;
+ skippedNoSubscription: number;
+ failed: number;
+};
+
+async function backfillOneProject(
+ project: ProjectBillingRow,
+ dryRun: boolean,
+ counters: BackfillCounters,
+): Promise<void> {
+ const customerId = project.stripeId;
+ if (!customerId) {
+ return;
+ }
+
+ try {
+ const allSubscriptions = await listCustomerSubscriptions(customerId);
+ const sub = pickSubscription(allSubscriptions);
+ if (!sub) {
+ console.log(
+ `[skip] ${project.id} (${project.slug}): no subscription for customer ${customerId}`,
+ );
+ counters.skippedNoSubscription++;
+ return;
+ }
+
+ const planPeriod: PlanPeriod | undefined =
+ getPlanPeriodFromStripeSubscription(sub);
+ const { subscriptionCanceledAt, billingCycleEndsAt } =
+ getSubscriptionCancellationFields(sub);
+
+ const nextData = {
+ planPeriod,
+ subscriptionCanceledAt,
+ billingCycleEndsAt,
+ };
+
+ const planEqual =
+ planPeriod === undefined || planPeriod === project.planPeriod;
+ const noOp =
+ planEqual &&
+ sameInstant(subscriptionCanceledAt, project.subscriptionCanceledAt) &&
+ sameInstant(billingCycleEndsAt, project.billingCycleEndsAt);
+
+ if (dryRun) {
+ console.log({
+ id: project.id,
+ slug: project.slug,
+ dryRun: true,
+ subscriptionId: sub.id,
+ subStatus: sub.status,
+ noOp,
+ proposed: nextData,
+ current: {
+ planPeriod: project.planPeriod,
+ subscriptionCanceledAt: project.subscriptionCanceledAt,
+ billingCycleEndsAt: project.billingCycleEndsAt,
+ },
+ });
+ return;
+ }
+
+ if (noOp) {
+ return;
+ }
+
+ const data: {
+ subscriptionCanceledAt: Date | null;
+ billingCycleEndsAt: Date | null;
+ planPeriod?: PlanPeriod;
+ } = {
+ subscriptionCanceledAt,
+ billingCycleEndsAt,
+ };
+ if (planPeriod !== undefined) {
+ data.planPeriod = planPeriod;
+ }
+
+ await prisma.project.update({
+ where: { id: project.id },
+ data,
+ });
+ counters.updated++;
+ console.log(`[updated] ${project.id} (${project.slug}) sub=${sub.id}`);
+ } catch (e) {
+ if (isStripeMissingCustomerError(e)) {
+ console.log(
+ `[skip] ${project.id} (${project.slug}): Stripe customer not found (${customerId})`,
+ );
+ counters.skippedNoSubscription++;
+ return;
+ }
+ counters.failed++;
+ console.error(
+ `[error] ${project.id} (${project.slug}):`,
+ e instanceof Error ? e.message : e,
+ );
+ }
+}
+
+async function runProjectBatches(
+ projects: ProjectBillingRow[],
+ dryRun: boolean,
+ counters: BackfillCounters,
+ onBatchComplete: (batchSize: number) => void,
+): Promise<void> {
+ const batches = chunk(projects, PARALLEL_BATCH);
+ for (const batch of batches) {
+ await Promise.all(
+ batch.map((project) => backfillOneProject(project, dryRun, counters)),
+ );
+ onBatchComplete(batch.length);
+ await sleep(BATCH_DELAY_MS);
+ }
+}
+
+async function main() {
+ const { dryRun, limit, slug, projectId } = parseArgs();
+
+ if (slug != null && projectId != null) {
+ throw new Error("Use only one of --slug or --project-id");
+ }
+
+ if (!process.env.STRIPE_SECRET_KEY) {
+ throw new Error("STRIPE_SECRET_KEY is required");
+ }
+
+ let processed = 0;
+ let cursor: { id: string } | undefined;
+ const counters: BackfillCounters = {
+ updated: 0,
+ skippedNoSubscription: 0,
+ failed: 0,
+ };
+
+ /** Single-record mode: no cursor pagination */
+ const scopedWhere =
+ slug != null
+ ? { slug, stripeId: { not: null } }
+ : projectId != null
+ ? { id: projectId, stripeId: { not: null } }
+ : { stripeId: { not: null }, billingCycleEndsAt: null };
+
+ if (scopedWhere != null) {
+ const projects = await prisma.project.findMany({
+ where: scopedWhere,
+ select: {
+ id: true,
+ slug: true,
+ stripeId: true,
+ planPeriod: true,
+ subscriptionCanceledAt: true,
+ billingCycleEndsAt: true,
+ },
+ });
+
+ if (projects.length === 0) {
+ console.log({
+ done: true,
+ dryRun,
+ message: "No matching project (check slug/id and stripeId)",
+ slug: slug ?? null,
+ projectId: projectId ?? null,
+ });
+ return;
+ }
+
+ await runProjectBatches(projects, dryRun, counters, (n) => {
+ processed += n;
+ });
+
+ console.log({
+ done: true,
+ dryRun,
+ mode: "scoped",
+ processed,
+ updated: counters.updated,
+ skippedNoSubscription: counters.skippedNoSubscription,
+ failed: counters.failed,
+ slug: slug ?? null,
+ projectId: projectId ?? null,
+ });
+ if (counters.failed > 0) {
+ throw new Error(
+ `Backfill finished with ${counters.failed} project error(s); see [error] logs above.`,
+ );
+ }
+ return;
+ }
+
+ while (true) {
+ if (limit != null && processed >= limit) {
+ break;
+ }
+
+ const take =
+ limit != null ? Math.min(PAGE_SIZE, limit - processed) : PAGE_SIZE;
+ if (take <= 0) {
+ break;
+ }
+
+ const projects = await prisma.project.findMany({
+ where: {
+ stripeId: { not: null },
+ },
+ select: {
+ id: true,
+ slug: true,
+ stripeId: true,
+ planPeriod: true,
+ subscriptionCanceledAt: true,
+ billingCycleEndsAt: true,
+ },
+ take,
+ skip: cursor ? 1 : 0,
+ cursor,
+ orderBy: { id: "asc" },
+ });
+
+ if (projects.length === 0) {
+ break;
+ }
+
+ await runProjectBatches(projects, dryRun, counters, (n) => {
+ processed += n;
+ });
+
+ cursor = { id: projects[projects.length - 1].id };
+ }
+
+ console.log({
+ done: true,
+ dryRun,
+ mode: "full",
+ processed,
+ updated: counters.updated,
+ skippedNoSubscription: counters.skippedNoSubscription,
+ failed: counters.failed,
+ limit: limit ?? null,
+ });
+ if (counters.failed > 0) {
+ throw new Error(
+ `Backfill finished with ${counters.failed} project error(s); see [error] logs above.`,
+ );
+ }
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/apps/web/tests/email/run-trial-email-cron.test.ts b/apps/web/tests/email/run-trial-email-cron.test.ts
new file mode 100644
index 0000000000..8ecb803992
--- /dev/null
+++ b/apps/web/tests/email/run-trial-email-cron.test.ts
@@ -0,0 +1,241 @@
+import { runTrialEmailCron } from "@/lib/email/run-trial-email-cron";
+import {
+ getTrialEmailSubject,
+ TRIAL_EMAIL_TYPE,
+} from "@/lib/email/trial-email-schedule";
+import { describe, expect, it, vi } from "vitest";
+
+const TRIAL_ENDS_AT = new Date(Date.UTC(2025, 0, 8, 23, 59, 59));
+
+describe("runTrialEmailCron", () => {
+ const workspaceId = "ws_trial_test";
+ const slug = "acme";
+
+ const baseWorkspace = {
+ id: workspaceId,
+ name: "Acme",
+ slug,
+ plan: "business",
+ trialEndsAt: TRIAL_ENDS_AT,
+ sentEmails: [] as { type: string }[],
+ users: [{ user: { email: "[email protected]", name: "Owner" } }] as const,
+ };
+
+ const batchOk = { data: null as null, error: null as null };
+
+ it("returns zeros and does not send when no workspaces match", async () => {
+ const findMany = vi.fn().mockResolvedValue([]);
+ const create = vi.fn();
+ const sendBatchEmail = vi.fn();
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result).toEqual({
+ sentCount: 0,
+ workspaceCount: 0,
+ hasMore: false,
+ });
+ expect(sendBatchEmail).not.toHaveBeenCalled();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it("sends due email to all recipients via sendBatchEmail and creates one SentEmail row", async () => {
+ const findMany = vi.fn().mockResolvedValue([{ ...baseWorkspace }]);
+ const create = vi.fn().mockResolvedValue({ id: "se_1" });
+ const sendBatchEmail = vi.fn().mockResolvedValue(batchOk);
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result).toEqual({
+ sentCount: 1,
+ workspaceCount: 1,
+ hasMore: false,
+ });
+ expect(sendBatchEmail).toHaveBeenCalledTimes(1);
+ const firstBatch = sendBatchEmail.mock.calls[0]?.[0] as {
+ to: string;
+ subject: string;
+ replyTo: string;
+ variant: string;
+ }[];
+ expect(firstBatch).toHaveLength(1);
+ expect(firstBatch?.[0]).toMatchObject({
+ subject: getTrialEmailSubject({
+ type: TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING,
+ companyName: "Acme",
+ }),
+ replyTo: "[email protected]",
+ variant: "marketing",
+ });
+ expect(create).toHaveBeenCalledWith({
+ data: {
+ projectId: workspaceId,
+ type: TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING,
+ },
+ });
+ });
+
+ it("sends one batched payload per due type when multiple workspace members have email", async () => {
+ const findMany = vi.fn().mockResolvedValue([
+ {
+ ...baseWorkspace,
+ users: [
+ { user: { email: "[email protected]", name: "Owner" } },
+ { user: { email: "[email protected]", name: "Member" } },
+ ],
+ },
+ ]);
+ const create = vi.fn().mockResolvedValue({ id: "se_1" });
+ const sendBatchEmail = vi.fn().mockResolvedValue(batchOk);
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result.sentCount).toBe(2);
+ expect(sendBatchEmail).toHaveBeenCalledTimes(1);
+ const batch = sendBatchEmail.mock.calls[0]?.[0] as { to: string }[];
+ expect(batch).toHaveLength(2);
+ expect(batch.map((b) => b.to).sort()).toEqual([
+ ]);
+ expect(create).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not send when that type was already sent", async () => {
+ const findMany = vi.fn().mockResolvedValue([
+ {
+ ...baseWorkspace,
+ sentEmails: [{ type: TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING }],
+ },
+ ]);
+ const create = vi.fn();
+ const sendBatchEmail = vi.fn();
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result).toEqual({
+ sentCount: 0,
+ workspaceCount: 1,
+ hasMore: false,
+ });
+ expect(sendBatchEmail).not.toHaveBeenCalled();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it("skips sending when no user has an email", async () => {
+ const findMany = vi.fn().mockResolvedValue([
+ {
+ ...baseWorkspace,
+ users: [{ user: { email: null, name: "Owner" } }],
+ },
+ ]);
+ const create = vi.fn();
+ const sendBatchEmail = vi.fn();
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result).toEqual({
+ sentCount: 0,
+ workspaceCount: 1,
+ hasMore: false,
+ });
+ expect(sendBatchEmail).not.toHaveBeenCalled();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it("skips workspace when trialEndsAt is null", async () => {
+ const findMany = vi.fn().mockResolvedValue([
+ {
+ ...baseWorkspace,
+ trialEndsAt: null,
+ },
+ ]);
+ const create = vi.fn();
+ const sendBatchEmail = vi.fn();
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result).toEqual({
+ sentCount: 0,
+ workspaceCount: 1,
+ hasMore: false,
+ });
+ expect(sendBatchEmail).not.toHaveBeenCalled();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it("sets hasMore and nextStartingAfter when page is full", async () => {
+ const workspaces = Array.from({ length: 50 }, (_, i) => ({
+ ...baseWorkspace,
+ id: `ws_${i}`,
+ slug: `slug-${i}`,
+ }));
+ const findMany = vi.fn().mockResolvedValue(workspaces);
+ const create = vi.fn();
+ const sendBatchEmail = vi.fn().mockResolvedValue(batchOk);
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ const result = await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ });
+
+ expect(result.workspaceCount).toBe(50);
+ expect(result.hasMore).toBe(true);
+ expect(result.nextStartingAfter).toBe("ws_49");
+ });
+
+ it("passes cursor to findMany when startingAfter is set", async () => {
+ const findMany = vi.fn().mockResolvedValue([]);
+ const create = vi.fn();
+ const sendBatchEmail = vi.fn();
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+
+ await runTrialEmailCron({
+ now,
+ prisma: { project: { findMany }, sentEmail: { create } },
+ sendBatchEmail,
+ startingAfter: "ws_prev",
+ });
+
+ expect(findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ skip: 1,
+ cursor: { id: "ws_prev" },
+ take: 50,
+ }),
+ );
+ });
+});
diff --git a/apps/web/tests/email/trial-email-schedule.test.ts b/apps/web/tests/email/trial-email-schedule.test.ts
new file mode 100644
index 0000000000..6939a74c81
--- /dev/null
+++ b/apps/web/tests/email/trial-email-schedule.test.ts
@@ -0,0 +1,78 @@
+import {
+ getDueTrialEmailTypes,
+ TRIAL_EMAIL_TYPE,
+} from "@/lib/email/trial-email-schedule";
+import { describe, expect, it } from "vitest";
+
+/** Fixed trial window: trial starts 2025-01-01 UTC, ends 2025-01-15 UTC (14 days). */
+const TRIAL_ENDS_AT = new Date(Date.UTC(2025, 0, 15, 12, 0, 0));
+
+describe("getDueTrialEmailTypes", () => {
+ const emptySent = new Set<string>();
+
+ it("returns trial7DaysRemaining when 7 calendar days remain until end", () => {
+ const now = new Date(Date.UTC(2025, 0, 8, 10, 0, 0));
+ expect(
+ getDueTrialEmailTypes({
+ trialEndsAt: TRIAL_ENDS_AT,
+ sent: emptySent,
+ now,
+ }),
+ ).toEqual([TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING]);
+ });
+
+ it("returns trial3DaysRemaining when 3 calendar days remain until end", () => {
+ const now = new Date(Date.UTC(2025, 0, 12, 10, 0, 0));
+ expect(
+ getDueTrialEmailTypes({
+ trialEndsAt: TRIAL_ENDS_AT,
+ sent: emptySent,
+ now,
+ }),
+ ).toEqual([TRIAL_EMAIL_TYPE.THREE_DAYS_REMAINING]);
+ });
+
+ it("returns nothing after the trial end instant (no late ends-today on same UTC date)", () => {
+ const now = new Date(Date.UTC(2025, 0, 15, 14, 0, 0));
+ expect(
+ getDueTrialEmailTypes({
+ trialEndsAt: TRIAL_ENDS_AT,
+ sent: emptySent,
+ now,
+ }),
+ ).toEqual([]);
+ });
+
+ it("returns trial-7-days-remaining one calendar day late (catch-up)", () => {
+ const now = new Date(Date.UTC(2025, 0, 9, 10, 0, 0));
+ expect(
+ getDueTrialEmailTypes({
+ trialEndsAt: TRIAL_ENDS_AT,
+ sent: emptySent,
+ now,
+ }),
+ ).toEqual([TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING]);
+ });
+
+ it("does not return a type that is already in sent", () => {
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+ const sent = new Set<string>([TRIAL_EMAIL_TYPE.SEVEN_DAYS_REMAINING]);
+ expect(
+ getDueTrialEmailTypes({
+ trialEndsAt: TRIAL_ENDS_AT,
+ sent,
+ now,
+ }),
+ ).toEqual([]);
+ });
+
+ it("does not duplicate a type in the due list", () => {
+ const now = new Date(Date.UTC(2025, 0, 1, 10, 0, 0));
+ const due = getDueTrialEmailTypes({
+ trialEndsAt: TRIAL_ENDS_AT,
+ sent: emptySent,
+ now,
+ });
+ expect(new Set(due).size).toBe(due.length);
+ });
+});
diff --git a/apps/web/ui/domains/add-edit-domain-form.tsx b/apps/web/ui/domains/add-edit-domain-form.tsx
index 6a8a10c8d1..9e72867e17 100644
--- a/apps/web/ui/domains/add-edit-domain-form.tsx
+++ b/apps/web/ui/domains/add-edit-domain-form.tsx
@@ -103,10 +103,14 @@ export function AddEditDomainForm({
props,
onSuccess,
enableDomainConfig = true,
+ initialDomain,
+ fixedDomainSuffix,
}: {
props?: DomainProps;
onSuccess?: (data: DomainProps) => void;
enableDomainConfig?: boolean;
+ fixedDomainSuffix?: string;
+ initialDomain?: string;
}) {
const { id: workspaceId, plan } = useWorkspace();
const [lockDomain, setLockDomain] = useState(true);
@@ -124,10 +128,13 @@ export function AddEditDomainForm({
handleSubmit,
watch,
setValue,
- formState: { isSubmitting, isDirty },
+ formState: { isSubmitting, isSubmitSuccessful, isDirty },
} = useForm<FormData>({
defaultValues: {
- slug: props?.slug,
+ slug:
+ props?.slug ||
+ initialDomain ||
+ (fixedDomainSuffix ? `.${fixedDomainSuffix}` : ""),
logo: props?.logo,
expiredUrl: props?.expiredUrl,
notFoundUrl: props?.notFoundUrl,
@@ -176,6 +183,13 @@ export function AddEditDomainForm({
}, []);
const domain = watch("slug");
+ const escapedFixedDomainSuffix = fixedDomainSuffix?.replace(
+ /[.*+?^${}()|[\]\\]/g,
+ "\\$&",
+ );
+ const subdomainPrefix = fixedDomainSuffix
+ ? (domain || "").replace(new RegExp(`\\.${escapedFixedDomainSuffix}$`), "")
+ : undefined;
const debouncedValidateDomain = useDebouncedCallback(
async (value: string) => {
@@ -189,6 +203,12 @@ export function AddEditDomainForm({
500,
);
+ useEffect(() => {
+ if (domain && isValidDomain(domain)) {
+ debouncedValidateDomain(domain);
+ }
+ }, [domain, debouncedValidateDomain]);
+
const saveDisabled = useMemo(() => {
return (
!["available", "has site"].includes(domainStatus) || (props && !isDirty)
@@ -330,17 +350,47 @@ export function AddEditDomainForm({
)}
>
<div className="flex rounded-md border border-neutral-300 bg-white">
- <input
- {...register("slug", {
- onChange: (e) => {
- setDomainStatus("idle");
- debouncedValidateDomain(e.target.value);
- },
- })}
- className="block w-full rounded-md border-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
- placeholder="go.acme.com"
- autoFocus={!isMobile}
- />
+ {fixedDomainSuffix ? (
+ <>
+ <input
+ value={subdomainPrefix}
+ onChange={(e) => {
+ const prefix = e.target.value
+ .toLowerCase()
+ .replace(/[^a-z0-9-]/g, "");
+ const fullDomain = prefix
+ ? `${prefix}.${fixedDomainSuffix}`
+ : `.${fixedDomainSuffix}`;
+ setValue("slug", fullDomain, {
+ shouldDirty: true,
+ });
+ setDomainStatus("idle");
+ if (prefix) {
+ debouncedValidateDomain(fullDomain);
+ }
+ }}
+ className="block w-full rounded-l-md border-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ placeholder="workspace"
+ autoFocus={!isMobile}
+ />
+ <span className="inline-flex items-center rounded-r-md border-l border-neutral-300 bg-neutral-100 px-3 text-sm text-neutral-600">
+ .{fixedDomainSuffix}
+ </span>
+ <input type="hidden" {...register("slug")} />
+ </>
+ ) : (
+ <input
+ {...register("slug", {
+ onChange: (e) => {
+ setDomainStatus("idle");
+ debouncedValidateDomain(e.target.value);
+ },
+ })}
+ className="block w-full rounded-md border-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ placeholder="go.acme.com"
+ autoFocus={!isMobile}
+ />
+ )}
</div>
<AnimatedSizeContainer
@@ -611,7 +661,7 @@ export function AddEditDomainForm({
<Button
text={props ? "Save changes" : "Add domain"}
disabled={saveDisabled}
- loading={isSubmitting}
+ loading={isSubmitting || isSubmitSuccessful}
/>
</div>
</form>
diff --git a/apps/web/ui/domains/free-dot-link-banner.tsx b/apps/web/ui/domains/free-dot-link-banner.tsx
index d634030308..c2cb4f0d74 100644
--- a/apps/web/ui/domains/free-dot-link-banner.tsx
+++ b/apps/web/ui/domains/free-dot-link-banner.tsx
@@ -1,11 +1,12 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { Grid, useLocalStorage } from "@dub/ui";
import { LinkBroken } from "@dub/ui/icons";
+import { isWorkspaceBillingTrialActive } from "@dub/utils";
import { useRegisterDomainModal } from "../modals/register-domain-modal";
import { X } from "../shared/icons";
export function FreeDotLinkBanner() {
- const { id: workspaceId } = useWorkspace();
+ const { id: workspaceId, trialEndsAt } = useWorkspace();
const [show, setShow] = useLocalStorage(
`show-free-dot-link-banner:${workspaceId}`,
true,
@@ -14,6 +15,10 @@ export function FreeDotLinkBanner() {
const { RegisterDomainModal, setShowRegisterDomainModal } =
useRegisterDomainModal();
+ if (isWorkspaceBillingTrialActive(trialEndsAt)) {
+ return null;
+ }
+
return (
show && (
<>
diff --git a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
index 6212203d09..177e1c9c6b 100644
--- a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
@@ -12,7 +12,6 @@ import { usePayoutsCount } from "@/lib/swr/use-payouts-count";
import useProgram from "@/lib/swr/use-program";
import { useProgramReferralsCount } from "@/lib/swr/use-program-referrals-count";
import useWorkspace from "@/lib/swr/use-workspace";
-import useWorkspaces from "@/lib/swr/use-workspaces";
import { useRouterStuff } from "@dub/ui";
import {
Bell,
@@ -46,10 +45,11 @@ import {
Users6,
Webhook,
} from "@dub/ui/icons";
+import { isWorkspaceBillingTrialActive } from "@dub/utils";
import { Session } from "next-auth";
import { useSession } from "next-auth/react";
import { useParams, usePathname } from "next/navigation";
-import { ReactNode, useEffect, useMemo } from "react";
+import { ReactNode, useMemo } from "react";
import { DubPartnersPopup } from "./dub-partners-popup";
import { Compass } from "./icons/compass";
import { ConnectedDots4 } from "./icons/connected-dots4";
@@ -79,113 +79,43 @@ type SidebarNavData = {
partnerNetworkEnabled?: boolean;
};
-const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({ slug, pathname }) => [
- {
- name: "Short Links",
- description:
- "Create, organize, and measure the performance of your short links.",
- learnMoreHref: "https://dub.co/links",
- icon: Compass,
- href: slug ? `/${slug}/links` : "/links",
- active:
- !!slug &&
- pathname.startsWith(`/${slug}`) &&
- !pathname.startsWith(`/${slug}/program`) &&
- !pathname.startsWith(`/${slug}/settings`),
- },
- {
+const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({
+ slug,
+ pathname,
+ defaultProgramId,
+}) => {
+ const programGroup = {
+ id: "program",
name: "Partner Program",
description:
"Kickstart viral product-led growth with powerful, branded referral and affiliate programs.",
learnMoreHref: "https://dub.co/partners",
icon: ConnectedDots4,
href: slug ? `/${slug}/program` : "/program",
- active: pathname.startsWith(`/${slug}/program`),
+ active:
+ !!slug &&
+ pathname.startsWith(`/${slug}`) &&
+ !pathname.startsWith(`/${slug}/links`) &&
+ !pathname.startsWith(`/${slug}/settings`),
popup: DubPartnersPopup,
- },
-];
+ };
+ const linksGroup = {
+ id: "links",
+ name: "Short Links",
+ description:
+ "Create, organize, and measure the performance of your short links.",
+ learnMoreHref: "https://dub.co/links",
+ icon: Compass,
+ href: slug ? `/${slug}/links` : "/links",
+ active: pathname.startsWith(`/${slug}/links`),
+ };
+ return defaultProgramId
+ ? [programGroup, linksGroup]
+ : [linksGroup, programGroup];
+};
const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
- // Top-level
- default: ({ slug, pathname, queryString, showNews }) => ({
- title: "Short Links",
- showNews,
- direction: "left",
- content: [
- {
- items: [
- {
- name: "Links",
- icon: Hyperlink,
- href: `/${slug}/links${pathname === `/${slug}/links` ? "" : queryString}`,
- isActive: (pathname: string, href: string) => {
- const basePath = href.split("?")[0];
-
- // Exact match for the base links page
- if (pathname === basePath) return true;
-
- // Check if it's a link detail page (path segment after base contains a dot for domain)
- if (pathname.startsWith(basePath + "/")) {
- const nextSegment = pathname
- .slice(basePath.length + 1)
- .split("/")[0];
- return nextSegment.includes(".");
- }
-
- return false;
- },
- },
- {
- name: "Domains",
- icon: Globe,
- href: `/${slug}/links/domains`,
- },
- ],
- },
- {
- name: "Insights",
- items: [
- {
- name: "Analytics",
- icon: LinesY,
- href: `/${slug}/analytics${pathname === `/${slug}/analytics` ? "" : queryString}`,
- },
- {
- name: "Events",
- icon: CursorRays,
- href: `/${slug}/events${pathname === `/${slug}/events` ? "" : queryString}`,
- },
- {
- name: "Customers",
- icon: User,
- href: `/${slug}/customers`,
- },
- ],
- },
- {
- name: "Library",
- items: [
- {
- name: "Folders",
- icon: Folder,
- href: `/${slug}/links/folders`,
- },
- {
- name: "Tags",
- icon: Tag,
- href: `/${slug}/links/tags`,
- },
- {
- name: "UTM Templates",
- icon: DiamondTurnRight,
- href: `/${slug}/links/utm`,
- },
- ],
- },
- ],
- }),
-
- // Program
+ // partner program
program: ({
slug,
showNews,
@@ -357,6 +287,84 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
},
],
}),
+ // short links
+ links: ({ slug, pathname, queryString, showNews }) => ({
+ title: "Short Links",
+ showNews,
+ direction: "left",
+ content: [
+ {
+ items: [
+ {
+ name: "Links",
+ icon: Hyperlink,
+ href: `/${slug}/links${pathname === `/${slug}/links` ? "" : queryString}`,
+ isActive: (pathname: string, href: string) => {
+ const basePath = href.split("?")[0];
+
+ // Exact match for the base links page
+ if (pathname === basePath) return true;
+
+ // Check if it's a link detail page (path segment after base contains a dot for domain)
+ if (pathname.startsWith(basePath + "/")) {
+ const nextSegment = pathname
+ .slice(basePath.length + 1)
+ .split("/")[0];
+ return nextSegment.includes(".");
+ }
+
+ return false;
+ },
+ },
+ {
+ name: "Domains",
+ icon: Globe,
+ href: `/${slug}/links/domains`,
+ },
+ ],
+ },
+ {
+ name: "Insights",
+ items: [
+ {
+ name: "Analytics",
+ icon: LinesY,
+ href: `/${slug}/analytics${pathname === `/${slug}/analytics` ? "" : queryString}`,
+ },
+ {
+ name: "Events",
+ icon: CursorRays,
+ href: `/${slug}/events${pathname === `/${slug}/events` ? "" : queryString}`,
+ },
+ {
+ name: "Customers",
+ icon: User,
+ href: `/${slug}/customers`,
+ },
+ ],
+ },
+ {
+ name: "Library",
+ items: [
+ {
+ name: "Folders",
+ icon: Folder,
+ href: `/${slug}/links/folders`,
+ },
+ {
+ name: "Tags",
+ icon: Tag,
+ href: `/${slug}/links/tags`,
+ },
+ {
+ name: "UTM Templates",
+ icon: DiamondTurnRight,
+ href: `/${slug}/links/utm`,
+ },
+ ],
+ },
+ ],
+ }),
// Workspace settings
workspaceSettings: ({ slug }) => ({
@@ -486,55 +494,11 @@ export function AppSidebarNav({
toolContent?: ReactNode;
newsContent?: ReactNode;
}) {
- const { slug: paramsSlug } = useParams() as { slug?: string };
+ const { slug } = useParams() as { slug?: string };
const pathname = usePathname();
const { getQueryString } = useRouterStuff();
- const { data: session, status } = useSession();
- const { plan, defaultProgramId } = useWorkspace();
- const { workspaces } = useWorkspaces();
-
- // Store the current workspace slug in sessionStorage so we can remember it on account settings pages
- useEffect(() => {
- if (paramsSlug) {
- sessionStorage.setItem("dub_last_workspace", paramsSlug);
- }
- }, [paramsSlug]);
-
- // Validate and clear sessionStorage if user doesn't have access to the stored workspace
- useEffect(() => {
- if (status === "unauthenticated") {
- // Clear sessionStorage on logout
- sessionStorage.removeItem("dub_last_workspace");
- return;
- }
-
- if (workspaces && typeof window !== "undefined") {
- const storedSlug = sessionStorage.getItem("dub_last_workspace");
- if (storedSlug && !paramsSlug) {
- // Only validate if we're not currently on a workspace page (to avoid clearing during navigation)
- const hasAccess = workspaces.some((w) => w.slug === storedSlug);
- if (!hasAccess) {
- // User doesn't have access to the stored workspace, clear it
- sessionStorage.removeItem("dub_last_workspace");
- }
- }
- }
- }, [workspaces, status, paramsSlug]);
-
- // Use params slug when available, otherwise try sessionStorage (last visited workspace), then fall back to default workspace
- const slug =
- paramsSlug ||
- (typeof window !== "undefined" && workspaces
- ? (() => {
- const storedSlug = sessionStorage.getItem("dub_last_workspace");
- // Validate that the stored slug is accessible by the current user
- if (storedSlug && workspaces.some((w) => w.slug === storedSlug)) {
- return storedSlug;
- }
- return null;
- })()
- : null) ||
- session?.user?.["defaultWorkspace"];
+ const { data: session } = useSession();
+ const { plan, defaultProgramId, trialEndsAt } = useWorkspace();
const currentArea = useMemo(() => {
return pathname.startsWith("/account/settings")
@@ -545,9 +509,9 @@ export function AppSidebarNav({
pathname.includes("/program/messages/") ||
pathname.endsWith("/program/payouts/success")
? null
- : pathname.startsWith(`/${slug}/program`)
- ? "program"
- : "default";
+ : pathname.startsWith(`/${slug}/links`)
+ ? "links"
+ : "program";
}, [slug, pathname]);
const { program } = useProgram({
@@ -628,7 +592,14 @@ export function AppSidebarNav({
program && program.partnerNetworkEnabledAt !== null,
}}
toolContent={toolContent}
- newsContent={plan && (plan === "free" ? <SidebarUsage /> : newsContent)}
+ newsContent={
+ plan &&
+ (plan === "free" || isWorkspaceBillingTrialActive(trialEndsAt) ? (
+ <SidebarUsage />
+ ) : (
+ newsContent
+ ))
+ }
switcher={<WorkspaceDropdown />}
/>
);
diff --git a/apps/web/ui/layout/sidebar/sidebar-usage.tsx b/apps/web/ui/layout/sidebar/sidebar-usage.tsx
index c6d2a252fb..32c10aa77d 100644
--- a/apps/web/ui/layout/sidebar/sidebar-usage.tsx
+++ b/apps/web/ui/layout/sidebar/sidebar-usage.tsx
@@ -1,15 +1,26 @@
"use client";
+import { clientAccessCheck } from "@/lib/client-access-check";
+import usePartnersCount from "@/lib/swr/use-partners-count";
import useWorkspace from "@/lib/swr/use-workspace";
+import { useStartPaidPlanModal } from "@/ui/modals/start-paid-plan-modal";
import ManageSubscriptionButton from "@/ui/workspaces/manage-subscription-button";
-import { AnimatedSizeContainer, buttonVariants, Icon } from "@dub/ui";
-import { CursorRays, Hyperlink } from "@dub/ui/icons";
+import {
+ AnimatedSizeContainer,
+ Button,
+ buttonVariants,
+ DynamicTooltipWrapper,
+ Icon,
+} from "@dub/ui";
+import { CursorRays, Hyperlink, MoneyBills2, Users } from "@dub/ui/icons";
import {
cn,
getFirstAndLastDay,
getNextPlan,
INFINITY_NUMBER,
+ isWorkspaceBillingTrialActive,
nFormatter,
+ TRIAL_PROGRAM_ENROLLMENT_LIMIT,
} from "@dub/utils";
import NumberFlow from "@number-flow/react";
import { ChevronRight } from "lucide-react";
@@ -30,14 +41,44 @@ function UsageInner() {
usageLimit,
linksUsage,
linksLimit,
+ payoutsUsage,
payoutsLimit,
billingCycleStart,
plan,
slug,
paymentFailedAt,
loading,
+ trialEndsAt,
+ role,
+ defaultProgramId,
} = useWorkspace({ swrOpts: { keepPreviousData: true } });
+ const isTrial = isWorkspaceBillingTrialActive(trialEndsAt);
+
+ const { partnersCount } = usePartnersCount<number>({
+ ignoreParams: true,
+ enabled: Boolean(isTrial && defaultProgramId),
+ });
+
+ const permissionsError = clientAccessCheck({
+ action: "billing.write",
+ role,
+ }).error;
+
+ const { StartPaidPlanModal, setShowStartPaidPlanModal } =
+ useStartPaidPlanModal();
+
+ const trialDaysLeft = useMemo(() => {
+ if (!trialEndsAt || !isWorkspaceBillingTrialActive(trialEndsAt)) {
+ return null;
+ }
+ const end = new Date(trialEndsAt);
+ const days = Math.ceil(
+ (end.getTime() - Date.now()) / (1000 * 60 * 60 * 24),
+ );
+ return Math.max(0, days);
+ }, [trialEndsAt]);
+
const [billingEnd] = useMemo(() => {
if (billingCycleStart) {
const { lastDay } = getFirstAndLastDay(billingCycleStart);
@@ -60,49 +101,106 @@ function UsageInner() {
() =>
[
[usage, usageLimit],
- [linksUsage, linksLimit],
+ [payoutsUsage, payoutsLimit],
+ [partnersCount, TRIAL_PROGRAM_ENROLLMENT_LIMIT],
].map(
([usage, limit]) =>
usage !== undefined &&
limit !== undefined &&
usage / Math.max(0, usage, limit) >= 0.9,
),
- [usage, usageLimit, linksUsage, linksLimit],
+ [usage, usageLimit, payoutsUsage, payoutsLimit, partnersCount],
);
const warning = warnings.some((w) => w);
return loading || usage !== undefined ? (
<>
+ {isTrial ? <StartPaidPlanModal /> : null}
<AnimatedSizeContainer height>
<div className="border-t border-neutral-300/80 p-3">
- <Link
- className="group flex items-center gap-0.5 text-sm font-normal text-neutral-500 transition-colors hover:text-neutral-700"
- href={`/${slug}/settings/billing`}
- >
- Usage
- <ChevronRight className="size-3 text-neutral-400 transition-[color,transform] group-hover:translate-x-0.5 group-hover:text-neutral-500" />
- </Link>
+ {isTrial ? (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm font-semibold text-neutral-900">
+ Free trial
+ </span>
- <div className="mt-4 flex flex-col gap-4">
- <UsageRow
- icon={CursorRays}
- label="Events"
- usage={usage}
- limit={usageLimit}
- showNextPlan={hovered}
- nextPlanLimit={nextPlan?.limits.clicks}
- warning={warnings[0]}
- />
- <UsageRow
- icon={Hyperlink}
- label="Links"
- usage={linksUsage}
- limit={linksLimit}
- showNextPlan={hovered}
- nextPlanLimit={nextPlan?.limits.links}
- warning={warnings[1]}
- />
+ <Link
+ className="group flex shrink-0 items-center gap-0.5 text-sm font-normal text-neutral-600 transition-colors hover:text-neutral-700"
+ href={`/${slug}/settings/billing`}
+ >
+ {trialDaysLeft != null
+ ? `${trialDaysLeft} day${trialDaysLeft === 1 ? "" : "s"} left`
+ : "Trial"}
+ <ChevronRight className="size-3 text-neutral-400 transition-[color,transform] group-hover:translate-x-0.5 group-hover:text-neutral-500" />
+ </Link>
+ </div>
+ ) : (
+ <Link
+ className="group flex items-center gap-0.5 text-sm font-normal text-neutral-500 transition-colors hover:text-neutral-700"
+ href={`/${slug}/settings/billing`}
+ >
+ Usage
+ <ChevronRight className="size-2 text-neutral-400 transition-[color,transform] group-hover:translate-x-0.5 group-hover:text-neutral-500" />
+ </Link>
+ )}
+
+ <div
+ className={cn("mt-4 flex flex-col", isTrial ? "gap-3" : "gap-4")}
+ >
+ {isTrial ? (
+ <>
+ <UsageRow
+ icon={CursorRays}
+ label="Events"
+ usage={usage}
+ limit={usageLimit}
+ showNextPlan={false}
+ nextPlanLimit={undefined}
+ warning={warnings[0]}
+ />
+ <UsageRow
+ icon={MoneyBills2}
+ label="Payouts"
+ usage={payoutsUsage}
+ limit={payoutsLimit}
+ showNextPlan={false}
+ nextPlanLimit={undefined}
+ warning={warnings[1]}
+ valueInCents
+ />
+ <UsageRow
+ icon={Users}
+ label="Partners"
+ usage={defaultProgramId ? partnersCount : 0}
+ limit={TRIAL_PROGRAM_ENROLLMENT_LIMIT}
+ showNextPlan={false}
+ nextPlanLimit={undefined}
+ warning={warnings[2]}
+ />
+ </>
+ ) : (
+ <>
+ <UsageRow
+ icon={CursorRays}
+ label="Events"
+ usage={usage}
+ limit={usageLimit}
+ showNextPlan={hovered}
+ nextPlanLimit={nextPlan?.limits.clicks}
+ warning={warnings[0]}
+ />
+ <UsageRow
+ icon={Hyperlink}
+ label="Links"
+ usage={linksUsage}
+ limit={linksLimit}
+ showNextPlan={hovered}
+ nextPlanLimit={nextPlan?.limits.links}
+ warning={warnings[1]}
+ />
+ </>
+ )}
</div>
<div className="mt-3">
@@ -117,7 +215,11 @@ function UsageInner() {
>
{paymentFailedAt
? "Your last payment failed. Please update your payment method to continue using Dub."
- : `Usage will reset ${billingEnd}`}
+ : isTrial && trialEndsAt
+ ? null
+ : billingEnd
+ ? `Usage will reset ${billingEnd}`
+ : null}
</p>
)}
</div>
@@ -134,6 +236,26 @@ function UsageInner() {
setHovered(false);
}}
/>
+ ) : isTrial ? (
+ <DynamicTooltipWrapper
+ tooltipProps={
+ permissionsError ? { content: permissionsError } : undefined
+ }
+ >
+ <Button
+ text="Activate plan"
+ variant="primary"
+ className="mt-4 h-8 w-full rounded-lg"
+ disabled={Boolean(permissionsError)}
+ onClick={() => setShowStartPaidPlanModal(true)}
+ onMouseEnter={() => {
+ setHovered(true);
+ }}
+ onMouseLeave={() => {
+ setHovered(false);
+ }}
+ />
+ </DynamicTooltipWrapper>
) : (warning || plan === "free") && plan !== "enterprise" ? (
<Link
href={`/${slug}/upgrade`}
@@ -165,6 +287,8 @@ type UsageRowProps = {
showNextPlan: boolean;
nextPlanLimit?: number;
warning: boolean;
+ hideProgressBar?: boolean;
+ valueInCents?: boolean;
};
const UsageRow = forwardRef<HTMLDivElement, UsageRowProps>(
@@ -177,6 +301,8 @@ const UsageRow = forwardRef<HTMLDivElement, UsageRowProps>(
showNextPlan,
nextPlanLimit,
warning,
+ hideProgressBar = false,
+ valueInCents = false,
}: UsageRowProps,
ref,
) => {
@@ -193,55 +319,61 @@ const UsageRow = forwardRef<HTMLDivElement, UsageRowProps>(
</span>
</div>
{!loading ? (
- <div className="flex items-center">
+ valueInCents ? (
<span className="text-xs font-medium text-neutral-600">
- <NumberFlow value={usage} /> of{" "}
- <motion.span
- className={cn(
- "relative transition-colors duration-150",
- showNextPlan && nextPlanLimit
- ? "text-neutral-400"
- : "text-neutral-600",
- )}
- >
- {formatNumber(limit)}
+ {formatUsdFromCents(usage!)} of {formatUsdFromCents(limit!)}
+ </span>
+ ) : (
+ <div className="flex items-center">
+ <span className="text-xs font-medium text-neutral-600">
+ <NumberFlow value={usage} /> of{" "}
+ <motion.span
+ className={cn(
+ "relative transition-colors duration-150",
+ showNextPlan && nextPlanLimit
+ ? "text-neutral-400"
+ : "text-neutral-600",
+ )}
+ >
+ {formatNumber(limit)}
+ {showNextPlan && nextPlanLimit && (
+ <motion.span
+ className="absolute bottom-[45%] left-0 h-[1px] bg-neutral-400"
+ initial={{ width: "0%" }}
+ animate={{ width: "100%" }}
+ transition={{
+ duration: 0.25,
+ ease: "easeInOut",
+ }}
+ />
+ )}
+ </motion.span>
+ </span>
+ <AnimatePresence>
{showNextPlan && nextPlanLimit && (
- <motion.span
- className="absolute bottom-[45%] left-0 h-[1px] bg-neutral-400"
- initial={{ width: "0%" }}
- animate={{ width: "100%" }}
+ <motion.div
+ className="flex items-center"
+ initial={{ width: 0, opacity: 0 }}
+ animate={{ width: "auto", opacity: 1 }}
+ exit={{ width: 0, opacity: 0 }}
transition={{
duration: 0.25,
- ease: "easeInOut",
+ ease: [0.4, 0, 0.2, 1], // Custom cubic-bezier for smooth movement
}}
- />
+ >
+ <motion.span className="ml-1 whitespace-nowrap text-xs font-medium text-blue-600">
+ {formatNumber(nextPlanLimit)}
+ </motion.span>
+ </motion.div>
)}
- </motion.span>
- </span>
- <AnimatePresence>
- {showNextPlan && nextPlanLimit && (
- <motion.div
- className="flex items-center"
- initial={{ width: 0, opacity: 0 }}
- animate={{ width: "auto", opacity: 1 }}
- exit={{ width: 0, opacity: 0 }}
- transition={{
- duration: 0.25,
- ease: [0.4, 0, 0.2, 1], // Custom cubic-bezier for smooth movement
- }}
- >
- <motion.span className="ml-1 whitespace-nowrap text-xs font-medium text-blue-600">
- {formatNumber(nextPlanLimit)}
- </motion.span>
- </motion.div>
- )}
- </AnimatePresence>
- </div>
+ </AnimatePresence>
+ </div>
+ )
) : (
<div className="h-4 w-16 animate-pulse rounded-md bg-neutral-500/10" />
)}
</div>
- {!unlimited && (
+ {!hideProgressBar && !unlimited && (
<div className="mt-1.5">
<div
className={cn(
@@ -260,7 +392,7 @@ const UsageRow = forwardRef<HTMLDivElement, UsageRowProps>(
warning && "to-rose-500",
)}
style={{
- transform: `translateX(-${100 - Math.max(Math.floor((usage / Math.max(0, usage, limit)) * 100), usage === 0 ? 0 : 1)}%)`,
+ transform: `translateX(-${100 - Math.max(Math.floor((usage! / Math.max(0, usage!, limit!)) * 100), usage === 0 ? 0 : 1)}%)`,
transition: "transform 0.25s ease-in-out",
}}
/>
@@ -281,3 +413,14 @@ const formatNumber = (value: number) =>
full: value !== undefined && value < 999,
digits: 1,
});
+
+function formatUsdFromCents(cents: number) {
+ if (cents >= INFINITY_NUMBER) {
+ return "∞";
+ }
+ const dollars = cents / 100;
+ return `$${nFormatter(dollars, {
+ full: dollars < 1000,
+ digits: 1,
+ })}`;
+}
diff --git a/apps/web/ui/layout/upgrade-banner.tsx b/apps/web/ui/layout/upgrade-banner.tsx
index af97f07049..4c1d750ac2 100644
--- a/apps/web/ui/layout/upgrade-banner.tsx
+++ b/apps/web/ui/layout/upgrade-banner.tsx
@@ -1,8 +1,13 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import { Crown } from "@dub/ui";
-import { cn } from "@dub/utils";
+import {
+ cn,
+ getTrialLimitResourceForOverageBanner,
+ isWorkspaceBillingTrialActive,
+} from "@dub/utils";
import { motion } from "motion/react";
import Link from "next/link";
import ManageSubscriptionButton from "../workspaces/manage-subscription-button";
@@ -16,59 +21,98 @@ export function useUpgradeBannerVisible() {
}
export function UpgradeBanner() {
- const { slug, exceededEvents, exceededLinks, exceededPayouts } =
+ const { slug, exceededEvents, exceededLinks, exceededPayouts, trialEndsAt } =
useWorkspace();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const needsUpgrade = exceededEvents || exceededLinks || exceededPayouts;
+ const overageLimitResource = getTrialLimitResourceForOverageBanner({
+ exceededEvents: Boolean(exceededEvents),
+ exceededLinks: Boolean(exceededLinks),
+ exceededPayouts: Boolean(exceededPayouts),
+ });
const isVisible = useUpgradeBannerVisible();
if (!isVisible) return null;
return (
- <motion.div
- initial={{ transform: "translateY(-100%)" }}
- animate={{ transform: "translateY(0)" }}
- className="text-content-inverted bg-bg-inverted fixed left-0 right-0 top-0 z-50 flex h-12 items-center justify-center overflow-hidden px-6"
- >
- {needsUpgrade && <Crown className="mr-2 size-4 shrink-0" />}
- <p className="text-sm">
+ <>
+ <TrialLimitActivateModal />
+ <motion.div
+ initial={{ transform: "translateY(-100%)" }}
+ animate={{ transform: "translateY(0)" }}
+ className="text-content-inverted bg-bg-inverted fixed left-0 right-0 top-0 z-50 flex h-12 items-center justify-center overflow-hidden px-6"
+ >
+ {needsUpgrade && <Crown className="mr-2 size-4 shrink-0" />}
+ <p className="text-sm">
+ {needsUpgrade ? (
+ <>
+ You&rsquo;ve hit the{" "}
+ <Link href={`/${slug}/settings/billing`} className="underline">
+ monthly{" "}
+ {exceededEvents
+ ? "events"
+ : exceededLinks
+ ? "links"
+ : "payouts"}{" "}
+ limit
+ </Link>
+ <span className="xs:inline hidden">
+ &nbsp;on your current plan
+ </span>
+ <span className="hidden md:inline">
+ . Upgrade to keep using Dub.
+ </span>
+ </>
+ ) : (
+ <>
+ Your last payment failed. Please update your payment method to
+ continue using Dub.
+ </>
+ )}
+ </p>
{needsUpgrade ? (
- <>
- You&rsquo;ve hit the{" "}
- <Link href={`/${slug}/settings/billing`} className="underline">
- monthly{" "}
- {exceededEvents ? "events" : exceededLinks ? "links" : "payouts"}{" "}
- limit
+ trialActive ? (
+ <button
+ type="button"
+ onClick={() =>
+ openTrialLimitModal(
+ overageLimitResource ??
+ (exceededEvents
+ ? "clicks"
+ : exceededLinks
+ ? "links"
+ : "payouts"),
+ )
+ }
+ className={cn(
+ "bg-bg-default text-content-emphasis border-border-subtle ml-4 flex h-7 items-center justify-center rounded-lg border px-2.5 text-sm font-medium",
+ "hover:bg-bg-subtle transition-colors duration-150",
+ )}
+ >
+ Upgrade
+ </button>
+ ) : (
+ <Link
+ href={`/${slug}/settings/billing/upgrade`}
+ className={cn(
+ "bg-bg-default text-content-emphasis border-border-subtle ml-4 flex h-7 items-center justify-center rounded-lg border px-2.5 text-sm font-medium",
+ "hover:bg-bg-subtle transition-colors duration-150",
+ )}
+ >
+ Upgrade
</Link>
- <span className="xs:inline hidden">&nbsp;on your current plan</span>
- <span className="hidden md:inline">
- . Upgrade to keep using Dub.
- </span>
- </>
+ )
) : (
- <>
- Your last payment failed. Please update your payment method to
- continue using Dub.
- </>
+ <ManageSubscriptionButton
+ text="Update Payment Method"
+ variant="secondary"
+ className="ml-4 h-7 w-fit px-2.5 text-sm font-medium"
+ />
)}
- </p>
- {needsUpgrade ? (
- <Link
- href={`/${slug}/settings/billing/upgrade`}
- className={cn(
- "bg-bg-default text-content-emphasis border-border-subtle ml-4 flex h-7 items-center justify-center rounded-lg border px-2.5 text-sm font-medium",
- "hover:bg-bg-subtle transition-colors duration-150",
- )}
- >
- Upgrade
- </Link>
- ) : (
- <ManageSubscriptionButton
- text="Update Payment Method"
- variant="secondary"
- className="ml-4 h-7 w-fit px-2.5 text-sm font-medium"
- />
- )}
- </motion.div>
+ </motion.div>
+ </>
);
}
diff --git a/apps/web/ui/modals/approve-partner-application-modal.tsx b/apps/web/ui/modals/approve-partner-application-modal.tsx
index 6f72cf2c43..c19b669671 100644
--- a/apps/web/ui/modals/approve-partner-application-modal.tsx
+++ b/apps/web/ui/modals/approve-partner-application-modal.tsx
@@ -3,6 +3,7 @@ import useWorkspace from "@/lib/swr/use-workspace";
import { PartnerProps } from "@/lib/types";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
import { Button, Modal, useKeyboardShortcut } from "@dub/ui";
+import { isWorkspaceBillingTrialActive } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import {
Dispatch,
@@ -12,6 +13,7 @@ import {
useState,
} from "react";
import { toast } from "sonner";
+import { useTrialLimitActivateModal } from "./trial-limit-activate-modal";
interface ApprovePartnerApplicationModalProps {
showApprovePartnerApplicationModal: boolean;
@@ -33,7 +35,12 @@ export function ApprovePartnerApplicationModal({
onConfirm,
confirmShortcutOptions,
}: ApprovePartnerApplicationModalProps) {
- const { id: workspaceId } = useWorkspace();
+ const { id: workspaceId, trialEndsAt } = useWorkspace();
+
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const { executeAsync: approvePartnerApplication, isPending } = useAction(
approvePartnerAction,
@@ -46,7 +53,15 @@ export function ApprovePartnerApplicationModal({
await onConfirm?.();
},
onError: ({ error }) => {
- toast.error(error.serverError || "Failed to approve partner.");
+ const msg = String(error.serverError ?? "");
+ if (
+ trialActive &&
+ (msg.includes("free trial") || msg.includes("enrolled partners"))
+ ) {
+ openTrialLimitModal("partnerEnrollments");
+ } else {
+ toast.error(msg || "Failed to approve partner.");
+ }
},
},
);
@@ -71,54 +86,57 @@ export function ApprovePartnerApplicationModal({
});
return (
- <Modal
- showModal={showApprovePartnerApplicationModal}
- setShowModal={setShowApprovePartnerApplicationModal}
- onClose={handleClose}
- >
- <div className="border-b border-neutral-200 p-4 sm:p-6">
- <h3 className="text-lg font-medium leading-none">
- Approve application
- </h3>
- </div>
+ <>
+ <Modal
+ showModal={showApprovePartnerApplicationModal}
+ setShowModal={setShowApprovePartnerApplicationModal}
+ onClose={handleClose}
+ >
+ <div className="border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">
+ Approve application
+ </h3>
+ </div>
- {partner && (
- <div className="flex flex-col gap-6 bg-neutral-50 p-4 sm:p-6">
- <div className="rounded-lg border border-neutral-200 bg-neutral-100 p-3">
- <div className="flex items-center gap-4">
- <PartnerAvatar partner={partner} className="size-10 bg-white" />
- <div className="flex min-w-0 flex-col">
- <h4 className="truncate text-sm font-medium text-neutral-900">
- {partner.name}
- </h4>
- <p className="truncate text-xs text-neutral-500">
- {partner.email}
- </p>
+ {partner && (
+ <div className="flex flex-col gap-6 bg-neutral-50 p-4 sm:p-6">
+ <div className="rounded-lg border border-neutral-200 bg-neutral-100 p-3">
+ <div className="flex items-center gap-4">
+ <PartnerAvatar partner={partner} className="size-10 bg-white" />
+ <div className="flex min-w-0 flex-col">
+ <h4 className="truncate text-sm font-medium text-neutral-900">
+ {partner.name}
+ </h4>
+ <p className="truncate text-xs text-neutral-500">
+ {partner.email}
+ </p>
+ </div>
</div>
</div>
</div>
- </div>
- )}
+ )}
- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 p-4">
- <Button
- variant="secondary"
- text="Cancel"
- className="h-8 w-fit px-3"
- onClick={handleClose}
- disabled={isPending}
- />
- <Button
- className="h-8 w-fit px-3"
- text="Approve"
- variant="primary"
- loading={isPending}
- autoFocus
- shortcut="A"
- onClick={handleConfirm}
- />
- </div>
- </Modal>
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 p-4">
+ <Button
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ onClick={handleClose}
+ disabled={isPending}
+ />
+ <Button
+ className="h-8 w-fit px-3"
+ text="Approve"
+ variant="primary"
+ loading={isPending}
+ autoFocus
+ shortcut="A"
+ onClick={handleConfirm}
+ />
+ </div>
+ </Modal>
+ <TrialLimitActivateModal />
+ </>
);
}
diff --git a/apps/web/ui/modals/bulk-approve-partners-modal.tsx b/apps/web/ui/modals/bulk-approve-partners-modal.tsx
index 4d363d51ae..c2165d163c 100644
--- a/apps/web/ui/modals/bulk-approve-partners-modal.tsx
+++ b/apps/web/ui/modals/bulk-approve-partners-modal.tsx
@@ -3,10 +3,11 @@ import { mutatePrefix } from "@/lib/swr/mutate";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { EnrolledPartnerProps } from "@/lib/types";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import { GroupSelector } from "@/ui/partners/groups/group-selector";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
import { Button, Modal } from "@dub/ui";
-import { cn, pluralize } from "@dub/utils";
+import { cn, isWorkspaceBillingTrialActive, pluralize } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import {
Dispatch,
@@ -26,8 +27,11 @@ function BulkApprovePartnersModal({
setShowBulkApprovePartnersModal: Dispatch<SetStateAction<boolean>>;
partners: EnrolledPartnerProps[];
}) {
- const { id: workspaceId } = useWorkspace();
+ const { id: workspaceId, trialEndsAt } = useWorkspace();
const { program } = useProgram();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const [selectedGroupId, setSelectedGroupId] = useState<string | null>(
program?.defaultGroupId ?? null,
@@ -40,7 +44,22 @@ function BulkApprovePartnersModal({
toast.success(`${pluralize("Partner", partners.length)} approved.`);
},
onError({ error }) {
- toast.error(error.serverError);
+ const serverMsg = String(error.serverError ?? "").trim();
+ if (
+ trialActive &&
+ (serverMsg.includes("free trial") ||
+ serverMsg.includes("enrolled partners"))
+ ) {
+ openTrialLimitModal("partnerEnrollments");
+ return;
+ }
+ const message =
+ serverMsg ||
+ ("message" in error &&
+ typeof (error as { message?: unknown }).message === "string"
+ ? String((error as { message: string }).message).trim()
+ : "");
+ toast.error(message || "An error occurred");
},
});
@@ -59,75 +78,78 @@ function BulkApprovePartnersModal({
};
return (
- <Modal
- showModal={showBulkApprovePartnersModal}
- setShowModal={setShowBulkApprovePartnersModal}
- >
- <div className="space-y-1 border-b border-neutral-200 p-4 sm:p-6">
- <h3 className="text-lg font-semibold leading-none">
- Approve {pluralize("application", partners.length)}
- </h3>
+ <>
+ <TrialLimitActivateModal />
+ <Modal
+ showModal={showBulkApprovePartnersModal}
+ setShowModal={setShowBulkApprovePartnersModal}
+ >
+ <div className="space-y-1 border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-semibold leading-none">
+ Approve {pluralize("application", partners.length)}
+ </h3>
- <p className="text-content-subtle text-base font-medium">
- Are you sure you want to approve{" "}
- {pluralize("this application", partners.length, {
- plural: "these applications",
- })}
- ?
- </p>
- </div>
+ <p className="text-content-subtle text-base font-medium">
+ Are you sure you want to approve{" "}
+ {pluralize("this application", partners.length, {
+ plural: "these applications",
+ })}
+ ?
+ </p>
+ </div>
- <div className="space-y-6 bg-neutral-50 p-4 sm:p-6">
- <div className="flex items-center gap-3 rounded-lg border border-neutral-200 bg-neutral-100 p-3">
- <div className="flex items-center">
- {partners.slice(0, 3).map((partner, index) => (
- <PartnerAvatar
- key={partner.id}
- partner={partner}
- className={cn(
- "inline-block size-7 border-2 border-neutral-100",
- index > 0 && "-ml-2.5",
- )}
- />
- ))}
+ <div className="space-y-6 bg-neutral-50 p-4 sm:p-6">
+ <div className="flex items-center gap-3 rounded-lg border border-neutral-200 bg-neutral-100 p-3">
+ <div className="flex items-center">
+ {partners.slice(0, 3).map((partner, index) => (
+ <PartnerAvatar
+ key={partner.id}
+ partner={partner}
+ className={cn(
+ "inline-block size-7 border-2 border-neutral-100",
+ index > 0 && "-ml-2.5",
+ )}
+ />
+ ))}
+ </div>
+ <span className="text-base font-semibold text-neutral-900">
+ {partners.length} {pluralize("partner", partners.length)} selected
+ </span>
</div>
- <span className="text-base font-semibold text-neutral-900">
- {partners.length} {pluralize("partner", partners.length)} selected
- </span>
- </div>
- <div className="grid grid-cols-1 gap-6">
- <div>
- <label className="block text-sm font-medium text-neutral-900">
- Assign all to group{" "}
- </label>
+ <div className="grid grid-cols-1 gap-6">
+ <div>
+ <label className="block text-sm font-medium text-neutral-900">
+ Assign all to group{" "}
+ </label>
- <div className="relative mt-2 rounded-md shadow-sm">
- <GroupSelector
- selectedGroupId={selectedGroupId}
- setSelectedGroupId={setSelectedGroupId}
- />
+ <div className="relative mt-2 rounded-md shadow-sm">
+ <GroupSelector
+ selectedGroupId={selectedGroupId}
+ setSelectedGroupId={setSelectedGroupId}
+ />
+ </div>
</div>
</div>
</div>
- </div>
- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
- <Button
- onClick={() => setShowBulkApprovePartnersModal(false)}
- variant="secondary"
- text="Cancel"
- className="h-8 w-fit px-3"
- />
- <Button
- onClick={handleBulkApprove}
- autoFocus
- loading={isPending}
- text="Approve"
- className="h-8 w-fit px-3"
- />
- </div>
- </Modal>
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
+ <Button
+ onClick={() => setShowBulkApprovePartnersModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ />
+ <Button
+ onClick={handleBulkApprove}
+ autoFocus
+ loading={isPending}
+ text="Approve"
+ className="h-8 w-fit px-3"
+ />
+ </div>
+ </Modal>
+ </>
);
}
diff --git a/apps/web/ui/modals/link-builder/index.tsx b/apps/web/ui/modals/link-builder/index.tsx
index 923fb436e0..62fd849f79 100644
--- a/apps/web/ui/modals/link-builder/index.tsx
+++ b/apps/web/ui/modals/link-builder/index.tsx
@@ -27,6 +27,7 @@ import { TagSelect } from "@/ui/links/link-builder/tag-select";
import { useLinkBuilderSubmit } from "@/ui/links/link-builder/use-link-builder-submit";
import { useMetatags } from "@/ui/links/link-builder/use-metatags";
import { useAvailableDomains } from "@/ui/links/use-available-domains";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import {
ArrowTurnLeft,
Button,
@@ -36,7 +37,7 @@ import {
useKeyboardShortcut,
useRouterStuff,
} from "@dub/ui";
-import { cn, isValidUrl } from "@dub/utils";
+import { cn, isValidUrl, isWorkspaceBillingTrialActive } from "@dub/utils";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import {
Dispatch,
@@ -263,7 +264,10 @@ export function CreateLinkButton({
}: {
setShowLinkBuilder: Dispatch<SetStateAction<boolean>>;
} & CreateLinkButtonProps) {
- const { slug, role, exceededLinks } = useWorkspace();
+ const { slug, role, exceededLinks, trialEndsAt } = useWorkspace();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const permissionsError = clientAccessCheck({
action: "links.write",
@@ -304,23 +308,34 @@ export function CreateLinkButton({
}, []);
return (
- <Button
- text="Create link"
- shortcut="C"
- disabledTooltip={
- exceededLinks ? (
- <TooltipContent
- title="Your workspace has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to create more links."
- cta="Upgrade plan"
- href={`/${slug}/upgrade`}
- />
- ) : (
- permissionsError || undefined
- )
- }
- onClick={() => setShowLinkBuilder(true)}
- {...buttonProps}
- />
+ <>
+ <TrialLimitActivateModal />
+ <Button
+ text="Create link"
+ shortcut="C"
+ disabledTooltip={
+ exceededLinks ? (
+ trialActive ? (
+ <TooltipContent
+ title="Your workspace has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to create more links."
+ cta="Start paid plan"
+ onClick={() => openTrialLimitModal("links")}
+ />
+ ) : (
+ <TooltipContent
+ title="Your workspace has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to create more links."
+ cta="Upgrade plan"
+ href={`/${slug}/upgrade`}
+ />
+ )
+ ) : (
+ permissionsError || undefined
+ )
+ }
+ onClick={() => setShowLinkBuilder(true)}
+ {...buttonProps}
+ />
+ </>
);
}
diff --git a/apps/web/ui/modals/manage-usage-modal.tsx b/apps/web/ui/modals/manage-usage-modal.tsx
index 52b6793ef0..94904ef5de 100644
--- a/apps/web/ui/modals/manage-usage-modal.tsx
+++ b/apps/web/ui/modals/manage-usage-modal.tsx
@@ -27,7 +27,8 @@ type ManageUsageModalProps = {
function ManageUsageModalContent({ type }: ManageUsageModalProps) {
const workspace = useWorkspace();
- const { slug, role, plan, planTier, usageLimit, linksLimit } = workspace;
+ const { slug, role, plan, planPeriod, planTier, usageLimit, linksLimit } =
+ workspace;
const { error: permissionsError } = clientAccessCheck({
action: "billing.write",
@@ -72,6 +73,7 @@ function ManageUsageModalContent({ type }: ManageUsageModalProps) {
const isCurrentPlanSuggested =
plan === suggestedPlan.name.toLowerCase() &&
+ planPeriod === period &&
suggestedPlanTier === (planTier ?? 1);
const isDowngradeSuggested =
@@ -183,7 +185,9 @@ function ManageUsageModalContent({ type }: ManageUsageModalProps) {
? "Current plan"
: isDowngradeSuggested
? "Downgrade"
- : "Upgrade"
+ : planPeriod !== period
+ ? `Switch to ${period}`
+ : "Upgrade"
}
variant={isDowngradeSuggested ? "secondary" : "primary"}
className="h-8 rounded-lg shadow-sm"
diff --git a/apps/web/ui/modals/plan-change-confirmation-modal.tsx b/apps/web/ui/modals/plan-change-confirmation-modal.tsx
index aba869afbd..0355bd6d25 100644
--- a/apps/web/ui/modals/plan-change-confirmation-modal.tsx
+++ b/apps/web/ui/modals/plan-change-confirmation-modal.tsx
@@ -1,8 +1,11 @@
"use client";
+import usePartnersCount from "@/lib/swr/use-partners-count";
+import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { Button, Modal } from "@dub/ui";
import { TriangleWarning } from "@dub/ui/icons";
+import { OG_AVATAR_URL, pluralize } from "@dub/utils";
import {
Dispatch,
SetStateAction,
@@ -13,18 +16,63 @@ import {
} from "react";
import { Markdown } from "../shared/markdown";
+export type PlanChangeConfirmationMode =
+ | "program-downgrade"
+ | "advanced-downgrade";
+
function PlanChangeConfirmationModal({
showPlanChangeConfirmationModal,
setShowPlanChangeConfirmationModal,
+ confirmationMode,
onConfirm,
}: {
showPlanChangeConfirmationModal: boolean;
setShowPlanChangeConfirmationModal: Dispatch<SetStateAction<boolean>>;
+ confirmationMode: PlanChangeConfirmationMode;
onConfirm: () => void | Promise<void>;
}) {
- const { slug } = useWorkspace();
+ const {
+ slug,
+ name: workspaceName,
+ logo: workspaceLogo,
+ defaultProgramId,
+ } = useWorkspace();
+
+ const { program } = useProgram({
+ enabled: showPlanChangeConfirmationModal,
+ });
+
+ const { partnersCount, loading: partnersCountLoading } =
+ usePartnersCount<number>({
+ ignoreParams: true,
+ enabled: showPlanChangeConfirmationModal,
+ });
+
const [isSubmitting, setIsSubmitting] = useState(false);
+ const displayName = program?.name ?? workspaceName ?? "";
+ const logoSrc =
+ program?.logo ??
+ workspaceLogo ??
+ (displayName
+ ? `${OG_AVATAR_URL}${displayName}`
+ : `${OG_AVATAR_URL}default`);
+
+ const PROGRAM_DOWNGRADE_MARKDOWN = [
+ "- You will lose access to your partner program.",
+ "- Your partner program will be deactivated and partners will be notified automatically.",
+ "- Partner links will stop tracking new activity.",
+ `- Any [pending payouts](https://app.dub.co/${slug}/program/payouts?status=pending) must be communicated and settled directly with your partners.`,
+ ].join("\n");
+
+ const ADVANCED_DOWNGRADE_MARKDOWN = [
+ "- [Email campaigns](https://dub.co/help/article/email-campaigns) will be paused or canceled.",
+ "- [Messaging center](https://dub.co/help/article/messaging-partners) will be disabled.",
+ "- [Advanced reward conditions](https://dub.co/help/article/partner-rewards) will be removed.",
+ "- [Fraud events](https://dub.co/help/article/fraud-detection) will still be tracked, but you need to upgrade to view them.",
+ "- If you've set up the [Embedded Referral Dashboard](https://dub.co/docs/partners/embedded-referrals), it will no longer work.",
+ ].join("\n");
+
return (
<Modal
showModal={showPlanChangeConfirmationModal}
@@ -36,20 +84,43 @@ function PlanChangeConfirmationModal({
</div>
<div className="flex flex-col gap-4 bg-neutral-50 p-4 sm:p-6">
- <div className="flex flex-col items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-4">
- <TriangleWarning className="size-5 text-amber-600" />
- <p className="text-sm font-medium text-amber-900">
- This change will affect your partner program
- </p>
+ <div className="flex flex-col gap-1 rounded-lg bg-amber-100 p-1">
+ <div className="flex items-center gap-2 p-2">
+ <TriangleWarning className="size-4 shrink-0 text-amber-500" />
+ <p className="text-sm text-amber-900">
+ {confirmationMode === "advanced-downgrade"
+ ? "You will lose Advanced plan features"
+ : "This change will affect your partner program"}
+ </p>
+ </div>
+
+ {defaultProgramId && displayName ? (
+ <div className="w-full rounded-lg border border-amber-100 bg-white p-3 shadow-sm">
+ <div className="flex items-center gap-3">
+ <img
+ src={logoSrc}
+ alt={displayName}
+ className="size-10 shrink-0 rounded-full object-cover"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-semibold text-neutral-800">
+ {displayName}
+ </p>
+ {!partnersCountLoading && partnersCount !== undefined ? (
+ <p className="text-sm text-neutral-500">
+ {partnersCount} {pluralize("partner", partnersCount)}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ ) : null}
</div>
<Markdown className="list-decimal">
- {[
- "- You will lose access to your partner program.",
- "- Your partner program will be deactivated and partners will be notified automatically.",
- "- Partner links will stop tracking new activity.",
- `- Any [pending payouts](https://app.dub.co/${slug}/program/payouts?status=pending) must be communicated and settled directly with your partners.`,
- ].join("\n")}
+ {confirmationMode === "advanced-downgrade"
+ ? ADVANCED_DOWNGRADE_MARKDOWN
+ : PROGRAM_DOWNGRADE_MARKDOWN}
</Markdown>
</div>
@@ -70,7 +141,6 @@ function PlanChangeConfirmationModal({
if (isSubmitting) return;
setIsSubmitting(true);
await onConfirm();
- setIsSubmitting(false);
}}
/>
</div>
@@ -80,8 +150,10 @@ function PlanChangeConfirmationModal({
export function usePlanChangeConfirmationModal({
onConfirm,
+ confirmationMode = "program-downgrade",
}: {
onConfirm: () => void | Promise<void>;
+ confirmationMode?: PlanChangeConfirmationMode;
}) {
const [showPlanChangeConfirmationModal, setShowPlanChangeConfirmationModal] =
useState(false);
@@ -90,11 +162,15 @@ export function usePlanChangeConfirmationModal({
const onConfirmRef = useRef(onConfirm);
onConfirmRef.current = onConfirm;
+ const confirmationModeRef = useRef(confirmationMode);
+ confirmationModeRef.current = confirmationMode;
+
const PlanChangeConfirmationModalCallback = useCallback(() => {
return (
<PlanChangeConfirmationModal
showPlanChangeConfirmationModal={showPlanChangeConfirmationModal}
setShowPlanChangeConfirmationModal={setShowPlanChangeConfirmationModal}
+ confirmationMode={confirmationModeRef.current}
onConfirm={() => onConfirmRef.current()}
/>
);
diff --git a/apps/web/ui/modals/start-paid-plan-modal.tsx b/apps/web/ui/modals/start-paid-plan-modal.tsx
new file mode 100644
index 0000000000..ce79040c8e
--- /dev/null
+++ b/apps/web/ui/modals/start-paid-plan-modal.tsx
@@ -0,0 +1,156 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Button, Modal, useRouterStuff } from "@dub/ui";
+import { getPlanDetails } from "@dub/utils";
+import NumberFlow from "@number-flow/react";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { toast } from "sonner";
+
+function StartPaidPlanModal({
+ showModal,
+ setShowModal,
+}: {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const {
+ id: workspaceId,
+ plan,
+ planPeriod,
+ planTier = 1,
+ mutate,
+ } = useWorkspace();
+ const { queryParams } = useRouterStuff();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const planDetails = useMemo(() => {
+ if (!plan || plan === "free" || plan === "enterprise") return null;
+ return getPlanDetails({ plan, planTier });
+ }, [plan, planTier]);
+
+ const workspacePlanPeriod = planPeriod ?? "monthly";
+ const workspacePlanPrice = planDetails?.price
+ ? planDetails.price[workspacePlanPeriod] *
+ (workspacePlanPeriod === "monthly" ? 1 : 12)
+ : null;
+
+ const handleConfirm = async () => {
+ if (isSubmitting || !workspaceId) return;
+ setIsSubmitting(true);
+ try {
+ const res = await fetch(
+ `/api/workspaces/${workspaceId}/billing/activate-paid-plan`,
+ { method: "POST" },
+ );
+ if (res.ok) {
+ await mutate();
+ queryParams({
+ set: {
+ upgraded: "true",
+ plan: plan ?? "pro",
+ },
+ replace: true,
+ scroll: false,
+ });
+ setShowModal(false);
+ } else {
+ const body = await res.json().catch(() => null);
+ const message =
+ body?.error?.message ??
+ "Failed to start paid plan. Please try again or use the billing portal.";
+ toast.error(message);
+ }
+ } catch (error) {
+ console.error(error);
+ toast.error(
+ "Failed to start paid plan. Please try again or use the billing portal.",
+ );
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="max-w-md"
+ >
+ <div className="sm:py-4.5 border-b border-neutral-200 px-4 py-3 sm:px-6">
+ <h3 className="text-lg font-medium text-neutral-900">
+ Plan start confirmation
+ </h3>
+ </div>
+
+ <div className="flex flex-col gap-4 bg-neutral-50 p-4 sm:p-6">
+ <div className="rounded-lg border border-neutral-200 bg-white p-4">
+ <p className="text-base font-semibold text-neutral-900">
+ {planDetails?.name}
+ </p>
+ {workspacePlanPrice != null && (
+ <div className="mt-1 flex flex-wrap items-baseline gap-1">
+ <NumberFlow
+ value={workspacePlanPrice}
+ className="text-sm font-medium tabular-nums text-neutral-900"
+ format={{
+ style: "currency",
+ currency: "USD",
+ minimumFractionDigits: 0,
+ }}
+ />
+ <span className="text-sm text-neutral-500">
+ per {workspacePlanPeriod.replace("ly", "")}
+ </span>
+ </div>
+ )}
+ </div>
+ <p className="text-sm text-neutral-600">
+ You&apos;ll be charged today and your trial will end.
+ </p>
+ </div>
+
+ <div className="flex items-center justify-between gap-2 border-t border-neutral-200 px-4 py-5 sm:px-6">
+ <Button
+ variant="secondary"
+ className="h-8 rounded-lg px-3 text-sm"
+ text="Cancel"
+ onClick={() => setShowModal(false)}
+ disabled={isSubmitting}
+ />
+ <Button
+ variant="primary"
+ className="h-8 rounded-lg px-3 text-sm"
+ text="Start paid plan"
+ loading={isSubmitting}
+ disabled={isSubmitting}
+ onClick={handleConfirm}
+ />
+ </div>
+ </Modal>
+ );
+}
+
+export function useStartPaidPlanModal() {
+ const [showModal, setShowModal] = useState(false);
+
+ const StartPaidPlanModalCallback = useCallback(() => {
+ return (
+ <StartPaidPlanModal showModal={showModal} setShowModal={setShowModal} />
+ );
+ }, [showModal]);
+
+ return useMemo(
+ () => ({
+ setShowStartPaidPlanModal: setShowModal,
+ StartPaidPlanModal: StartPaidPlanModalCallback,
+ }),
+ [setShowModal, StartPaidPlanModalCallback],
+ );
+}
diff --git a/apps/web/ui/modals/trial-limit-activate-modal.tsx b/apps/web/ui/modals/trial-limit-activate-modal.tsx
new file mode 100644
index 0000000000..907803ea76
--- /dev/null
+++ b/apps/web/ui/modals/trial-limit-activate-modal.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Button, Modal, useRouterStuff } from "@dub/ui";
+import {
+ getTrialLimitFeaturePhrase,
+ type TrialLimitResource,
+} from "@dub/utils";
+import { useCallback, useMemo, useState } from "react";
+import { toast } from "sonner";
+
+/**
+ * Colocate `useTrialLimitActivateModal` + `<TrialLimitActivateModal />` where you open the modal.
+ *
+ * Phrase mapping (`getTrialLimitFeaturePhrase` / `TrialLimitResource`):
+ * - links → link builder, import menu, upgrade banner
+ * - clicks → program analytics / exceeded-events surfaces, upgrade banner
+ * - payouts → upgrade banner when payouts over limit
+ * - users → `invite-teammates-form` (API `exceeded_limit` on invites)
+ * - partnerEnrollments → partner approve / bulk approve (trial enrollment cap)
+ * - networkInvites → partner network invite sheet (weekly invite limit)
+ * - freeDotLinkDomain → use where domain actions are trial-gated (add at call site)
+ */
+
+function TrialLimitActivateModalInner({
+ showModal,
+ setShowModal,
+ limitResource,
+}: {
+ showModal: boolean;
+ setShowModal: (open: boolean) => void;
+ limitResource: TrialLimitResource;
+}) {
+ const { id: workspaceId, plan, mutate } = useWorkspace();
+ const { queryParams } = useRouterStuff();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const featurePhrase = getTrialLimitFeaturePhrase(limitResource);
+
+ const handleConfirm = async () => {
+ if (isSubmitting || !workspaceId) return;
+ setIsSubmitting(true);
+ try {
+ const res = await fetch(
+ `/api/workspaces/${workspaceId}/billing/activate-paid-plan`,
+ { method: "POST" },
+ );
+ if (res.ok) {
+ await mutate();
+ queryParams({
+ set: {
+ upgraded: "true",
+ plan: plan ?? "pro",
+ },
+ replace: true,
+ scroll: false,
+ });
+ setShowModal(false);
+ } else {
+ const body = await res.json().catch(() => null);
+ const message =
+ body?.error?.message ??
+ "Could not end trial. Try again or use the billing portal.";
+ toast.error(message);
+ }
+ } catch (error) {
+ console.error(error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Could not end trial. Please try again or use the billing portal.",
+ );
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={(v) =>
+ setShowModal(typeof v === "function" ? v(showModal) : v)
+ }
+ className="max-w-md"
+ >
+ <div className="sm:py-4.5 border-b border-neutral-200 px-4 py-3 sm:px-6">
+ <h3 className="text-lg font-medium text-neutral-900">
+ Activate your plan
+ </h3>
+ </div>
+
+ <div className="flex flex-col gap-4 bg-neutral-50 p-4 sm:p-6">
+ <p className="text-sm text-neutral-600">
+ You&apos;ve hit a{" "}
+ <a
+ href="hthttps://dub.co/help/article/free-trial#trial-limits"
+ target="_blank"
+ className="cursor-help font-semibold text-neutral-800 underline decoration-dotted underline-offset-2"
+ >
+ trial limit
+ </a>
+ . In order to {featurePhrase}, you&apos;ll have to start a paid plan
+ to unlock higher limits.
+ </p>
+ </div>
+
+ <div className="flex items-center justify-between gap-2 border-t border-neutral-200 px-4 py-5 sm:px-6">
+ <Button
+ variant="secondary"
+ className="h-8 rounded-lg px-3 text-sm"
+ text="Continue trial"
+ onClick={() => setShowModal(false)}
+ disabled={isSubmitting}
+ />
+ <Button
+ variant="primary"
+ className="h-8 rounded-lg px-3 text-sm"
+ text="Start paid plan"
+ loading={isSubmitting}
+ disabled={isSubmitting}
+ onClick={handleConfirm}
+ />
+ </div>
+ </Modal>
+ );
+}
+
+export function useTrialLimitActivateModal() {
+ const [showModal, setShowModal] = useState(false);
+ const [limitResource, setLimitResource] =
+ useState<TrialLimitResource>("links");
+
+ const openTrialLimitModal = useCallback((resource: TrialLimitResource) => {
+ setLimitResource(resource);
+ setShowModal(true);
+ }, []);
+
+ const setShowTrialLimitActivateModal = useCallback(
+ (value: boolean | { open: boolean; limitResource: TrialLimitResource }) => {
+ if (typeof value === "boolean") {
+ setShowModal(value);
+ } else {
+ setLimitResource(value.limitResource);
+ setShowModal(value.open);
+ }
+ },
+ [],
+ );
+
+ const TrialLimitActivateModal = useCallback(() => {
+ return (
+ <TrialLimitActivateModalInner
+ showModal={showModal}
+ setShowModal={setShowModal}
+ limitResource={limitResource}
+ />
+ );
+ }, [showModal, limitResource]);
+
+ return useMemo(
+ () => ({
+ openTrialLimitModal,
+ setShowTrialLimitActivateModal,
+ TrialLimitActivateModal,
+ }),
+ [
+ openTrialLimitModal,
+ setShowTrialLimitActivateModal,
+ TrialLimitActivateModal,
+ ],
+ );
+}
diff --git a/apps/web/ui/modals/upgraded-modal.tsx b/apps/web/ui/modals/upgraded-modal.tsx
index 057d7b1817..0b36739531 100644
--- a/apps/web/ui/modals/upgraded-modal.tsx
+++ b/apps/web/ui/modals/upgraded-modal.tsx
@@ -1,7 +1,13 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { useWorkspaceStore } from "@/lib/swr/use-workspace-store";
import { Button, Modal, useRouterStuff, useScrollProgress } from "@dub/ui";
-import { getPlanDetails, PLANS, PRO_PLAN } from "@dub/utils";
+import {
+ capitalize,
+ getPlanDetails,
+ isWorkspaceBillingTrialActive,
+ PLANS,
+ PRO_PLAN,
+} from "@dub/utils";
import { usePlausible } from "next-plausible";
import { useSearchParams } from "next/navigation";
import {
@@ -26,7 +32,42 @@ function UpgradedModal({
const { queryParams } = useRouterStuff();
const searchParams = useSearchParams();
- const { dotLinkClaimed } = useWorkspace();
+ const {
+ dotLinkClaimed,
+ trialEndsAt,
+ loading: workspaceLoading,
+ mutate: mutateWorkspaceData,
+ } = useWorkspace();
+
+ const checkoutSuccess = searchParams.get("upgraded") === "true";
+ const [checkoutWorkspaceSynced, setCheckoutWorkspaceSynced] = useState(
+ () => !checkoutSuccess,
+ );
+
+ useEffect(() => {
+ if (!checkoutSuccess) {
+ setCheckoutWorkspaceSynced(true);
+ return;
+ }
+
+ let cancelled = false;
+ void mutateWorkspaceData().finally(() => {
+ if (!cancelled) {
+ setCheckoutWorkspaceSynced(true);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [checkoutSuccess, mutateWorkspaceData]);
+
+ const showDotLinkClaimUi =
+ checkoutWorkspaceSynced &&
+ !workspaceLoading &&
+ !dotLinkClaimed &&
+ !isWorkspaceBillingTrialActive(trialEndsAt);
+
const [_, setDotLinkOfferDismissed, { mutateWorkspace }] =
useWorkspaceStore<string>("dotLinkOfferDismissed");
@@ -39,9 +80,15 @@ function UpgradedModal({
const handlePlanUpgrade = async () => {
if (planId) {
const currentPlan = getPlanDetails({ plan: planId });
- const period = searchParams.get("period");
- if (currentPlan && period) {
+ const currentPlanPeriod = searchParams.get("period");
+ if (currentPlan && currentPlanPeriod) {
plausible(`Upgraded to ${currentPlan.name}`);
+ plausible("Upgraded Plan", {
+ props: {
+ plan: capitalize(currentPlan.name),
+ planPeriod: capitalize(currentPlanPeriod),
+ },
+ });
}
}
};
@@ -62,7 +109,9 @@ function UpgradedModal({
queryParams({
del: ["upgraded", "plan", "period"],
});
- await setDotLinkOfferDismissed(new Date().toISOString());
+ if (showDotLinkClaimUi) {
+ await setDotLinkOfferDismissed(new Date().toISOString());
+ }
mutateWorkspace();
};
@@ -87,7 +136,7 @@ function UpgradedModal({
<p className="mt-2 text-sm text-neutral-600">
Thank you for upgrading to the {plan?.name} plan. You now have
access to more powerful features
- {dotLinkClaimed ? (
+ {!showDotLinkClaimUi ? (
<> and higher usage limits.</>
) : (
<>
@@ -103,7 +152,7 @@ function UpgradedModal({
</>
)}
</p>
- {!dotLinkClaimed && (
+ {showDotLinkClaimUi && (
<div className="mt-6 rounded-xl border border-neutral-100 bg-neutral-50 p-4">
<RegisterDomainForm
showTerms={false}
@@ -123,18 +172,18 @@ function UpgradedModal({
</div>
<Button
type="button"
- variant={dotLinkClaimed ? "primary" : "secondary"}
+ variant={showDotLinkClaimUi ? "secondary" : "primary"}
text={
- dotLinkClaimed
- ? "Go to Dub"
- : "No thanks, take me to the dashboard"
+ showDotLinkClaimUi
+ ? "No thanks, take me to the dashboard"
+ : "View dashboard"
}
onClick={() => {
onClose();
setShowUpgradedModal(false);
}}
/>
- {!dotLinkClaimed && (
+ {showDotLinkClaimUi && (
<p className="mt-6 text-pretty text-center text-xs text-neutral-500">
By claiming your .link domain, you agree to our{" "}
<a
diff --git a/apps/web/ui/partners/overview/exceeded-events-limit.tsx b/apps/web/ui/partners/overview/exceeded-events-limit.tsx
index 7f7f1c0e79..30baa92f91 100644
--- a/apps/web/ui/partners/overview/exceeded-events-limit.tsx
+++ b/apps/web/ui/partners/overview/exceeded-events-limit.tsx
@@ -1,25 +1,44 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import { Lock } from "@dub/ui";
+import { isWorkspaceBillingTrialActive } from "@dub/utils";
import Link from "next/link";
export function ExceededEventsLimit() {
- const { slug } = useWorkspace();
+ const { slug, trialEndsAt } = useWorkspace();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
+
return (
- <div className="mx-auto flex size-full max-w-xs flex-col items-center justify-center gap-2">
- <Lock className="text-content-subtle size-6" />
- <h1 className="text-content-emphasis text-sm font-medium">
- Stats Locked
- </h1>
- <p className="text-content-subtle text-center text-sm">
- You have exceeded the events limit on your current plan.{" "}
- <Link
- href={`/${slug}/settings/billing`}
- className="hover:text-content-emphasis underline decoration-dotted underline-offset-2 transition-colors"
- >
- Upgrade to keep using Dub.
- </Link>
- </p>
- </div>
+ <>
+ <TrialLimitActivateModal />
+ <div className="mx-auto flex size-full max-w-xs flex-col items-center justify-center gap-2">
+ <Lock className="text-content-subtle size-6" />
+ <h1 className="text-content-emphasis text-sm font-medium">
+ Stats Locked
+ </h1>
+ <p className="text-content-subtle text-center text-sm">
+ You have exceeded the events limit on your current plan.{" "}
+ {trialActive ? (
+ <button
+ type="button"
+ onClick={() => openTrialLimitModal("clicks")}
+ className="hover:text-content-emphasis underline decoration-dotted underline-offset-2 transition-colors"
+ >
+ Start paid plan to keep using Dub.
+ </button>
+ ) : (
+ <Link
+ href={`/${slug}/settings/billing`}
+ className="hover:text-content-emphasis underline decoration-dotted underline-offset-2 transition-colors"
+ >
+ Upgrade to keep using Dub.
+ </Link>
+ )}
+ </p>
+ </div>
+ </>
);
}
diff --git a/apps/web/ui/partners/partner-network/network-partner-sheet.tsx b/apps/web/ui/partners/partner-network/network-partner-sheet.tsx
index 415c5a9481..75490a7545 100644
--- a/apps/web/ui/partners/partner-network/network-partner-sheet.tsx
+++ b/apps/web/ui/partners/partner-network/network-partner-sheet.tsx
@@ -6,6 +6,7 @@ import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { NetworkPartnerProps } from "@/lib/types";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import { X } from "@/ui/shared/icons";
import {
Button,
@@ -16,6 +17,7 @@ import {
useKeyboardShortcut,
useRouterStuff,
} from "@dub/ui";
+import { isWorkspaceBillingTrialActive } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { usePathname } from "next/navigation";
@@ -197,8 +199,11 @@ function PartnerControls({
setIsOpen: Dispatch<SetStateAction<boolean>>;
groupId?: string | null;
}) {
- const { id: workspaceId } = useWorkspace();
+ const { id: workspaceId, trialEndsAt } = useWorkspace();
const { program } = useProgram();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const pathname = usePathname();
const { executeAsync, isPending } = useAction(
@@ -210,7 +215,12 @@ function PartnerControls({
mutatePrefix(`/api/network/partners`);
},
onError({ error }) {
- toast.error(error.serverError);
+ const msg = String(error.serverError ?? "");
+ if (trialActive && msg.toLowerCase().includes("invitations limit")) {
+ openTrialLimitModal("networkInvites");
+ return;
+ }
+ toast.error(msg || "Failed to send invite.");
},
},
);
@@ -235,15 +245,25 @@ function PartnerControls({
const { remaining: remainingInvites } = usePartnerNetworkInvitesUsage();
- const disabled = remainingInvites === 0;
+ const atNetworkInviteLimit = remainingInvites === 0;
+ const disabled = atNetworkInviteLimit && !trialActive;
+
+ const handleSendInvitePress = () => {
+ if (trialActive && atNetworkInviteLimit) {
+ openTrialLimitModal("networkInvites");
+ return;
+ }
+ setShowConfirmModal(true);
+ };
- useKeyboardShortcut("s", () => setShowConfirmModal(true), {
+ useKeyboardShortcut("s", handleSendInvitePress, {
sheet: true,
- enabled: !disabled,
+ enabled: !disabled || trialActive,
});
return (
<>
+ <TrialLimitActivateModal />
{confirmModal}
<div className="flex items-center justify-end gap-2">
<div className="mr-2">
@@ -259,9 +279,9 @@ function PartnerControls({
variant="primary"
text="Send invite"
disabled={disabled}
- shortcut={disabled ? undefined : "S"}
+ shortcut={disabled && !trialActive ? undefined : "S"}
loading={isPending}
- onClick={() => setShowConfirmModal(true)}
+ onClick={handleSendInvitePress}
className="w-fit shrink-0"
/>
</div>
diff --git a/apps/web/ui/shared/password-requirements.tsx b/apps/web/ui/shared/password-requirements.tsx
index 6907859af6..b54e70e18d 100644
--- a/apps/web/ui/shared/password-requirements.tsx
+++ b/apps/web/ui/shared/password-requirements.tsx
@@ -5,6 +5,7 @@ import { useFormContext, useWatch } from "react-hook-form";
const REQUIREMENTS: {
name: string;
+ mobileName?: string;
check: (password: string) => boolean;
}[] = [
{
@@ -13,10 +14,12 @@ const REQUIREMENTS: {
},
{
name: "Uppercase letter",
+ mobileName: "Uppercase",
check: (p) => /[A-Z]/.test(p),
},
{
name: "Lowercase letter",
+ mobileName: "Lowercase",
check: (p) => /[a-z]/.test(p),
},
{
@@ -44,7 +47,7 @@ export const PasswordRequirements = memo(function PasswordRequirements({
return (
<ul className={cn("mt-2 flex flex-wrap items-center gap-3", className)}>
- {REQUIREMENTS.map(({ name, check }) => {
+ {REQUIREMENTS.map(({ name, mobileName, check }) => {
const checked = password?.length && check(password);
return (
@@ -65,7 +68,14 @@ export const PasswordRequirements = memo(function PasswordRequirements({
: "text-neutral-200",
)}
/>
- <span>{name}</span>
+ {mobileName ? (
+ <>
+ <span className="max-[420px]:hidden">{name}</span>
+ <span className="hidden max-[420px]:inline">{mobileName}</span>
+ </>
+ ) : (
+ <span>{name}</span>
+ )}
</li>
);
})}
diff --git a/apps/web/ui/workspaces/create-workspace-form.tsx b/apps/web/ui/workspaces/create-workspace-form.tsx
index 009cb80ffe..da7efd3865 100644
--- a/apps/web/ui/workspaces/create-workspace-form.tsx
+++ b/apps/web/ui/workspaces/create-workspace-form.tsx
@@ -81,9 +81,8 @@ export function CreateWorkspaceForm({
});
if (res.ok) {
- const { id: workspaceId } = await res.json();
- plausible("Created Workspace");
// track workspace creation event
+ plausible("Created Workspace");
await Promise.all([mutate("/api/workspaces"), update()]);
onSuccess?.(data);
} else {
@@ -193,7 +192,7 @@ export function CreateWorkspaceForm({
</p>
) : (
<p className="text-content-subtle mt-1.5 text-xs">
- This is used for your workspace and partner program.
+ This is used for both your workspace and your partner program.
</p>
)}
</div>
diff --git a/apps/web/ui/workspaces/invite-teammates-form.tsx b/apps/web/ui/workspaces/invite-teammates-form.tsx
index 73f8a9d5a6..a469e9bae5 100644
--- a/apps/web/ui/workspaces/invite-teammates-form.tsx
+++ b/apps/web/ui/workspaces/invite-teammates-form.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
import {
@@ -5,10 +7,11 @@ import {
WORKSPACE_ROLES,
} from "@/lib/workspace-roles";
import { Invite } from "@/lib/zod/schemas/invites";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
import { WorkspaceRole } from "@dub/prisma/client";
import { Button, useMediaQuery, useRouterStuff } from "@dub/ui";
import { Trash } from "@dub/ui/icons";
-import { cn, pluralize } from "@dub/utils";
+import { cn, isWorkspaceBillingTrialActive, pluralize } from "@dub/utils";
import { Plus } from "lucide-react";
import { useMemo } from "react";
import { useFieldArray, useForm } from "react-hook-form";
@@ -31,9 +34,12 @@ export function InviteTeammatesForm({
invites?: Invite[];
className?: string;
}) {
- const { id, slug, plan, usersLimit } = useWorkspace();
+ const { id, slug, plan, usersLimit, trialEndsAt } = useWorkspace();
const { isMobile } = useMediaQuery();
const { queryParams } = useRouterStuff();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const availableRolesForPlan = useMemo(() => {
return getAvailableRolesForPlan(plan);
@@ -55,110 +61,122 @@ export function InviteTeammatesForm({
});
return (
- <form
- onSubmit={handleSubmit(async (data) => {
- const teammates = data.teammates.filter(({ email }) => email);
- const res = await fetch(`/api/workspaces/${id}/invites`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ teammates }),
- });
+ <>
+ <TrialLimitActivateModal />
+ <form
+ onSubmit={handleSubmit(async (data) => {
+ const teammates = data.teammates.filter(({ email }) => email);
+ const res = await fetch(`/api/workspaces/${id}/invites`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ teammates }),
+ });
- if (res.ok) {
- await mutatePrefix(`/api/workspaces/${id}/invites`);
+ if (res.ok) {
+ await mutatePrefix(`/api/workspaces/${id}/invites`);
- toast.success(`${pluralize("Invitation", teammates.length)} sent!`);
- queryParams({
- set: {
- status: "invited",
- },
- });
+ toast.success(`${pluralize("Invitation", teammates.length)} sent!`);
+ queryParams({
+ set: {
+ status: "invited",
+ },
+ });
- onSuccess?.();
- } else {
- const { error } = await res.json();
- if (error.message.includes("upgrade")) {
- toast.custom(
- () => (
- <UpgradeRequiredToast
- title="Upgrade required"
- message="You've reached the invite limit for your plan. Please upgrade to invite more teammates."
- />
- ),
- { duration: 4000 },
- );
+ onSuccess?.();
} else {
- toast.error(error.message);
+ const body = await res.json().catch(() => null);
+ const error = body?.error;
+ if (trialActive && error?.code === "exceeded_limit") {
+ openTrialLimitModal("users");
+ return;
+ }
+ if (error?.message?.includes("upgrade")) {
+ if (trialActive) {
+ openTrialLimitModal("users");
+ } else {
+ toast.custom(
+ () => (
+ <UpgradeRequiredToast
+ title="Upgrade required"
+ message="You've reached the invite limit for your plan. Please upgrade to invite more teammates."
+ />
+ ),
+ { duration: 4000 },
+ );
+ }
+ return;
+ }
+ toast.error(error?.message ?? "Something went wrong");
+ if (error) throw error;
}
- throw error;
- }
- })}
- className={cn("flex flex-col gap-8 text-left", className)}
- >
- <div className="flex flex-col gap-2">
- {fields.map((field, index) => (
- <div key={field.id} className="flex items-end gap-2">
- <label className="flex-1">
- {index === 0 && (
- <span className="mb-2 block text-sm font-medium text-neutral-700">
- {pluralize("Email", fields.length)}
- </span>
- )}
- <div className="relative flex rounded-md shadow-sm">
- <input
- type="email"
- placeholder="[email protected]"
- autoFocus={index === 0 && !isMobile}
- autoComplete="off"
- className="z-10 block w-full rounded-l-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- {...register(`teammates.${index}.email`, {
- required: index === 0,
- })}
+ })}
+ className={cn("flex flex-col gap-8 text-left", className)}
+ >
+ <div className="flex flex-col gap-2">
+ {fields.map((field, index) => (
+ <div key={field.id} className="flex items-end gap-2">
+ <label className="flex-1">
+ {index === 0 && (
+ <span className="mb-2 block text-sm font-medium text-neutral-700">
+ {pluralize("Email", fields.length)}
+ </span>
+ )}
+ <div className="relative flex rounded-md shadow-sm">
+ <input
+ type="email"
+ placeholder="[email protected]"
+ autoFocus={index === 0 && !isMobile}
+ autoComplete="off"
+ className="z-10 block w-full rounded-l-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ {...register(`teammates.${index}.email`, {
+ required: index === 0,
+ })}
+ />
+ <select
+ {...register(`teammates.${index}.role`, {
+ required: index === 0,
+ })}
+ defaultValue="member"
+ className="rounded-r-md border border-l-0 border-neutral-300 bg-white pl-4 pr-8 text-neutral-600 focus:border-neutral-300 focus:outline-none focus:ring-0 sm:text-sm"
+ >
+ {WORKSPACE_ROLES.map(({ value, label }) => {
+ return (
+ <option
+ key={value}
+ value={value}
+ disabled={!availableRolesForPlan.includes(value)}
+ >
+ {label}
+ </option>
+ );
+ })}
+ </select>
+ </div>
+ </label>
+ {index > 0 && (
+ <Button
+ variant="outline"
+ icon={<Trash className="size-4" />}
+ className="h-9 w-9 shrink-0 px-0"
+ onClick={() => remove(index)}
/>
- <select
- {...register(`teammates.${index}.role`, {
- required: index === 0,
- })}
- defaultValue="member"
- className="rounded-r-md border border-l-0 border-neutral-300 bg-white pl-4 pr-8 text-neutral-600 focus:border-neutral-300 focus:outline-none focus:ring-0 sm:text-sm"
- >
- {WORKSPACE_ROLES.map(({ value, label }) => {
- return (
- <option
- key={value}
- value={value}
- disabled={!availableRolesForPlan.includes(value)}
- >
- {label}
- </option>
- );
- })}
- </select>
- </div>
- </label>
- {index > 0 && (
- <Button
- variant="outline"
- icon={<Trash className="size-4" />}
- className="h-9 w-9 shrink-0 px-0"
- onClick={() => remove(index)}
- />
- )}
- </div>
- ))}
+ )}
+ </div>
+ ))}
+ <Button
+ className="h-9 w-fit"
+ variant="secondary"
+ icon={<Plus className="size-4" />}
+ text="Add email"
+ onClick={() => append({ email: "", role: "member" })}
+ disabled={fields.length >= (usersLimit || Infinity)}
+ />
+ </div>
<Button
- className="h-9 w-fit"
- variant="secondary"
- icon={<Plus className="size-4" />}
- text="Add email"
- onClick={() => append({ email: "", role: "member" })}
- disabled={fields.length >= (usersLimit || Infinity)}
+ loading={isSubmitting || isSubmitSuccessful}
+ text={`Send ${pluralize("invite", fields.length)}`}
/>
- </div>
- <Button
- loading={isSubmitting || isSubmitSuccessful}
- text={`Send ${pluralize("invite", fields.length)}`}
- />
- </form>
+ </form>
+ </>
);
}
diff --git a/apps/web/ui/workspaces/subscription-menu.tsx b/apps/web/ui/workspaces/subscription-menu.tsx
index a1416a3ef4..ce9b0f744b 100644
--- a/apps/web/ui/workspaces/subscription-menu.tsx
+++ b/apps/web/ui/workspaces/subscription-menu.tsx
@@ -7,7 +7,6 @@ import {
Button,
DynamicTooltipWrapper,
Icon,
- LoadingSpinner,
Popover,
SquareXmark,
StripeIcon,
@@ -21,7 +20,14 @@ import { usePlanChangeConfirmationModal } from "../modals/plan-change-confirmati
import { ThreeDots } from "../shared/icons";
export default function SubscriptionMenu() {
- const { id: workspaceId, role, plan, defaultProgramId } = useWorkspace();
+ const {
+ id: workspaceId,
+ role,
+ plan,
+ defaultProgramId,
+ subscriptionCanceledAt,
+ mutate,
+ } = useWorkspace();
const router = useRouter();
const permissionsError = clientAccessCheck({
@@ -32,15 +38,12 @@ export default function SubscriptionMenu() {
const [isOpen, setIsOpen] = useState(false);
const [clicked, setClicked] = useState(false);
- const openBillingPortal = (cancel: boolean) => {
+ const openBillingPortal = () => {
setIsOpen(false);
setClicked(true);
- return fetch(
- `/api/workspaces/${workspaceId}/billing/${cancel ? "cancel" : "manage"}`,
- {
- method: "POST",
- },
- ).then(async (res) => {
+ return fetch(`/api/workspaces/${workspaceId}/billing/manage`, {
+ method: "POST",
+ }).then(async (res) => {
if (res.ok) {
const url = await res.json();
router.push(url);
@@ -52,6 +55,28 @@ export default function SubscriptionMenu() {
});
};
+ const cancelSubscription = () => {
+ setIsOpen(false);
+ setClicked(true);
+ return fetch(`/api/workspaces/${workspaceId}/billing/cancel`, {
+ method: "POST",
+ }).then(async (res) => {
+ if (res.ok) {
+ // sleep for 2 seconds to make sure Stripe webhook was received, and then mutate
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ await mutate();
+ setClicked(false);
+ toast.success(
+ "Your subscription has been scheduled for cancellation at the end of the current period.",
+ );
+ } else {
+ const { error } = await res.json();
+ toast.error(error.message);
+ setClicked(false);
+ }
+ });
+ };
+
// Check if canceling would lose partner access
const losesPartnerAccess =
plan &&
@@ -60,7 +85,10 @@ export default function SubscriptionMenu() {
const { setShowPlanChangeConfirmationModal, PlanChangeConfirmationModal } =
usePlanChangeConfirmationModal({
- onConfirm: () => openBillingPortal(true),
+ onConfirm: async () => {
+ await cancelSubscription();
+ setShowPlanChangeConfirmationModal(false);
+ },
});
const handleCancelSubscription = () => {
@@ -68,7 +96,7 @@ export default function SubscriptionMenu() {
if (losesPartnerAccess) {
setShowPlanChangeConfirmationModal(true);
} else {
- openBillingPortal(true);
+ cancelSubscription();
}
};
@@ -88,14 +116,18 @@ export default function SubscriptionMenu() {
<MenuItem
icon={StripeIcon}
label="Open billing portal"
- onSelect={() => openBillingPortal(false)}
+ onSelect={() => openBillingPortal()}
disabledTooltip={permissionsError}
/>
<MenuItem
icon={SquareXmark}
label="Cancel subscription"
onSelect={handleCancelSubscription}
- disabledTooltip={permissionsError}
+ disabledTooltip={
+ subscriptionCanceledAt
+ ? "Your subscription has already been scheduled for cancellation."
+ : permissionsError
+ }
/>
</Command.List>
</Command>
@@ -106,14 +138,8 @@ export default function SubscriptionMenu() {
type="button"
className="h-9 px-2"
variant="secondary"
- icon={
- clicked ? (
- <LoadingSpinner className="size-4 shrink-0" />
- ) : (
- <ThreeDots className="size-4 shrink-0" />
- )
- }
- disabled={clicked}
+ icon={<ThreeDots className="size-4 shrink-0" />}
+ loading={clicked}
/>
</Popover>
</>
diff --git a/apps/web/ui/workspaces/upgrade-plan-button.tsx b/apps/web/ui/workspaces/upgrade-plan-button.tsx
index 53a9e65714..baed9392ce 100644
--- a/apps/web/ui/workspaces/upgrade-plan-button.tsx
+++ b/apps/web/ui/workspaces/upgrade-plan-button.tsx
@@ -1,14 +1,23 @@
"use client";
import { wouldLosePartnerAccess } from "@/lib/plans/has-partner-access";
+import { wouldLoseAdvancedFeatures } from "@/lib/plans/would-lose-advanced-features";
import { getStripe } from "@/lib/stripe/client";
import useWorkspace from "@/lib/swr/use-workspace";
import { Button, ButtonProps } from "@dub/ui";
-import { APP_DOMAIN, capitalize, SELF_SERVE_PAID_PLANS } from "@dub/utils";
+import {
+ APP_DOMAIN,
+ capitalize,
+ DUB_TRIAL_PERIOD_DAYS,
+ isWorkspaceBillingTrialActive,
+ SELF_SERVE_PAID_PLANS,
+} from "@dub/utils";
+import { useOnboardingTrialVariant } from "app/app.dub.co/(onboarding)/onboarding/use-onboarding-trial-variant";
import { usePlausible } from "next-plausible";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { usePlanChangeConfirmationModal } from "../modals/plan-change-confirmation-modal";
+import { useStartPaidPlanModal } from "../modals/start-paid-plan-modal";
export function UpgradePlanButton({
plan,
@@ -26,11 +35,15 @@ export function UpgradePlanButton({
const {
slug: workspaceSlug,
plan: currentPlan,
+ planPeriod: currentPlanPeriod,
stripeId,
defaultProgramId,
+ trialEndsAt,
} = useWorkspace();
const plausible = usePlausible();
+ const { isTrialVariant } = useOnboardingTrialVariant();
+ const isTrialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const selectedPlan =
SELF_SERVE_PAID_PLANS.find(
@@ -41,16 +54,29 @@ export function UpgradePlanButton({
const queryString = searchParams.toString();
- const isCurrentPlan = currentPlan === selectedPlan.name.toLowerCase();
+ const isCurrentPlan =
+ currentPlan === selectedPlan.name.toLowerCase() &&
+ period === currentPlanPeriod;
- // Check if this plan change would lose partner access
- const losesPartnerAccess =
- currentPlan &&
- defaultProgramId &&
- wouldLosePartnerAccess({
- currentPlan,
- newPlan: selectedPlan.name.toLowerCase(),
- });
+ // Check if this plan change would lose partner access / advanced features
+ const { losesPartnerAccess, losesAdvancedFeatures } = useMemo(() => {
+ if (currentPlan && defaultProgramId) {
+ return {
+ losesPartnerAccess: wouldLosePartnerAccess({
+ currentPlan,
+ newPlan: selectedPlan.name.toLowerCase(),
+ }),
+ losesAdvancedFeatures: wouldLoseAdvancedFeatures({
+ currentPlan,
+ newPlan: selectedPlan.name.toLowerCase(),
+ }),
+ };
+ }
+ return {
+ losesPartnerAccess: false,
+ losesAdvancedFeatures: false,
+ };
+ }, [currentPlan, defaultProgramId, selectedPlan.name]);
const performUpgrade = () => {
setClicked(true);
@@ -65,10 +91,21 @@ export function UpgradePlanButton({
period,
baseUrl: `${APP_DOMAIN}${pathname}${queryString.length > 0 ? `?${queryString}` : ""}`,
onboarding: searchParams.get("workspace") ? "true" : "false",
+ isTrialVariant: isTrialVariant ? "true" : "false",
}),
})
.then(async (res) => {
- plausible("Opened Checkout");
+ if (!res.ok) {
+ const body = await res.json().catch(() => null);
+ throw new Error(body?.error?.message ?? "Failed to start checkout.");
+ }
+
+ plausible("Opened Checkout", {
+ props: {
+ plan: capitalize(selectedPlan.name),
+ planPeriod: capitalize(period),
+ },
+ });
if (!stripeId || currentPlan === "free") {
const data = await res.json();
const { id: sessionId } = data;
@@ -90,10 +127,21 @@ export function UpgradePlanButton({
const { setShowPlanChangeConfirmationModal, PlanChangeConfirmationModal } =
usePlanChangeConfirmationModal({
onConfirm: performUpgrade,
+ confirmationMode:
+ losesAdvancedFeatures && !losesPartnerAccess
+ ? "advanced-downgrade"
+ : "program-downgrade",
});
+ const { StartPaidPlanModal, setShowStartPaidPlanModal } =
+ useStartPaidPlanModal();
+
const handleClick = () => {
- if (losesPartnerAccess) {
+ if (isCurrentPlan && isTrialActive) {
+ setShowStartPaidPlanModal(true);
+ return;
+ }
+ if (losesPartnerAccess || losesAdvancedFeatures) {
setShowPlanChangeConfirmationModal(true);
} else {
performUpgrade();
@@ -103,16 +151,23 @@ export function UpgradePlanButton({
return (
<>
<PlanChangeConfirmationModal />
+ <StartPaidPlanModal />
<Button
text={
- isCurrentPlan
- ? "Your current plan"
- : currentPlan === "free"
- ? `Get started with ${selectedPlan.name} ${capitalize(period)}`
- : `Switch to ${selectedPlan.name} ${capitalize(period)}`
+ !currentPlan
+ ? "Loading..."
+ : isCurrentPlan
+ ? isTrialActive
+ ? "Activate plan"
+ : "Your current plan"
+ : currentPlan === "free"
+ ? isTrialVariant
+ ? `Start ${DUB_TRIAL_PERIOD_DAYS}-day trial · ${selectedPlan.name} ${capitalize(period)}`
+ : `Upgrade to ${selectedPlan.name} ${capitalize(period)}`
+ : `Switch to ${selectedPlan.name} ${capitalize(period)}`
}
- loading={clicked}
- disabled={!workspaceSlug || isCurrentPlan}
+ loading={clicked || !currentPlan}
+ disabled={!workspaceSlug || (isCurrentPlan && !isTrialActive)}
onClick={handleClick}
{...rest}
/>
diff --git a/apps/web/ui/workspaces/workspace-exceeded-events.tsx b/apps/web/ui/workspaces/workspace-exceeded-events.tsx
index 4e727c3c4e..c8d90a3df0 100644
--- a/apps/web/ui/workspaces/workspace-exceeded-events.tsx
+++ b/apps/web/ui/workspaces/workspace-exceeded-events.tsx
@@ -1,15 +1,21 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
-import { MaxWidthWrapper } from "@dub/ui";
+import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
+import { Button, MaxWidthWrapper } from "@dub/ui";
+import { isWorkspaceBillingTrialActive } from "@dub/utils";
import { CursorRays } from "../layout/sidebar/icons/cursor-rays";
import { AnimatedEmptyState } from "../shared/animated-empty-state";
export default function WorkspaceExceededEvents() {
- const { slug } = useWorkspace();
+ const { slug, trialEndsAt } = useWorkspace();
+ const { openTrialLimitModal, TrialLimitActivateModal } =
+ useTrialLimitActivateModal();
+ const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
return (
<MaxWidthWrapper>
+ <TrialLimitActivateModal />
<div className="my-10 flex flex-col items-center justify-center py-12">
<AnimatedEmptyState
title="Stats Locked"
@@ -21,9 +27,19 @@ export default function WorkspaceExceededEvents() {
</>
)}
className="border-none"
- learnMoreText="Upgrade plan"
- learnMoreHref={`/${slug}/settings/billing`}
+ learnMoreText={trialActive ? undefined : "Upgrade plan"}
+ learnMoreHref={trialActive ? undefined : `/${slug}/settings/billing`}
learnMoreTarget="_self"
+ addButton={
+ trialActive ? (
+ <Button
+ variant="primary"
+ text="Start paid plan"
+ className="h-9"
+ onClick={() => openTrialLimitModal("clicks")}
+ />
+ ) : undefined
+ }
/>
</div>
</MaxWidthWrapper>
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 788ef62275..453887ac46 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -32,6 +32,10 @@
"path": "/api/cron/pending-applications-summary",
"schedule": "0 9 * * *"
},
+ {
+ "path": "/api/cron/trial-emails",
+ "schedule": "0 * * * *"
+ },
{
"path": "/api/cron/payouts/aggregate-due-commissions",
"schedule": "0 * * * *"
diff --git a/packages/email/src/templates/advanced-plan-downgrade-notice.tsx b/packages/email/src/templates/advanced-plan-downgrade-notice.tsx
new file mode 100644
index 0000000000..d2ed8eefb4
--- /dev/null
+++ b/packages/email/src/templates/advanced-plan-downgrade-notice.tsx
@@ -0,0 +1,118 @@
+import { DUB_WORDMARK } from "@dub/utils";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { Footer } from "../components/footer";
+
+export default function AdvancedPlanDowngradeNotice({
+ email = "[email protected]",
+ workspace = {
+ name: "Acme",
+ slug: "acme",
+ },
+}: {
+ email: string;
+ workspace: {
+ name: string;
+ slug: string;
+ };
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ Removed features: Email campaigns, messaging center, advanced reward
+ conditions, fraud detection, embedded referral dashboard
+ </Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img src={DUB_WORDMARK} height="32" alt="Dub" />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-xl font-medium text-black">
+ Advanced plan features have been removed
+ </Heading>
+ <Text className="text-sm leading-6 text-black">
+ Your workspace <strong>{workspace.name}</strong> is no longer on
+ the Advanced plan. We have applied the following changes to match
+ your current subscription:
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ •{" "}
+ <Link
+ href="https://dub.co/help/article/email-campaigns"
+ className="font-medium text-black underline underline-offset-2"
+ >
+ Email campaigns
+ </Link>{" "}
+ have been paused or canceled.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ •{" "}
+ <Link
+ href="https://dub.co/help/article/messaging-partners"
+ className="font-medium text-black underline underline-offset-2"
+ >
+ Messaging center
+ </Link>{" "}
+ has been disabled.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ •{" "}
+ <Link
+ href="https://dub.co/help/article/partner-rewards"
+ className="font-medium text-black underline underline-offset-2"
+ >
+ Advanced reward conditions
+ </Link>{" "}
+ have been removed.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ •{" "}
+ <Link
+ href="https://dub.co/help/article/fraud-detection"
+ className="font-medium text-black underline underline-offset-2"
+ >
+ Fraud events
+ </Link>{" "}
+ are still being tracked, but you need to upgrade to view them.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ • If you've set up the{" "}
+ <Link
+ href="https://dub.co/docs/partners/embedded-referrals"
+ className="font-medium text-black underline underline-offset-2"
+ >
+ Embedded Referral Dashboard
+ </Link>
+ , it will no longer work.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ To reactivate these features, please upgrade to the Advanced plan.
+ </Text>
+ <Section className="mb-8 mt-8">
+ <Link
+ className="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ href={`https://app.dub.co/${workspace.slug}/settings/billing/upgrade?plan=advanced`}
+ >
+ Upgrade to Advanced
+ </Link>
+ </Section>
+ <Footer email={email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/packages/email/src/templates/program-welcome.tsx b/packages/email/src/templates/program-welcome.tsx
index 92cd5df24e..dedf8255ae 100644
--- a/packages/email/src/templates/program-welcome.tsx
+++ b/packages/email/src/templates/program-welcome.tsx
@@ -21,6 +21,7 @@ import {
} from "@react-email/components";
import { Footer } from "../components/footer";
+// only sent for existing workspaces that create a program outside of workspace onboarding
export default function ProgramWelcome({
email = "[email protected]",
workspace = {
@@ -54,10 +55,7 @@ export default function ProgramWelcome({
<Section className="mt-8">
<Img src={DUB_WORDMARK} height="32" alt="Dub" />
</Section>
- <Heading
- className="mt-8 text-lg font-semibold leading-7 text-neutral-900"
- as="h2"
- >
+ <Heading className="mt-8 text-lg font-semibold leading-7 text-neutral-900">
Congratulations on creating a program!
</Heading>
<Text className="mb-6 mt-5 text-sm leading-5 text-neutral-600">
@@ -93,36 +91,33 @@ export default function ProgramWelcome({
</Column>
</Row>
</Section>
- <Heading
- className="mb-6 text-base font-semibold leading-6 text-neutral-900"
- as="h3"
- >
+ <Heading className="mb-6 text-base font-semibold leading-6 text-neutral-900">
Getting started
</Heading>
<Text className="mb-4 text-sm leading-5 text-neutral-800">
- 1.{" "}
- <span className="font-medium">
- Create your program application form
- </span>
- : Use our{" "}
+ 1. <span className="font-medium">Connect your bank account</span>:{" "}
<Link
- href={`${workspaceUrlPrefix}/program/groups/default/branding`}
+ href="https://dub.co/help/article/how-to-set-up-bank-account"
className="font-semibold text-neutral-800 underline underline-offset-2"
>
- interactive builder
+ Set up a bank account
</Link>{" "}
- to create a beautiful, branded program application form to get
- more partners applying to join your program.
+ to start paying out commissions to your partners.
</Text>
+
<Text className="mb-4 text-sm leading-5 text-neutral-800">
- 2. <span className="font-medium">Connect your bank account</span>:{" "}
+ 2.{" "}
+ <span className="font-medium">
+ Create your program application form
+ </span>
+ : Use our{" "}
<Link
- href="https://dub.co/help/article/how-to-set-up-bank-account"
+ href={`${workspaceUrlPrefix}/program/groups/default/branding`}
className="font-semibold text-neutral-800 underline underline-offset-2"
>
- Set up a bank account
+ interactive builder
</Link>{" "}
- to start paying out commissions to your partners.
+ to create a beautiful, branded program application form.
</Text>
<Text className="mb-4 text-sm leading-5 text-neutral-800">
3. <span className="font-medium">Set up conversion tracking</span>
diff --git a/packages/email/src/templates/trial/styles-constants.ts b/packages/email/src/templates/trial/styles-constants.ts
new file mode 100644
index 0000000000..dfa7e96773
--- /dev/null
+++ b/packages/email/src/templates/trial/styles-constants.ts
@@ -0,0 +1,39 @@
+import type { CSSProperties } from "react";
+
+/** Gmail-style stack — matches “pasted from compose” HTML. */
+export const fontFamily = "Helvetica Neue, Liberation Sans, Arial, sans-serif";
+
+export const bodyStyle: CSSProperties = {
+ backgroundColor: "#ffffff",
+ color: "#222222",
+ fontFamily,
+ fontSize: 13,
+ lineHeight: "20px",
+ margin: 0,
+ padding: "16px 20px",
+};
+
+export const pStyle: CSSProperties = {
+ margin: "0 0 16px",
+};
+
+export const linkStyle: CSSProperties = {
+ color: "#1a0dab",
+ textDecoration: "underline",
+ fontFamily,
+ fontSize: 13,
+};
+
+export const footerStyle: CSSProperties = {
+ margin: "24px 0 0",
+ fontSize: 10,
+ lineHeight: "16px",
+ color: "#999999",
+ fontFamily,
+};
+
+export const footerLinkStyle: CSSProperties = {
+ ...linkStyle,
+ color: "#999999",
+ fontSize: 10,
+};
diff --git a/packages/email/src/templates/trial/trial-3-days-remaining.tsx b/packages/email/src/templates/trial/trial-3-days-remaining.tsx
new file mode 100644
index 0000000000..a21ff4d868
--- /dev/null
+++ b/packages/email/src/templates/trial/trial-3-days-remaining.tsx
@@ -0,0 +1,76 @@
+import { capitalize } from "@dub/utils";
+import { Body, Head, Html, Link, Preview, Text } from "@react-email/components";
+import { type TrialMarketingEmailProps } from "../../types";
+import {
+ bodyStyle,
+ footerLinkStyle,
+ footerStyle,
+ linkStyle,
+ pStyle,
+} from "./styles-constants";
+
+export default function Trial3DaysRemainingEmail({
+ name = "Dave",
+ plan = "business",
+ workspaceSlug = "acme",
+}: TrialMarketingEmailProps) {
+ const dashboardUrlPrefix = `https://app.dub.co/${workspaceSlug}`;
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ Don't forget to review your selected plan and billing details.
+ </Preview>
+ <Body style={bodyStyle}>
+ <Text style={pStyle}>Hi {name ? name.split(" ")[0] : "there"},</Text>
+
+ <Text style={pStyle}>
+ How are things going on your end? You have 3 days left in your Dub{" "}
+ {capitalize(plan)} trial, so I wanted to reach out before your trial
+ ends to make sure you have everything you need.
+ </Text>
+
+ <Text style={pStyle}>
+ If something is blocking you, just reply to this email and we'd be
+ happy to help you out.
+ </Text>
+
+ <Text style={pStyle}>
+ If Dub is indeed a perfect fit (and I really hope it is!), please
+ double-check your{" "}
+ <Link
+ href={`${dashboardUrlPrefix}/settings/billing`}
+ style={linkStyle}
+ >
+ billing details
+ </Link>{" "}
+ to ensure you have the right card on file, so your plan can be
+ activated with no issues.
+ </Text>
+
+ <Text style={pStyle}>
+ Always here if you have any questions or feedback!
+ </Text>
+
+ <Text style={{ ...pStyle, marginBottom: 0 }}>
+ Best,
+ <br />
+ Steven – Founder,{" "}
+ <Link href="https://dub.co" style={linkStyle}>
+ Dub.co
+ </Link>
+ </Text>
+
+ <Text style={footerStyle}>
+ If you&apos;d like me to stop sending you emails, please{" "}
+ <Link
+ href="https://app.dub.co/account/settings"
+ style={footerLinkStyle}
+ >
+ click here
+ </Link>
+ </Text>
+ </Body>
+ </Html>
+ );
+}
diff --git a/packages/email/src/templates/trial/trial-7-days-remaining.tsx b/packages/email/src/templates/trial/trial-7-days-remaining.tsx
new file mode 100644
index 0000000000..a4a74259aa
--- /dev/null
+++ b/packages/email/src/templates/trial/trial-7-days-remaining.tsx
@@ -0,0 +1,69 @@
+import { capitalize } from "@dub/utils";
+import { Body, Head, Html, Link, Preview, Text } from "@react-email/components";
+import { type TrialMarketingEmailProps } from "../../types";
+import {
+ bodyStyle,
+ footerLinkStyle,
+ footerStyle,
+ linkStyle,
+ pStyle,
+} from "./styles-constants";
+
+export default function Trial7DaysRemainingEmail({
+ name = "Dave",
+ plan = "business",
+}: TrialMarketingEmailProps) {
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ Here are some resources to help you get the most out of your Dub trial.
+ </Preview>
+ <Body style={bodyStyle}>
+ <Text style={pStyle}>Hi {name ? name.split(" ")[0] : "there"},</Text>
+
+ <Text style={pStyle}>
+ We're officially halfway through your Dub {capitalize(plan)} trial, so
+ I wanted to check in here and see if you need any help – do you have
+ any questions or blockers?
+ </Text>
+
+ <Text style={pStyle}>
+ If you haven't already, please check out our{" "}
+ <Link href="https://dub.co/help" style={linkStyle}>
+ help center
+ </Link>{" "}
+ and{" "}
+ <Link href="https://dub.co/docs" style={linkStyle}>
+ documentation
+ </Link>{" "}
+ to learn more about Dub and our various use cases.
+ </Text>
+
+ <Text style={pStyle}>
+ Excited to see how you plan to use Dub! Thank you for giving us a
+ chance 🙏
+ </Text>
+
+ <Text style={{ ...pStyle, marginBottom: 0 }}>
+ Best,
+ <br />
+ Steven – Founder,{" "}
+ <Link href="https://dub.co" style={linkStyle}>
+ Dub.co
+ </Link>
+ </Text>
+
+ <Text style={footerStyle}>
+ If you&apos;d like me to stop sending you emails, please{" "}
+ <Link
+ href="https://app.dub.co/account/settings"
+ style={footerLinkStyle}
+ >
+ click here
+ </Link>
+ </Text>
+ </Body>
+ </Html>
+ );
+}
diff --git a/packages/email/src/templates/trial/trial-started.tsx b/packages/email/src/templates/trial/trial-started.tsx
new file mode 100644
index 0000000000..c91f43c2e0
--- /dev/null
+++ b/packages/email/src/templates/trial/trial-started.tsx
@@ -0,0 +1,304 @@
+import {
+ capitalize,
+ DUB_LOGO,
+ DUB_TRIAL_PERIOD_DAYS,
+ DUB_WORDMARK,
+ getPrettyUrl,
+} from "@dub/utils";
+import {
+ Body,
+ Column,
+ Container,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Row,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { Footer } from "../../components/footer";
+import { type TrialMarketingEmailProps } from "../../types";
+
+export default function TrialStartedEmail({
+ email = "[email protected]",
+ plan = "Advanced",
+ workspace = {
+ slug: "acme",
+ logo: DUB_LOGO,
+ name: "Acme",
+ },
+ program,
+}: Omit<TrialMarketingEmailProps, "workspaceSlug"> & {
+ workspace: {
+ slug: string;
+ logo: string | null;
+ name: string;
+ };
+ program?: {
+ slug: string;
+ name: string;
+ logo: string | null;
+ };
+}) {
+ const planLabel = capitalize(plan);
+ const dashboardUrl = `https://app.dub.co/${workspace.slug}`;
+
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ {String(DUB_TRIAL_PERIOD_DAYS)} days of Dub — domains, tracking,
+ partners, and API. Here are your first steps.
+ </Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img src={DUB_WORDMARK} height="32" alt="Dub" />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-xl font-semibold text-black">
+ Welcome to your free {String(DUB_TRIAL_PERIOD_DAYS)}-day trial of
+ Dub!
+ </Heading>
+
+ <Text className="mb-6 mt-5 text-sm leading-5 text-neutral-600">
+ {program
+ ? `Your program ${program.name} is set up and ready for you to share with your partners.`
+ : "Your workspace is set up and ready for you to collaborate with your teammates."}
+ </Text>
+ <Section className="mb-6 rounded-xl border border-solid border-neutral-200 bg-neutral-50 px-6 py-4">
+ <Row>
+ <Column width={10}>
+ <Img
+ src={program?.logo || workspace.logo || DUB_LOGO}
+ alt={program?.name || workspace.name}
+ height="32"
+ width="32"
+ className="mr-4 rounded-md"
+ />
+ </Column>
+
+ <Column>
+ <Text className="text-md m-0 text-base font-semibold leading-none text-neutral-800">
+ {program?.name || workspace.name}
+ </Text>
+
+ <Link
+ href={`${dashboardUrl}/${program ? "program" : "links"}`}
+ className="m-0 text-xs font-medium text-neutral-800 underline"
+ >
+ {getPrettyUrl(
+ `${dashboardUrl}/${program ? "program" : "links"}`,
+ )}
+ </Link>
+ </Column>
+ </Row>
+ </Section>
+
+ <Heading className="mx-0 mb-6 p-0 text-base font-semibold text-black">
+ Here&apos;s what you can do next:
+ </Heading>
+
+ {program ? (
+ <>
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 1.{" "}
+ <span className="font-semibold text-black">
+ Connect your bank account
+ </span>
+ :{" "}
+ <Link
+ href="https://dub.co/help/article/how-to-set-up-bank-account"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ Set up a bank account
+ </Link>{" "}
+ to start paying out commissions to your partners.
+ </Text>
+
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 2.{" "}
+ <span className="font-semibold text-black">
+ Create your program application form
+ </span>
+ : Use our{" "}
+ <Link
+ href={`${dashboardUrl}/program/groups/default/branding`}
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ interactive builder
+ </Link>{" "}
+ to create a beautiful, branded program application form.
+ </Text>
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 3.{" "}
+ <span className="font-semibold text-black">
+ Set up conversion tracking
+ </span>
+ :{" "}
+ <Link
+ href={`${dashboardUrl}/settings/tracking`}
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ Follow our quickstart guide
+ </Link>{" "}
+ to set up conversion tracking for your program.
+ </Text>
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 4.{" "}
+ <span className="font-semibold text-black">
+ Invite your partners
+ </span>
+ : Easily{" "}
+ <Link
+ href={`${dashboardUrl}/program/partners`}
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ invite influencers, affiliates, and users
+ </Link>{" "}
+ to your program, or{" "}
+ <Link
+ href="https://dub.co/docs/partners/embedded-referrals"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ enroll them automatically.
+ </Link>
+ </Text>
+ <Text className="mb-0 text-sm leading-5 text-neutral-800">
+ 5.{" "}
+ <span className="font-semibold text-black">
+ Create more rewards
+ </span>{" "}
+ - Set up{" "}
+ <Link
+ href={`${dashboardUrl}/program/rewards`}
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ click, lead, and sale-based rewards
+ </Link>{" "}
+ to incentivize your partners to drive more traffic and
+ conversions.
+ </Text>
+ </>
+ ) : (
+ <>
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 1.{" "}
+ <span className="font-semibold text-black">
+ Use a custom domain
+ </span>
+ :{" "}
+ <Link
+ href="https://dub.co/help/article/how-to-add-custom-domain"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ Add a custom domain
+ </Link>{" "}
+ to increase trust and click-through rates on every link.
+ </Text>
+
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 2.{" "}
+ <span className="font-semibold text-black">
+ Customize your link preview
+ </span>
+ :{" "}
+ <Link
+ href="https://dub.co/help/article/custom-link-previews"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ Control the title, image, and description
+ </Link>{" "}
+ to improve how your links appear and perform.
+ </Text>
+
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 3.{" "}
+ <span className="font-semibold text-black">
+ Explore analytics
+ </span>
+ :{" "}
+ <Link
+ href="https://dub.co/help/article/dub-analytics"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ View the performance
+ </Link>{" "}
+ of your links with real-time data and advanced filtering
+ capabilities.
+ </Text>
+
+ <Text className="mb-4 text-sm leading-5 text-neutral-800">
+ 4.{" "}
+ <span className="font-semibold text-black">
+ Invite your teammates
+ </span>
+ :{" "}
+ <Link
+ href="https://dub.co/help/article/how-to-invite-teammates"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ Learn how to invite teammates
+ </Link>{" "}
+ to your workspace and start collaborating.
+ </Text>
+
+ <Text className="mb-0 text-sm leading-5 text-neutral-800">
+ 5.{" "}
+ <span className="font-semibold text-black">
+ Explore the API
+ </span>
+ :{" "}
+ <Link
+ href="https://dub.co/docs/api-reference/links/create"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ Check out our docs
+ </Link>{" "}
+ to learn how to programmatically manage your Dub links.
+ </Text>
+ </>
+ )}
+
+ <Hr />
+
+ <Text className="mb-8 text-sm leading-5 text-neutral-800">
+ You&apos;ll have access to all{" "}
+ <Link
+ href={`https://app.dub.co/${workspace.slug}/settings/billing/upgrade`}
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ {planLabel} features
+ </Link>{" "}
+ during your trial, with{" "}
+ <Link
+ href="https://dub.co/help/article/free-trial#trial-limits"
+ className="font-medium text-neutral-500 underline underline-offset-2"
+ >
+ trial usage limits
+ </Link>{" "}
+ in place. To remove these limits, you can activate your paid plan
+ at any time.
+ </Text>
+
+ <Section className="my-8">
+ <Link
+ className="rounded-lg bg-black px-4 py-2.5 text-center text-[14px] font-medium text-white no-underline"
+ href={dashboardUrl}
+ >
+ Go to your dashboard
+ </Link>
+ </Section>
+
+ <Footer email={email} marketing />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/packages/email/src/templates/upgrade-email.tsx b/packages/email/src/templates/upgrade-email.tsx
index 462261e9ed..f8ec5544e3 100644
--- a/packages/email/src/templates/upgrade-email.tsx
+++ b/packages/email/src/templates/upgrade-email.tsx
@@ -1,86 +1,63 @@
-import { DUB_WORDMARK, getPlanDetails } from "@dub/utils";
+import { capitalize } from "@dub/utils";
+import { Body, Head, Html, Link, Preview, Text } from "@react-email/components";
import {
- Body,
- Container,
- Head,
- Heading,
- Html,
- Img,
- Link,
- Preview,
- Section,
- Tailwind,
- Text,
-} from "@react-email/components";
-import { Footer } from "../components/footer";
+ bodyStyle,
+ footerLinkStyle,
+ footerStyle,
+ linkStyle,
+ pStyle,
+} from "./trial/styles-constants";
export default function UpgradeEmail({
name = "Brendon Urie",
- email = "[email protected]",
plan = "Business",
- planTier = 1,
}: {
name: string | null;
email: string;
plan: string;
- planTier: number;
}) {
- const planDetails = getPlanDetails({ plan, planTier });
return (
<Html>
<Head />
- <Preview>Thank you for upgrading to Dub {plan}!</Preview>
- <Tailwind>
- <Body className="mx-auto my-auto bg-white font-sans">
- <Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
- <Section className="mt-8">
- <Img src={DUB_WORDMARK} height="32" alt="Dub" />
- </Section>
- <Heading className="mx-0 my-7 p-0 text-xl font-medium text-black">
- Thank you for upgrading to Dub {plan}!
- </Heading>
- <Section className="my-8">
- <Img
- src="https://assets.dub.co/misc/thank-you-thumbnail.jpg"
- alt="Thank you"
- className="max-w-[500px]"
- />
- </Section>
- <Text className="text-sm leading-6 text-black">
- Hey{name && ` ${name}`}!
- </Text>
- <Text className="text-sm leading-6 text-black">
- My name is Steven, and I'm the founder of Dub.
- </Text>
- <Text className="text-sm leading-6 text-black">
- I wanted to personally reach out to thank you for upgrading to{" "}
- <strong>Dub {plan}</strong>! Your support means the world to us
- and helps us continue to build and improve Dub.
- </Text>
- <Text className="text-sm leading-6 text-black">
- On the {plan} plan, you now have access to:
- </Text>
- {planDetails.features?.map((feature) => (
- <Text className="ml-1 text-sm leading-4 text-black">
- ✦{" "}
- {feature.tooltip?.href ? (
- <Link href={feature.tooltip.href}>{feature.text}</Link>
- ) : (
- feature.text
- )}
- </Text>
- ))}
- <Text className="text-sm leading-6 text-black">
- If you have any questions or feedback about Dub, please don't
- hesitate to reach out – I'm always happy to help!
- </Text>
- <Text className="text-sm font-light leading-6 text-neutral-400">
- Steven from Dub
- </Text>
- <Footer email={email} marketing />
- </Container>
- </Body>
- </Tailwind>
+ <Preview>
+ Feel free to reach out if you have any questions or feedback!
+ </Preview>
+ <Body style={bodyStyle}>
+ <Text style={pStyle}>Hi {name ? name.split(" ")[0] : "there"},</Text>
+
+ <Text style={pStyle}>
+ My name is Steven, and I&apos;m the founder of Dub. I wanted to
+ personally reach out to thank you for upgrading to{" "}
+ <strong>Dub {capitalize(plan)}</strong>! Your support means the world
+ to us and helps us continue to build and improve Dub.
+ </Text>
+
+ <Text style={pStyle}>
+ If you have any questions or feedback about Dub, please don&apos;t
+ hesitate to reach out (you can just reply to this email) – I&apos;m
+ always happy to help!
+ </Text>
+
+ <Text style={{ ...pStyle, marginBottom: 0 }}>
+ Best,
+ <br />
+ Steven – Founder,{" "}
+ <Link href="https://dub.co" style={linkStyle}>
+ Dub.co
+ </Link>
+ </Text>
+
+ <Text style={footerStyle}>
+ If you don't want to receive these emails, you can adjust your email
+ preferences{" "}
+ <Link
+ href="https://app.dub.co/account/settings"
+ style={footerLinkStyle}
+ >
+ here
+ </Link>
+ </Text>
+ </Body>
</Html>
);
}
diff --git a/packages/email/src/templates/welcome-email.tsx b/packages/email/src/templates/welcome-email.tsx
index 1d2d006179..64feccd3af 100644
--- a/packages/email/src/templates/welcome-email.tsx
+++ b/packages/email/src/templates/welcome-email.tsx
@@ -20,8 +20,6 @@ import { Footer } from "../components/footer";
export default function WelcomeEmail({
email = "[email protected]",
workspace,
- program,
- hasDubPartners = true,
unsubscribeUrl,
}: {
email: string;
@@ -30,12 +28,6 @@ export default function WelcomeEmail({
name: string;
logo: string | null;
};
- program?: {
- slug: string;
- name: string;
- logo: string | null;
- };
- hasDubPartners?: boolean;
unsubscribeUrl: string;
}) {
const workspaceUrl = workspace
@@ -96,200 +88,77 @@ export default function WelcomeEmail({
<Hr />
)}
- {program && (
- <>
- <Heading className="mx-0 mb-2 p-0 text-base font-semibold text-black">
- Your program
- </Heading>
- <Section className="mb-6 rounded-xl border border-solid border-neutral-200 bg-neutral-50 p-4">
- <Row>
- <Column width={10}>
- <Img
- src={program.logo || DUB_THUMBNAIL}
- alt={program.name}
- height="32"
- width="32"
- className="mr-4 rounded-md"
- />
- </Column>
-
- <Column>
- <Text className="text-md m-0 text-base font-semibold leading-none text-neutral-800">
- {program.name}
- </Text>
-
- <Link
- href={`${workspaceUrl}/program`}
- className="m-0 text-xs font-medium text-neutral-600 underline"
- >
- {getPrettyUrl(`${workspaceUrl}/program`)}
- </Link>
- </Column>
- </Row>
- </Section>
- </>
- )}
-
<Heading className="mx-0 mb-0 mt-6 p-0 text-base font-semibold text-black">
- {hasDubPartners ? "Complete setup" : "Getting started"}
+ Getting started
</Heading>
<Text className="mb-6 mt-0 text-sm leading-6 text-neutral-600">
- {program
- ? "Finish setting up your program to get the most out of Dub Partners."
- : "Get familiar with Dub by exploring the platform and features."}
+ Get familiar with Dub by exploring the platform and features.
</Text>
- {program ? (
- <>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 1. Set up conversion tracking:{" "}
- <Link
- href="https://dub.co/docs/conversions/quickstart"
- className="text-neutral-600 underline underline-offset-2"
- >
- Follow our quickstart guide
- </Link>{" "}
- to set up conversion tracking for your program.
- </Text>
-
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 2. Create your program application form: Use our{" "}
- <Link
- href="https://dub.co/help/article/program-application-form"
- className="text-neutral-600 underline underline-offset-2"
- >
- interactive builder
- </Link>{" "}
- to create a beautiful, branded program application page to get
- more partners applying to join your program.
- </Text>
-
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 3. Connect your bank account:{" "}
- <Link
- href="https://dub.co/help/article/how-to-set-up-bank-account"
- className="text-neutral-600 underline underline-offset-2"
- >
- Set up a bank account
- </Link>{" "}
- to start paying out commissions to your partners.
- </Text>
-
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 4. Invite your partners: Easily{" "}
- <Link
- href="https://dub.co/help/article/inviting-partners"
- className="text-neutral-600 underline underline-offset-2"
- >
- Invite influencers, affiliates, and users
- </Link>{" "}
- to your program, or{" "}
- <Link
- href="https://dub.co/help/article/inviting-partners#enrolling-a-partner-automatically"
- className="text-neutral-600 underline underline-offset-2"
- >
- enroll them automatically.
- </Link>
- </Text>
-
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 5. Create more rewards: Set up{" "}
- <Link
- href="https://dub.co/help/article/partner-rewards"
- className="text-neutral-600 underline underline-offset-2"
- >
- click, lead, and sale-based rewards
- </Link>{" "}
- to incentivize your partners to drive more traffic and
- conversions.
- </Text>
- </>
- ) : (
- <>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 1. Set up your domain:{" "}
- <Link
- href="https://dub.co/help/article/how-to-add-custom-domain"
- className="text-neutral-600 underline underline-offset-2"
- >
- Add a custom domain
- </Link>{" "}
- or{" "}
- <Link
- href="https://dub.co/help/article/free-dot-link-domain"
- className="text-neutral-600 underline underline-offset-2"
- >
- claim a free .link domain
- </Link>{" "}
- and start creating your branded short links.
- </Text>
+ <Text className="mb-4 text-sm leading-6 text-neutral-600">
+ 1. Set up your domain:{" "}
+ <Link
+ href="https://dub.co/help/article/how-to-add-custom-domain"
+ className="text-neutral-600 underline underline-offset-2"
+ >
+ Add a custom domain
+ </Link>{" "}
+ or{" "}
+ <Link
+ href="https://dub.co/help/article/free-dot-link-domain"
+ className="text-neutral-600 underline underline-offset-2"
+ >
+ claim a free .link domain
+ </Link>{" "}
+ and start creating your branded short links.
+ </Text>
- {hasDubPartners ? (
- <>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 2. Track conversions:{" "}
- <Link
- href="https://app.dub.co/settings/tracking"
- className="text-neutral-600 underline underline-offset-2"
- >
- Install the Dub tracking script
- </Link>{" "}
- to track your short link and partner conversions.
- </Text>
+ <Text className="mb-4 text-sm leading-6 text-neutral-600">
+ 2. Track conversions:{" "}
+ <Link
+ href="https://app.dub.co/settings/tracking"
+ className="text-neutral-600 underline underline-offset-2"
+ >
+ Install the Dub tracking script
+ </Link>{" "}
+ to track your short link and partner conversions.
+ </Text>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 3. Create a program:{" "}
- <Link
- href="https://dub.co/docs/partners/quickstart"
- className="text-neutral-600 underline underline-offset-2"
- >
- Set up your Dub partner program
- </Link>{" "}
- to grow your revenue on autopilot with advanced reward
- structures, dual-sided incentives, and real-time
- attribution.
- </Text>
- </>
- ) : (
- <>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 2. Create a short link:{" "}
- <Link
- href="https://dub.co/help/article/how-to-create-link"
- className="text-neutral-600 underline underline-offset-2"
- >
- Create your first Dub short link
- </Link>{" "}
- and explore the different features available.
- </Text>
+ <Text className="mb-4 text-sm leading-6 text-neutral-600">
+ 3. Create a program:{" "}
+ <Link
+ href="https://dub.co/help/article/setting-up-your-program"
+ className="text-neutral-600 underline underline-offset-2"
+ >
+ Set up your Dub partner program
+ </Link>{" "}
+ to grow your revenue on autopilot with advanced reward structures,
+ dual-sided incentives, and real-time attribution.
+ </Text>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 3. Explore analytics:{" "}
- <Link
- href="https://dub.co/help/article/dub-analytics"
- className="text-neutral-600 underline underline-offset-2"
- >
- View the performance
- </Link>{" "}
- of your short links with graphs and detailed analytics.
- </Text>
- </>
- )}
+ <Text className="mb-4 text-sm leading-6 text-neutral-600">
+ 4. Explore analytics:{" "}
+ <Link
+ href="https://dub.co/help/article/dub-analytics"
+ className="text-neutral-600 underline underline-offset-2"
+ >
+ View the performance
+ </Link>{" "}
+ of your links with graphs and detailed analytics.
+ </Text>
- <Text className="mb-4 text-sm leading-6 text-neutral-600">
- 4. Explore the API:{" "}
- <Link
- href="https://dub.co//docs"
- className="text-neutral-600 underline underline-offset-2"
- >
- Check out our docs
- </Link>{" "}
- for programmatic link creation
- {hasDubPartners ? " and partner management" : ""}.
- </Text>
- </>
- )}
+ <Text className="mb-4 text-sm leading-6 text-neutral-600">
+ 5. Explore the API:{" "}
+ <Link
+ href="https://dub.co/docs"
+ className="text-neutral-600 underline underline-offset-2"
+ >
+ Check out our docs
+ </Link>{" "}
+ to learn how to programmatically manage your Dub links and
+ partners.
+ </Text>
<Section className="my-8">
<Link
diff --git a/packages/email/src/types.ts b/packages/email/src/types.ts
index ecf13a99f3..7b50fd7d7e 100644
--- a/packages/email/src/types.ts
+++ b/packages/email/src/types.ts
@@ -10,6 +10,13 @@ export type WorkspaceProps = {
export type PartnerPayoutMethod = "connect" | "stablecoin" | "paypal";
+export type TrialMarketingEmailProps = {
+ email: string;
+ name?: string | null;
+ plan: string;
+ workspaceSlug: string;
+};
+
// constants
export const STABLECOIN_PAYOUT_FEE_RATE = 0.005;
export const MIN_WITHDRAWAL_AMOUNT_CENTS = 10_00;
diff --git a/packages/prisma/client.ts b/packages/prisma/client.ts
index 141719a72e..ccfb957cf3 100644
--- a/packages/prisma/client.ts
+++ b/packages/prisma/client.ts
@@ -25,6 +25,7 @@ export {
PartnerLinkStructure,
PartnerProfileType,
PartnerRole,
+ PlanPeriod,
PayoutMode,
PayoutStatus,
PlatformType,
diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prisma
index f5ab0f5742..72377bcd45 100644
--- a/packages/prisma/schema/workspace.prisma
+++ b/packages/prisma/schema/workspace.prisma
@@ -1,3 +1,10 @@
+enum PlanPeriod {
+ monthly
+ yearly
+ quarterly
+ biweekly
+}
+
model Project {
id String @id @default(cuid())
name String
@@ -8,8 +15,12 @@ model Project {
plan String @default("free")
planTier Int @default(1)
+ planPeriod PlanPeriod? // monthly, yearly, etc. from Stripe price.recurring.interval
stripeId String? @unique // Stripe subscription ID
billingCycleStart Int // day of the month when the billing cycle starts
+ billingCycleEndsAt DateTime? // derived from Stripe current_period_end
+ trialEndsAt DateTime? // when set and in the future, the workspace is on a Stripe subscription free trial
+ subscriptionCanceledAt DateTime? // when the workspace's subscription was canceled (or set to cancel)
paymentFailedAt DateTime?
invoicePrefix String? @unique // prefix used to generate unique invoice numbers (for Dub Payouts)
@@ -80,6 +91,7 @@ model Project {
yearInReviews YearInReview[]
@@index(usageLastChecked(sort: Asc))
+ @@index(trialEndsAt)
}
enum WorkspaceRole {
@@ -116,7 +128,7 @@ model ProjectUsers {
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
@@unique([userId, projectId])
- @@index([projectId])
+ @@index(projectId)
}
// TODO: could potentially combine this with NotificationEmail in the future?
@@ -127,5 +139,5 @@ model SentEmail {
project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
projectId String?
- @@index([projectId])
+ @@index(projectId)
}
diff --git a/packages/ui/src/hooks/use-local-storage.ts b/packages/ui/src/hooks/use-local-storage.ts
index 6fa774a7e0..0afda7c4d8 100644
--- a/packages/ui/src/hooks/use-local-storage.ts
+++ b/packages/ui/src/hooks/use-local-storage.ts
@@ -24,10 +24,10 @@ export function useLocalStorage<T>(
}, [key]);
const setValue = (value: T) => {
- // Save state
setStoredValue(value);
- // Save to localStorage
- window.localStorage.setItem(key, JSON.stringify(value));
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(key, JSON.stringify(value));
+ }
};
return [storedValue, setValue];
diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.ts
index 3293e8497e..3a716300c1 100644
--- a/packages/utils/src/constants/index.ts
+++ b/packages/utils/src/constants/index.ts
@@ -23,3 +23,4 @@ export * from "./pricing/pricing-plan-compare-features";
export * from "./pricing/pricing-plan-main-features";
export * from "./pricing/pricing-plan-taglines";
export * from "./pricing/pricing-plans";
+export * from "./pricing/trial-limits";
diff --git a/packages/utils/src/constants/pricing/trial-limits.ts b/packages/utils/src/constants/pricing/trial-limits.ts
new file mode 100644
index 0000000000..1c259e884f
--- /dev/null
+++ b/packages/utils/src/constants/pricing/trial-limits.ts
@@ -0,0 +1,100 @@
+import type { PlanDetails } from "./pricing-plans";
+
+export const TRIAL_PROGRAM_ENROLLMENT_LIMIT = 100;
+
+export const TRIAL_LIMITS = {
+ links: 100,
+ clicks: 5_000,
+ payouts: 500_00,
+ domains: 5,
+ tags: 5,
+ folders: 5,
+ groups: 5,
+ networkInvites: 0,
+ users: 5,
+ ai: 100,
+ api: 120,
+ analyticsApi: 2,
+} as const;
+
+export type TrialLimitResource =
+ | keyof typeof TRIAL_LIMITS
+ | "partnerEnrollments"
+ | "freeDotLinkDomain";
+
+const TRIAL_LIMIT_FEATURE_PHRASES: Record<TrialLimitResource, string> = {
+ links: "create more links",
+ clicks: "track more events",
+ payouts: "send more payouts",
+ domains: "add more domains",
+ tags: "create more tags",
+ folders: "create more folders",
+ groups: "create more groups",
+ networkInvites: "invite partners from the network",
+ users: "invite more teammates",
+ partnerEnrollments: "add more partners",
+ freeDotLinkDomain: "claim a free .link domain",
+ // unused fields
+ ai: "",
+ api: "",
+ analyticsApi: "",
+};
+
+export function getTrialLimitFeaturePhrase(kind: TrialLimitResource): string {
+ return TRIAL_LIMIT_FEATURE_PHRASES[kind];
+}
+
+export function getTrialLimitResourceForOverageBanner({
+ exceededEvents,
+ exceededLinks,
+ exceededPayouts,
+}: {
+ exceededEvents: boolean;
+ exceededLinks: boolean;
+ exceededPayouts: boolean;
+}): TrialLimitResource | null {
+ if (exceededEvents) return "clicks";
+ if (exceededLinks) return "links";
+ if (exceededPayouts) return "payouts";
+ return null;
+}
+
+export const DUB_TRIAL_PERIOD_DAYS = 14;
+
+export function isWorkspaceBillingTrialActive(
+ trialEndsAt: Date | string | null | undefined,
+): boolean {
+ if (trialEndsAt == null) return false;
+ const d = trialEndsAt instanceof Date ? trialEndsAt : new Date(trialEndsAt);
+ return !Number.isNaN(d.getTime()) && d.getTime() > Date.now();
+}
+
+type WorkspaceLimitFields = PlanDetails["limits"];
+
+export function getWorkspaceLimitsForStripeSubscriptionStatus({
+ planLimits,
+ subscriptionStatus,
+}: {
+ planLimits: WorkspaceLimitFields;
+ subscriptionStatus: string;
+}): WorkspaceLimitFields {
+ if (subscriptionStatus !== "trialing") {
+ return planLimits;
+ }
+
+ return {
+ ...planLimits,
+ links: TRIAL_LIMITS.links,
+ clicks: TRIAL_LIMITS.clicks,
+ payouts: TRIAL_LIMITS.payouts,
+ users: TRIAL_LIMITS.users,
+ domains: TRIAL_LIMITS.domains,
+ tags: TRIAL_LIMITS.tags,
+ folders: TRIAL_LIMITS.folders,
+ groups: TRIAL_LIMITS.groups,
+ networkInvites: TRIAL_LIMITS.networkInvites,
+ ai: TRIAL_LIMITS.ai,
+ api: TRIAL_LIMITS.api,
+ analyticsApi: TRIAL_LIMITS.analyticsApi,
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1ef1784df6..6493a7ab6f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -300,8 +300,8 @@ importers:
specifier: 4.24.11
next-plausible:
- specifier: ^3.12.0
+ specifier: ^4.0.0
next-safe-action:
specifier: ^8.0.11
@@ -10385,12 +10385,12 @@ packages:
nodemailer:
optional: true
- resolution: {integrity: sha512-SSkEqKQ6PgR8fx3sYfIAT69k2xuCUXO5ngkSS19CjxY97lAoZxsfZpYednxB4zo0mHYv87JzhPynrdBPlCBVHg==}
+ resolution: {integrity: sha512-tC48VscREZ4fEvas9T4oj5qJwnpPlms0Wih1Unbgi/ozG08yN1w0IAPGp+/cHB8n6qzEAL5J0MlAS0FOr132jA==}
peerDependencies:
- next: ^11.1.0 || ^12.0.0 || ^13.0.0 || ^14.0.0
- react: ^16.8.0 || ^17.0.0 || ^18.0.0
- react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0
+ next: '^11.1.0 || ^12.0.0 || ^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 '
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
resolution: {integrity: sha512-gqJLmnQLAoFCq1kRBopN46New+vx1n9J9Y/qDQLXpv/VqU40AWxDakvshwwnWAt8R0kLvlakNYNLX5PqlXWSMg==}
@@ -25309,7 +25309,7 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.3
dependencies:
react: 19.1.3