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.

revert referral coupon, add relation

Steven Tey8e7cda7babdb
diff --git a/apps/web/app/api/dub/webhook/lead-created.ts b/apps/web/app/api/dub/webhook/lead-created.ts
index caaf8ba698..930942cb2b 100644
--- a/apps/web/app/api/dub/webhook/lead-created.ts
+++ b/apps/web/app/api/dub/webhook/lead-created.ts
@@ -1,6 +1,5 @@
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";
@@ -34,8 +33,12 @@ export async function leadCreated(data: any) {
}),
]);
- if (!user || !workspace) {
- return "User or workspace not found";
+ if (!user) {
+ return "referredUser not found";
+ }
+
+ if (!workspace) {
+ return `Referral link workspace not found for ${referralLink.shortLink}`;
}
await Promise.all([
@@ -44,7 +47,7 @@ export async function leadCreated(data: any) {
id: user.id,
},
data: {
- referredBy: getPrettyUrl(referralLink.shortLink),
+ referredByWorkspaceId: workspace.id,
},
}),
prisma.project.update({
diff --git a/apps/web/app/api/dub/webhook/sale-created.ts b/apps/web/app/api/dub/webhook/sale-created.ts
index 2c2d082d58..45e49c5334 100644
--- a/apps/web/app/api/dub/webhook/sale-created.ts
+++ b/apps/web/app/api/dub/webhook/sale-created.ts
@@ -1,6 +1,6 @@
import { prisma } from "@/lib/prisma";
import { sendEmail } from "emails";
-import NewReferralSignup from "emails/new-referral-signup";
+import NewReferralSale from "emails/new-referral-sale";
export async function saleCreated(data: any) {
const referralLink = data.link;
@@ -37,10 +37,11 @@ export async function saleCreated(data: any) {
owner.email &&
sendEmail({
email: owner.email,
- subject: `Congrats! You just made a $${Math.round(data.sale.amount / 100).toLocaleString()} sale via your referral link!`,
- react: NewReferralSignup({
+ subject: `Congrats! You just made a $${(data.sale.amount / 100).toFixed(2)} sale via your Dub referral link!`,
+ react: NewReferralSale({
email: owner.email,
workspace,
+ saleAmount: data.sale.amount,
}),
}),
),
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 555b450212..56fcd1f70a 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
@@ -1,7 +1,5 @@
-import { Session, withWorkspace } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
+import { withWorkspace } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
-import { redis } from "@/lib/upstash";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
@@ -56,14 +54,13 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
// if the user does not have a subscription, create a new checkout session
} else {
- const referralCoupon = await getReferralCoupon(session);
-
const stripeSession = await stripe.checkout.sessions.create({
customer_email: session.user.email,
billing_address_collection: "required",
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 }],
+ allow_promotion_codes: true,
automatic_tax: {
enabled: true,
},
@@ -75,57 +72,8 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
metadata: {
dubCustomerId: session.user.id,
},
- ...(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/emails/new-referral-sale.tsx b/apps/web/emails/new-referral-sale.tsx
new file mode 100644
index 0000000000..e9ca49c603
--- /dev/null
+++ b/apps/web/emails/new-referral-sale.tsx
@@ -0,0 +1,85 @@
+import { DUB_WORDMARK, getPrettyUrl } 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 NewReferralSale({
+ email = "[email protected]",
+ workspace = {
+ name: "Acme, Inc",
+ slug: "acme",
+ },
+ saleAmount = 4900,
+}: {
+ email: string;
+ workspace: {
+ name: string;
+ slug: string;
+ };
+ saleAmount: number;
+}) {
+ const referralLink = `https://refer.dub.co/${workspace.slug}`;
+ const saleAmountInDollars = Math.round(saleAmount / 100).toLocaleString();
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ You just made a ${saleAmountInDollars} sale via your referral link{" "}
+ {getPrettyUrl(referralLink)}
+ </Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img
+ src={DUB_WORDMARK}
+ height="40"
+ alt="Dub.co"
+ className="mx-auto my-0"
+ />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ You just made a ${saleAmountInDollars} referral sale!
+ </Heading>
+ <Text className="text-sm leading-6 text-black">
+ Congratulations – someone just upgraded their Dub plan using your
+ referral link:{" "}
+ <a
+ href={referralLink}
+ className="text-semibold font-medium text-black underline"
+ >
+ {getPrettyUrl(referralLink)}
+ </a>
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ As a thank you from us for spreading the word about Dub, you will
+ receive{" "}
+ <strong>10% of every successful payment from this sale</strong> –
+ for the first 12 months.
+ </Text>
+ <Section className="my-8 text-center">
+ <Link
+ className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ href={`https://app.dub.co/${workspace.slug}/settings/referrals`}
+ >
+ View your referral stats
+ </Link>
+ </Section>
+ <Footer email={email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/apps/web/lib/actions/invalidate-referral-coupon.ts b/apps/web/lib/actions/invalidate-referral-coupon.ts
deleted file mode 100644
index 8bbb98c074..0000000000
--- a/apps/web/lib/actions/invalidate-referral-coupon.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-"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/prisma/schema/oauth.prisma b/apps/web/prisma/schema/oauth.prisma
index 6ff4d1be04..a20286539f 100644
--- a/apps/web/prisma/schema/oauth.prisma
+++ b/apps/web/prisma/schema/oauth.prisma
@@ -46,4 +46,4 @@ model OAuthRefreshToken {
@@index([installationId])
@@index([accessTokenId])
-}
\ No newline at end of file
+}
diff --git a/apps/web/prisma/schema/schema.prisma b/apps/web/prisma/schema/schema.prisma
index c0f2be3d33..f5c5a804a5 100644
--- a/apps/web/prisma/schema/schema.prisma
+++ b/apps/web/prisma/schema/schema.prisma
@@ -10,23 +10,24 @@ generator client {
}
model User {
- id String @id @default(cuid())
- name String?
- email String? @unique
- emailVerified DateTime?
- image String?
- isMachine Boolean @default(false)
+ id String @id @default(cuid())
+ name String?
+ email String? @unique
+ emailVerified DateTime?
+ image String?
+ isMachine Boolean @default(false)
// password data
passwordHash String?
invalidLoginAttempts Int @default(0)
lockedAt DateTime?
- createdAt DateTime @default(now())
- subscribed Boolean @default(true) // email subscription
+ createdAt DateTime @default(now())
+ subscribed Boolean @default(true) // email subscription
source String? // where the user came from
defaultWorkspace String? // slug of the user's default workspace
- referredBy String? // ID of the workspace that referred this user
+ referredByWorkspace Project? @relation(fields: [referredByWorkspaceId], references: [id])
+ referredByWorkspaceId String? // ID of the workspace that referred this user
// relational data
accounts Account[]
@@ -41,6 +42,7 @@ model User {
@@index(source)
@@index(defaultWorkspace)
+ @@index([referredByWorkspaceId])
}
model Account {
diff --git a/apps/web/prisma/schema/workspace.prisma b/apps/web/prisma/schema/workspace.prisma
index 0ba7d24323..daf358f9bf 100644
--- a/apps/web/prisma/schema/workspace.prisma
+++ b/apps/web/prisma/schema/workspace.prisma
@@ -23,7 +23,8 @@ model Project {
aiLimit Int @default(10)
referralLinkId String? @unique
- referredSignups Int @default(0)
+ referredSignups Int @default(0)
+ referredUsers User[]
webhookEnabled Boolean @default(false)
conversionEnabled Boolean @default(false)
@@ -62,7 +63,7 @@ model ProjectInvite {
projectId String
role Role @default(member)
createdAt DateTime @default(now())
-
+
@@unique([email, projectId])
@@index([projectId])
}
diff --git a/apps/web/ui/modals/welcome-modal.tsx b/apps/web/ui/modals/welcome-modal.tsx
index 24492e7274..c3e353bf1e 100644
--- a/apps/web/ui/modals/welcome-modal.tsx
+++ b/apps/web/ui/modals/welcome-modal.tsx
@@ -1,4 +1,3 @@
-import { invalidateReferralCoupon } from "@/lib/actions/invalidate-referral-coupon";
import {
Button,
Logo,
@@ -8,7 +7,6 @@ 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";
@@ -40,8 +38,6 @@ function WelcomeModal({
const upgraded = searchParams.get("upgraded");
const plausible = usePlausible();
- const { executeAsync } = useAction(invalidateReferralCoupon);
-
const handlePlanUpgrade = async () => {
if (planId) {
const currentPlan = getPlanDetails(planId);
@@ -54,8 +50,6 @@ function WelcomeModal({
revenue: currentPlan.price[period],
});
}
- // invalidate referral coupon
- await executeAsync();
}
};
useEffect(() => {