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.

handle invalidating referral coupon after upgrading

Steven Teya660595c1828
diff --git a/apps/web/app/api/dub/webhook/lead-created.ts b/apps/web/app/api/dub/webhook/lead-created.ts
index 3b310a6958..caaf8ba698 100644
--- a/apps/web/app/api/dub/webhook/lead-created.ts
+++ b/apps/web/app/api/dub/webhook/lead-created.ts
@@ -1,5 +1,6 @@
import { prisma } from "@/lib/prisma";
import { REFERRAL_SIGNUPS_MAX } from "@/lib/referrals/constants";
+import { getPrettyUrl } from "@dub/utils";
import { sendEmail } from "emails";
import NewReferralSignup from "emails/new-referral-signup";
@@ -43,7 +44,7 @@ export async function leadCreated(data: any) {
id: user.id,
},
data: {
- referredBy: workspace.id,
+ referredBy: getPrettyUrl(referralLink.shortLink),
},
}),
prisma.project.update({
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 7f63aaf292..555b450212 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
@@ -1,5 +1,7 @@
-import { withWorkspace } from "@/lib/auth";
+import { Session, withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
+import { redis } from "@/lib/upstash";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
@@ -54,25 +56,12 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
// if the user does not have a subscription, create a new checkout session
} else {
- const successUrl = onboarding
- ? `${APP_DOMAIN}/${workspace.slug}?onboarded=true&plan=${plan}&period=${period}`
- : `${baseUrl}${baseUrl.includes("?") ? "&" : "?"}${new URLSearchParams({ upgraded: "true", plan, period })}`;
-
- // let referralCoupon: string | undefined;
- // if (session.user["referredBy"]) {
- // const coupon = await stripe.coupons.create({
- // percent_off: 10,
- // duration: "repeating",
- // duration_in_months: 12,
- // max_redemptions: 1,
- // });
- // referralCoupon = coupon.id;
- // }
+ const referralCoupon = await getReferralCoupon(session);
const stripeSession = await stripe.checkout.sessions.create({
customer_email: session.user.email,
billing_address_collection: "required",
- success_url: successUrl,
+ success_url: `${APP_DOMAIN}/${workspace.slug}?${onboarding ? "onboarded" : "upgraded"}=true&plan=${plan}&period=${period}`,
cancel_url: baseUrl,
line_items: [{ price: prices.data[0].id, quantity: 1 }],
automatic_tax: {
@@ -82,22 +71,61 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
enabled: true,
},
mode: "subscription",
- allow_promotion_codes: true,
client_reference_id: workspace.id,
metadata: {
dubCustomerId: session.user.id,
},
- // ...(referralCoupon
- // ? {
- // discounts: [
- // {
- // coupon: referralCoupon,
- // },
- // ],
- // }
- // : {}),
+ ...(referralCoupon && referralCoupon !== "expired"
+ ? {
+ discounts: [
+ {
+ coupon: referralCoupon,
+ },
+ ],
+ }
+ : { allow_promotion_codes: true }),
});
return NextResponse.json(stripeSession);
}
});
+
+/**
+ * Get a referral coupon for the user if they were referred via a refer.dub.co link.
+ * @param session The session object.
+ * @returns The coupon ID if the user has a referrer, otherwise null.
+ */
+const getReferralCoupon = async (session: Session) => {
+ let referredBy: string | null = session.user["referredBy"] || null;
+ if (!referredBy) {
+ const user = await prisma.user.findUnique({
+ where: {
+ id: session.user.id,
+ },
+ select: {
+ referredBy: true,
+ },
+ });
+ referredBy = user?.referredBy || null;
+ if (referredBy) {
+ const referralCoupon = await redis.get<string>(
+ `referralCoupon:${session.user.id}`,
+ );
+ if (referralCoupon) {
+ return referralCoupon;
+ } else {
+ const coupon = await stripe.coupons.create({
+ name: `Referral Discount (${referredBy})`,
+ percent_off: 10,
+ duration: "repeating",
+ duration_in_months: 12,
+ max_redemptions: 1,
+ });
+ const couponId = coupon.id;
+ await redis.set(`referralCoupon:${session.user.id}`, couponId);
+ return couponId;
+ }
+ }
+ }
+ return null;
+};
diff --git a/apps/web/app/app.dub.co/(onboarding)/[slug]/upgrade/page.tsx b/apps/web/app/app.dub.co/(onboarding)/[slug]/upgrade/page.tsx
index 75420ed17c..45fdc23723 100644
--- a/apps/web/app/app.dub.co/(onboarding)/[slug]/upgrade/page.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/[slug]/upgrade/page.tsx
@@ -4,7 +4,7 @@ import { PlanSelector } from "../../onboarding/(steps)/plan/plan-selector";
import { StepPage } from "../../onboarding/(steps)/step-page";
import BackButton from "./back-button";
-export default function Plan({ params }: { params: { slug: string } }) {
+export default function Plan() {
return (
<div className="relative flex flex-col items-center">
<BackButton />
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 838e059d19..05c04cfabe 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
@@ -1,6 +1,5 @@
"use client";
-import useWorkspace from "@/lib/swr/use-workspace";
import { PlanFeatures } from "@/ui/workspaces/plan-features";
import { UpgradePlanButton } from "@/ui/workspaces/upgrade-plan-button";
import { Badge } from "@dub/ui";
@@ -52,8 +51,6 @@ function PlanCard({
plans: (typeof SELF_SERVE_PAID_PLANS)[number][];
period: "monthly" | "yearly";
}) {
- const { slug } = useWorkspace();
-
const [selectedPlanIndex, setSelectedPlanIndex] = useState(0);
const selectedPlan = plans[selectedPlanIndex];
diff --git a/apps/web/lib/actions/invalidate-referral-coupon.ts b/apps/web/lib/actions/invalidate-referral-coupon.ts
new file mode 100644
index 0000000000..8bbb98c074
--- /dev/null
+++ b/apps/web/lib/actions/invalidate-referral-coupon.ts
@@ -0,0 +1,11 @@
+"use server";
+
+import { redis } from "../upstash";
+import { authUserActionClient } from "./safe-action";
+
+export const invalidateReferralCoupon = authUserActionClient.action(
+ async ({ ctx }) => {
+ const { user } = ctx;
+ await redis.set(`referralCoupon:${user.id}`, "expired");
+ },
+);
diff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.ts
index 79bbcd08a5..c589edfbe1 100644
--- a/apps/web/lib/auth/utils.ts
+++ b/apps/web/lib/auth/utils.ts
@@ -10,6 +10,7 @@ export interface Session {
name: string;
image?: string;
isMachine: boolean;
+ referredBy?: string;
};
}
diff --git a/apps/web/ui/modals/welcome-modal.tsx b/apps/web/ui/modals/welcome-modal.tsx
index 8eb42998d8..24492e7274 100644
--- a/apps/web/ui/modals/welcome-modal.tsx
+++ b/apps/web/ui/modals/welcome-modal.tsx
@@ -1,3 +1,4 @@
+import { invalidateReferralCoupon } from "@/lib/actions/invalidate-referral-coupon";
import {
Button,
Logo,
@@ -7,6 +8,7 @@ import {
} from "@dub/ui";
import { cn, getPlanDetails, PLANS, PRO_PLAN } from "@dub/utils";
import { usePlausible } from "next-plausible";
+import { useAction } from "next-safe-action/hooks";
import Image from "next/image";
import { useSearchParams } from "next/navigation";
import posthog from "posthog-js";
@@ -38,7 +40,9 @@ function WelcomeModal({
const upgraded = searchParams.get("upgraded");
const plausible = usePlausible();
- useEffect(() => {
+ const { executeAsync } = useAction(invalidateReferralCoupon);
+
+ const handlePlanUpgrade = async () => {
if (planId) {
const currentPlan = getPlanDetails(planId);
const period = searchParams.get("period");
@@ -50,12 +54,18 @@ function WelcomeModal({
revenue: currentPlan.price[period],
});
}
+ // invalidate referral coupon
+ await executeAsync();
}
+ };
+ useEffect(() => {
+ handlePlanUpgrade();
}, [searchParams, planId]);
const plan = planId
- ? PLANS.find((p) => p.name.toLowerCase() === planId.toLowerCase()) ??
- PRO_PLAN
+ ? PLANS.find(
+ (p) => p.name.toLowerCase() === planId.replace("+", " ").toLowerCase(),
+ ) ?? PRO_PLAN
: undefined;
return (