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.

Support upfront 12x limits for yearly plans

Steven Teya71d0f2fd642
diff --git a/apps/web/app/(ee)/api/cron/usage/utils.ts b/apps/web/app/(ee)/api/cron/usage/utils.ts
index e06e3488b7..335fcf0542 100644
--- a/apps/web/app/(ee)/api/cron/usage/utils.ts
+++ b/apps/web/app/(ee)/api/cron/usage/utils.ts
@@ -11,6 +11,7 @@ import {
getAdjustedBillingCycleStart,
log,
} from "@dub/utils";
+import { getMonth, getYear } from "date-fns";
const limit = 100;
@@ -62,50 +63,61 @@ export const updateUsage = async () => {
// adjustedBillingCycleStart that matches today's date
const billingReset = workspaces.filter(
({ billingCycleStart }) =>
- getAdjustedBillingCycleStart(billingCycleStart as number) ===
- new Date().getDate(),
+ getAdjustedBillingCycleStart(billingCycleStart) === new Date().getDate(),
);
// Reset usage and alert emails for the billingReset workspaces
// also send 30-day summary email
await Promise.allSettled(
billingReset.map(async (workspace) => {
- const { plan, usage, usageLimit } = workspace;
+ const { usage, usageLimit, plan, planPeriod, billingCycleEndsAt } =
+ workspace;
/*
We only reset clicks usage if it's not over usageLimit by:
- 4x for free plan (4K clicks)
- 2x for all other plans
*/
-
- const resetUsage =
+ let resetUsage =
plan === "free" ? usage <= usageLimit * 4 : usage <= usageLimit * 2;
- await prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- ...(resetUsage && {
+ // if yearly plan, we skip resetting usage if the billing cycle end date is not this year+month
+ if (
+ planPeriod === "yearly" &&
+ billingCycleEndsAt &&
+ !(
+ getYear(billingCycleEndsAt) === getYear(new Date()) &&
+ getMonth(billingCycleEndsAt) === getMonth(new Date())
+ )
+ ) {
+ resetUsage = false;
+ }
+
+ if (resetUsage) {
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
usage: 0,
- }),
- linksUsage: 0,
- payoutsUsage: 0,
- aiUsage: 0,
- sentEmails: {
- deleteMany: {
- type: {
- in: [
- "firstUsageLimitEmail",
- "secondUsageLimitEmail",
- "firstLinksLimitEmail",
- "secondLinksLimitEmail",
- ],
+ linksUsage: 0,
+ payoutsUsage: 0,
+ aiUsage: 0,
+ sentEmails: {
+ deleteMany: {
+ type: {
+ in: [
+ "firstUsageLimitEmail",
+ "secondUsageLimitEmail",
+ "firstLinksLimitEmail",
+ "secondLinksLimitEmail",
+ ],
+ },
},
},
},
- },
- });
+ });
+ }
/* Only send the 30-day summary email if:
- the workspace has at least 1 link click
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 2075bf887a..0858be9a83 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
@@ -9,14 +9,11 @@ import { stripe } from "@/lib/stripe";
import { redis } from "@/lib/upstash";
import { sendBatchEmail } from "@dub/email";
import TrialStartedEmail from "@dub/email/templates/trial/trial-started";
-import {
- getPlanAndTierFromPriceId,
- getWorkspaceLimitsForStripeSubscriptionStatus,
- log,
-} from "@dub/utils";
+import { getPlanAndTierFromPriceId, log } from "@dub/utils";
import { User } from "@prisma/client";
import Stripe from "stripe";
-import { getPlanPeriodFromStripeSubscription } from "./utils/stripe-plan-period";
+import { getPlanPeriodFromStripeSubscription } from "./utils/get-plan-period-from-stripe-subscription";
+import { getWorkspaceLimitsFromStripeSubscription } from "./utils/get-workspace-limits-from-stripe-subscription";
export async function checkoutSessionCompleted(
event: Stripe.CheckoutSessionCompletedEvent,
@@ -60,11 +57,6 @@ 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)
@@ -75,6 +67,11 @@ export async function checkoutSessionCompleted(
const planName = plan.name.toLowerCase();
const planPeriod = getPlanPeriodFromStripeSubscription(subscription);
+ const limits = getWorkspaceLimitsFromStripeSubscription({
+ planLimits: plan.limits,
+ subscription,
+ });
+
// when the workspace subscribes to a plan, set their stripe customer ID
// in the database for easy identification in future webhook events
// also update the billingCycleStart to today's date
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/stripe-plan-period.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/get-plan-period-from-stripe-subscription.ts
similarity index 100%
rename from apps/web/app/(ee)/api/stripe/webhook/utils/stripe-plan-period.ts
rename to apps/web/app/(ee)/api/stripe/webhook/utils/get-plan-period-from-stripe-subscription.ts
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts
new file mode 100644
index 0000000000..96ec8b3a9c
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/get-workspace-limits-from-stripe-subscription.ts
@@ -0,0 +1,45 @@
+import { PlanDetails, TRIAL_LIMITS } from "@dub/utils";
+import type Stripe from "stripe";
+import { getPlanPeriodFromStripeSubscription } from "./get-plan-period-from-stripe-subscription";
+
+export function getWorkspaceLimitsFromStripeSubscription({
+ planLimits,
+ subscription,
+}: {
+ planLimits: PlanDetails["limits"];
+ subscription: Stripe.Subscription;
+}): PlanDetails["limits"] {
+ if (subscription.status !== "trialing") {
+ const subscriptionPeriod =
+ getPlanPeriodFromStripeSubscription(subscription);
+ return {
+ ...planLimits,
+ ...(subscriptionPeriod === "yearly"
+ ? {
+ clicks: planLimits.clicks * 12,
+ links: planLimits.links * 12,
+ payouts: planLimits.payouts * 12,
+ ai: planLimits.ai * 12,
+ }
+ : {}),
+ };
+ }
+
+ 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,
+ partnerTags: TRIAL_LIMITS.partnerTags,
+ folders: TRIAL_LIMITS.folders,
+ groups: TRIAL_LIMITS.groups,
+ networkInvites: TRIAL_LIMITS.networkInvites,
+ partners: TRIAL_LIMITS.partners,
+ ai: TRIAL_LIMITS.ai,
+ api: TRIAL_LIMITS.api,
+ analyticsApi: TRIAL_LIMITS.analyticsApi,
+ };
+}
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 7ef72a8b20..08c4162864 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
@@ -21,13 +21,11 @@ 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 {
- getPlanAndTierFromPriceId,
- getWorkspaceLimitsForStripeSubscriptionStatus,
-} from "@dub/utils";
+import { getPlanAndTierFromPriceId } from "@dub/utils";
import { NEW_BUSINESS_PRICE_IDS } from "@dub/utils/src";
import type Stripe from "stripe";
-import { getPlanPeriodFromStripeSubscription } from "./stripe-plan-period";
+import { getPlanPeriodFromStripeSubscription } from "./get-plan-period-from-stripe-subscription";
+import { getWorkspaceLimitsFromStripeSubscription } from "./get-workspace-limits-from-stripe-subscription";
export async function updateWorkspacePlan({
workspace,
@@ -65,17 +63,17 @@ export async function updateWorkspacePlan({
const { canMessagePartners, canCreateWebhooks, canAddFolder } =
getPlanCapabilities(newPlanName);
- 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);
+ const limits = getWorkspaceLimitsFromStripeSubscription({
+ planLimits: newPlan.limits,
+ subscription,
+ });
+
const datetimeFieldsUpdated =
workspace.billingCycleEndsAt?.getTime() !==
cancellationFields.billingCycleEndsAt?.getTime() ||
diff --git a/apps/web/playwright/workspaces/billing-mocks.ts b/apps/web/playwright/workspaces/billing-mocks.ts
index 120a1453b6..b6cd07ac0f 100644
--- a/apps/web/playwright/workspaces/billing-mocks.ts
+++ b/apps/web/playwright/workspaces/billing-mocks.ts
@@ -1,27 +1,10 @@
import "dotenv-flow/config";
import { prisma } from "@/lib/prisma";
-import {
- DUB_TRIAL_PERIOD_DAYS,
- getWorkspaceLimitsForStripeSubscriptionStatus,
- PLANS,
-} from "@dub/utils";
+import { DUB_TRIAL_PERIOD_DAYS, TRIAL_LIMITS } from "@dub/utils";
import type { Page, Request } from "@playwright/test";
import type { Prisma } from "@prisma/client";
-function getTrialingLimitsForPlan(planId: string) {
- const planDetails = PLANS.find(
- (p) => p.name.toLowerCase() === planId.toLowerCase(),
- );
- if (!planDetails) {
- throw new Error(`applyMockTrialToWorkspace: unknown plan "${planId}"`);
- }
- return getWorkspaceLimitsForStripeSubscriptionStatus({
- planLimits: planDetails.limits,
- subscriptionStatus: "trialing",
- });
-}
-
const MOCK_CHECKOUT_SESSION_ID = "cs_test_e2e_mock_session";
/** Synthetic path used in the browser before Hosted Checkout is mocked (see redirectToCheckout stub). */
@@ -148,7 +131,7 @@ export async function applyMockTrialToWorkspace(
) {
const plan = (options?.plan ?? "business").toLowerCase();
const period = options?.period ?? "monthly";
- const limits = getTrialingLimitsForPlan(plan);
+ const limits = TRIAL_LIMITS;
const trialEndsAt = new Date();
trialEndsAt.setDate(trialEndsAt.getDate() + DUB_TRIAL_PERIOD_DAYS);
diff --git a/apps/web/scripts/migrations/update-yearly-workspace-usage.ts b/apps/web/scripts/migrations/update-yearly-workspace-usage.ts
new file mode 100644
index 0000000000..e9d7462780
--- /dev/null
+++ b/apps/web/scripts/migrations/update-yearly-workspace-usage.ts
@@ -0,0 +1,99 @@
+import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { prisma } from "@/lib/prisma";
+import { subYears } from "date-fns";
+import "dotenv-flow/config";
+
+const BATCH_SIZE = 50;
+
+// TODO: will need to also double check that billingCycleEndsAt is actually reliable
+async function main() {
+ while (true) {
+ const workspaces = await prisma.project.findMany({
+ where: {
+ planPeriod: "yearly",
+ // Unmigrated yearly workspaces still have monthly AI limits
+ aiLimit: 1000,
+ billingCycleEndsAt: {
+ not: null,
+ },
+ },
+ take: BATCH_SIZE,
+ });
+
+ if (workspaces.length === 0) {
+ console.log("No yearly workspaces left to update");
+ break;
+ }
+
+ await Promise.allSettled(
+ workspaces.map(async (workspace) => {
+ const billingStart = subYears(workspace.billingCycleEndsAt!, 1);
+
+ const [clicksResponse, linksUsage, payoutsUsage] = await Promise.all([
+ getAnalytics({
+ workspaceId: workspace.id,
+ event: "clicks",
+ start: billingStart,
+ end: new Date(),
+ dataAvailableFrom: workspace.createdAt,
+ }),
+ prisma.link.count({
+ where: {
+ projectId: workspace.id,
+ createdAt: {
+ gte: billingStart,
+ },
+ },
+ }),
+ prisma.invoice.aggregate({
+ where: {
+ workspaceId: workspace.id,
+ type: "partnerPayout",
+ status: "completed",
+ paidAt: {
+ gte: billingStart,
+ },
+ },
+ _sum: {
+ amount: true,
+ },
+ }),
+ ]);
+
+ const usage =
+ typeof clicksResponse === "object" && clicksResponse !== null
+ ? (clicksResponse as { clicks?: number }).clicks ?? 0
+ : typeof clicksResponse === "number"
+ ? clicksResponse
+ : 0;
+
+ const newUsageLimit = workspace.usageLimit * 12;
+ const newLinksLimit = workspace.linksLimit * 12;
+ const newPayoutsLimit = workspace.payoutsLimit * 12;
+ const newAiLimit = workspace.aiLimit * 12;
+ const newPayoutsUsage = payoutsUsage._sum.amount ?? 0;
+
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ usage,
+ linksUsage,
+ payoutsUsage: newPayoutsUsage,
+ usageLimit: newUsageLimit,
+ linksLimit: newLinksLimit,
+ payoutsLimit: newPayoutsLimit,
+ aiLimit: newAiLimit,
+ },
+ });
+
+ console.log(
+ `Updated ${workspace.slug}: clicks ${usage}/${newUsageLimit}, links ${linksUsage}/${newLinksLimit}, payouts ${newPayoutsUsage}/${newPayoutsLimit}, ai ${workspace.aiUsage}/${newAiLimit}`,
+ );
+ }),
+ );
+ }
+}
+
+main();
diff --git a/packages/utils/src/constants/pricing/trial-limits.ts b/packages/utils/src/constants/pricing/trial-limits.ts
index 813fe1e394..5b054f5531 100644
--- a/packages/utils/src/constants/pricing/trial-limits.ts
+++ b/packages/utils/src/constants/pricing/trial-limits.ts
@@ -1,5 +1,3 @@
-import type { PlanDetails } from "./pricing-plans";
-
export const TRIAL_LIMITS = {
links: 100,
clicks: 5_000,
@@ -70,35 +68,3 @@ export function isWorkspaceBillingTrialActive(
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,
- partnerTags: TRIAL_LIMITS.partnerTags,
- folders: TRIAL_LIMITS.folders,
- groups: TRIAL_LIMITS.groups,
- networkInvites: TRIAL_LIMITS.networkInvites,
- partners: TRIAL_LIMITS.partners,
- ai: TRIAL_LIMITS.ai,
- api: TRIAL_LIMITS.api,
- analyticsApi: TRIAL_LIMITS.analyticsApi,
- };
-}
diff --git a/packages/utils/src/functions/datetime/billing-utils.ts b/packages/utils/src/functions/datetime/billing-utils.ts
index c0f0ec4a03..7c54432af9 100644
--- a/packages/utils/src/functions/datetime/billing-utils.ts
+++ b/packages/utils/src/functions/datetime/billing-utils.ts
@@ -22,6 +22,7 @@ export const getBillingStartDate = (billingCycleStart: number) => {
const currentYear = today.getFullYear();
const adjustedBillingCycleStart =
getAdjustedBillingCycleStart(billingCycleStart);
+
if (currentDay <= adjustedBillingCycleStart) {
// if the current day is less than the billing cycle start, we need to go back a month
const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December