The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Tremendous (#3952)
Kiran K9e76dc71b96e
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex ac8c3dc3b3..353d65404a 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -169,6 +169,9 @@ PAYPAL_CLIENT_ID=PAYPAL_CLIENT_SECRET=PAYPAL_WEBHOOK_ID=+# Tremendous+TREMENDOUS_API_KEY=+# Program lander generationFIRECRAWL_API_KEY=diff --git a/apps/web/app/(ee)/api/cron/disposable-emails/route.ts b/apps/web/app/(ee)/api/cron/disposable-emails/route.tsindex d97ab47885..c18312cb7c 100644--- a/apps/web/app/(ee)/api/cron/disposable-emails/route.ts+++ b/apps/web/app/(ee)/api/cron/disposable-emails/route.ts@@ -1,44 +1,68 @@-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { withCron } from "@/lib/cron/with-cron";import { redis } from "@/lib/upstash";-import { log } from "@dub/utils";-import { NextResponse } from "next/server";+import { logAndRespond } from "../utils";export const dynamic = "force-dynamic";-// Cron to update the disposable email domains list in Redis+// POST /api/cron/disposable-emails+// Sync disposable and Tremendous prohibited email domain blocklists into Redis.// Runs every Monday at noon UTC (0 12 * * 1)-export async function POST(req: Request) {- try {- const rawBody = await req.text();+export const POST = withCron(async () => {+ const [disposableRes, tremendousRes] = await Promise.allSettled([+ fetch(+ "https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/master/disposable_email_blocklist.conf",+ ),+ fetch("https://api.tremendous.com/prohibited_email_domains.txt"),+ ]);- await verifyQstashSignature({- req,- rawBody,- });+ if (disposableRes.status === "rejected") {+ console.warn(+ `Failed to fetch disposable email domains list: ${disposableRes.status} ${disposableRes.reason}`,+ );+ }- const disposableEmails = await fetch(- "https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/master/disposable_email_blocklist.conf",+ if (tremendousRes.status === "rejected") {+ console.warn(+ `Failed to fetch Tremendous prohibited email domains list: ${tremendousRes.status} ${tremendousRes.reason}`,);+ }- const domains = (await disposableEmails.text()).split("\n").filter(Boolean);+ const disposableDomains =+ disposableRes.status === "fulfilled"+ ? (await disposableRes.value.text()).split("\n").filter(Boolean)+ : [];- if (domains.length < 100) {- throw new Error("Disposable email domains list is too short");- }+ const tremendousDomains =+ tremendousRes.status === "fulfilled"+ ? (await tremendousRes.value.text())+ .split("\n")+ .map((d) => d.trim().toLowerCase())+ .filter(Boolean)+ : [];- // Use a temporary set to avoid emptying the old set+ if (disposableDomains.length > 0) {+ // Use temporary sets to avoid emptying the old setsawait redis.del("disposableEmailDomainsTmp");- await redis.sadd("disposableEmailDomainsTmp", ...(domains as [string]));+ await redis.sadd(+ "disposableEmailDomainsTmp",+ ...(disposableDomains as [string]),+ );await redis.rename("disposableEmailDomainsTmp", "disposableEmailDomains");+ }- return NextResponse.json({ status: "OK" });- } catch (error) {- await log({- message: `Error updating disposable email domains list: ${error.message}`,- type: "cron",- });-- return handleAndReturnErrorResponse(error);+ if (tremendousDomains.length > 0) {+ await redis.del("tremendousProhibitedEmailDomainsTmp");+ await redis.sadd(+ "tremendousProhibitedEmailDomainsTmp",+ ...(tremendousDomains as [string]),+ );+ await redis.rename(+ "tremendousProhibitedEmailDomainsTmp",+ "tremendousProhibitedEmailDomains",+ );}-}++ return logAndRespond(+ `Synced ${disposableDomains.length} disposable and ${tremendousDomains.length} Tremendous prohibited email domains.`,+ );+});diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.tsnew file mode 100644index 0000000000..6b844c1933--- /dev/null+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts@@ -0,0 +1,89 @@+import { qstash } from "@/lib/cron";+import { TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS } from "@/lib/tremendous/constants";+import { createTremendousCampaign } from "@/lib/tremendous/create-tremendous-campaign";+import { prisma } from "@dub/prisma";+import {+ Invoice,+ PartnerPayoutMethod,+ PayoutMode,+ PayoutStatus,+} from "@dub/prisma/client";+import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";++const queue = qstash.queue({+ queueName: "send-tremendous-payout",+});++export async function queueTremendousPayouts(+ invoice: Pick<Invoice, "id" | "paymentMethod" | "payoutMode" | "programId">,+) {+ if (invoice.payoutMode === "external" || !invoice.programId) {+ return;+ }++ const program = await prisma.program.findUniqueOrThrow({+ where: {+ id: invoice.programId,+ },+ select: {+ id: true,+ name: true,+ logo: true,+ tremendousCampaignId: true,+ },+ });++ if (!program.tremendousCampaignId) {+ await createTremendousCampaign(program);+ }++ const partnersInCurrentInvoice = await prisma.payout.groupBy({+ by: ["partnerId"],+ where: {+ invoiceId: invoice.id,+ status: PayoutStatus.processing,+ mode: PayoutMode.internal,+ method: PartnerPayoutMethod.tremendous,+ amount: {+ lte: TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,+ },+ partner: {+ tremendousEmail: {+ not: null,+ },+ payoutsEnabledAt: {+ not: null,+ },+ },+ },+ });++ if (partnersInCurrentInvoice.length === 0) {+ console.log("No partners for sending via Tremendous, skipping...");+ return;+ }++ const chunkedPartners = chunk(partnersInCurrentInvoice, 100);++ for (let i = 0; i < chunkedPartners.length; i++) {+ const partnersInChunk = chunkedPartners[i];++ await Promise.all(+ partnersInChunk.map(({ partnerId }) =>+ queue.enqueueJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/send-tremendous-payout`,+ deduplicationId: `${invoice.id}-${partnerId}`,+ method: "POST",+ body: {+ partnerId,+ invoiceId: invoice.id,+ },+ }),+ ),+ );++ console.log(+ `Enqueued Tremendous payout for ${partnersInChunk.length} partners in chunk ${i + 1} of ${chunkedPartners.length}`,+ );+ }+}diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.tsindex 3c0cda2ae3..9018e97c23 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts@@ -11,6 +11,7 @@ import * as z from "zod/v4";import { logAndRespond } from "../../utils";import { queueExternalPayouts } from "./queue-external-payouts";import { queueStripePayouts } from "./queue-stripe-payouts";+import { queueTremendousPayouts } from "./queue-tremendous-payouts";import { sendPaypalPayouts } from "./send-paypal-payouts";import { scheduleDelayedStablecoinPayouts } from "./utils";@@ -122,6 +123,8 @@ export async function POST(req: Request) {sendPaypalPayouts(invoice),// Queue external payoutsqueueExternalPayouts(invoice),+ // Queue Tremendous payouts+ queueTremendousPayouts(invoice),]);return logAndRespond(diff --git a/apps/web/app/(ee)/api/cron/payouts/send-tremendous-payout/route.ts b/apps/web/app/(ee)/api/cron/payouts/send-tremendous-payout/route.tsnew file mode 100644index 0000000000..56e893de8b--- /dev/null+++ b/apps/web/app/(ee)/api/cron/payouts/send-tremendous-payout/route.ts@@ -0,0 +1,25 @@+import { withCron } from "@/lib/cron/with-cron";+import { sendTremendousPayouts } from "@/lib/tremendous/send-tremendous-payouts";+import * as z from "zod/v4";+import { logAndRespond } from "../../utils";++export const dynamic = "force-dynamic";++const inputSchema = z.object({+ partnerId: z.string(),+ invoiceId: z.string().optional(),+});++// POST /api/cron/payouts/send-tremendous-payout+export const POST = withCron(async ({ rawBody }) => {+ const { partnerId, invoiceId } = inputSchema.parse(JSON.parse(rawBody));++ await sendTremendousPayouts({+ partnerId,+ invoiceId,+ });++ return logAndRespond(+ `Processed send-tremendous-payout job for partner ${partnerId}.`,+ );+});diff --git a/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.ts b/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.tsnew file mode 100644index 0000000000..1313673e00--- /dev/null+++ b/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.ts@@ -0,0 +1,159 @@+import { DubApiError } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { generateOTP } from "@/lib/auth";+import { EMAIL_OTP_EXPIRY_IN } from "@/lib/auth/constants";+import { extractEmailDomain } from "@/lib/email/extract-email-domain";+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";+import {+ TREMENDOUS_ENABLED_PROGRAM_IDS,+ TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS,+} from "@/lib/tremendous/constants";+import { ratelimit, redis } from "@/lib/upstash";+import { emailSchema } from "@/lib/zod/schemas/auth";+import { sendEmail } from "@dub/email";+import PartnerTremendousVerifyEmail from "@dub/email/templates/partner-tremendous-verify-email";+import { prisma } from "@dub/prisma";+import { TREMENDOUS_SUPPORTED_COUNTRIES } from "@dub/utils";+import { NextResponse } from "next/server";+import * as z from "zod/v4";++const sendOtpSchema = z.object({+ email: emailSchema,+});++// POST /api/embed/referrals/tremendous/send-otp+export const POST = withReferralsEmbedToken(+ async ({ req, programEnrollment }) => {+ if (!TREMENDOUS_ENABLED_PROGRAM_IDS.includes(programEnrollment.programId)) {+ throw new DubApiError({+ code: "forbidden",+ message: "Gift card payouts are not available for this program.",+ });+ }++ const { email } = sendOtpSchema.parse(await parseRequestBody(req));+ const { partnerId } = programEnrollment;++ const { success } = await ratelimit(10, "24 h").limit(+ `tremendous-send-otp:${partnerId}`,+ );++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests. Please try again later.",+ });+ }++ const emailDomain = extractEmailDomain(email)!;++ // Check if the email domain is allowed by Tremendous+ const isProhibited = TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS.some((tld) =>+ emailDomain.endsWith(tld),+ );++ if (isProhibited) {+ throw new DubApiError({+ code: "forbidden",+ message:+ "This email address isn't eligible for gift card payouts. Please use a different email address.",+ });+ }++ const [isDisposableEmailDomain, isTremendousProhibited] = await Promise.all(+ [+ redis.sismember("disposableEmailDomains", emailDomain),+ redis.sismember("tremendousProhibitedEmailDomains", emailDomain),+ ],+ );++ if (isDisposableEmailDomain || isTremendousProhibited) {+ throw new DubApiError({+ code: "forbidden",+ message:+ "This email address isn't eligible for gift card payouts. Please use a different email address.",+ });+ }++ const [partner, duplicatePartner] = await prisma.$transaction([+ prisma.partner.findUniqueOrThrow({+ where: {+ id: partnerId,+ },+ select: {+ id: true,+ country: true,+ defaultPayoutMethod: true,+ },+ }),++ prisma.partner.findFirst({+ where: {+ tremendousEmail: email,+ id: {+ not: partnerId,+ },+ },+ select: {+ id: true,+ },+ }),+ ]);++ if (+ partner.country &&+ !TREMENDOUS_SUPPORTED_COUNTRIES.includes(partner.country)+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Gift card payouts are not available in your country.",+ });+ }++ if (partner.defaultPayoutMethod) {+ throw new DubApiError({+ code: "bad_request",+ message: "You already have a payout method connected.",+ });+ }++ if (duplicatePartner) {+ throw new DubApiError({+ code: "conflict",+ message:+ "Unable to save partner details. Please verify the email address and try again.",+ });+ }++ const code = generateOTP();+ const identifier = `tremendous:${partnerId}:${email}`;++ await prisma.$transaction([+ prisma.emailVerificationToken.deleteMany({+ where: {+ identifier,+ },+ }),++ prisma.emailVerificationToken.create({+ data: {+ identifier,+ token: code,+ expires: new Date(Date.now() + EMAIL_OTP_EXPIRY_IN * 1000), // 5 minutes+ },+ }),+ ]);++ await sendEmail({+ subject: "OTP to verify your payout email",+ to: email,+ react: PartnerTremendousVerifyEmail({+ email,+ code,+ expiryMinutes: EMAIL_OTP_EXPIRY_IN / 60,+ }),+ });++ return NextResponse.json({ success: true });+ },+);diff --git a/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.ts b/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.tsnew file mode 100644index 0000000000..f6ef3e8b77--- /dev/null+++ b/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.ts@@ -0,0 +1,201 @@+import { DubApiError } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { extractEmailDomain } from "@/lib/email/extract-email-domain";+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";+import {+ TREMENDOUS_ENABLED_PROGRAM_IDS,+ TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS,+} from "@/lib/tremendous/constants";+import { ratelimit, redis } from "@/lib/upstash";+import { emailSchema } from "@/lib/zod/schemas/auth";+import { prisma } from "@dub/prisma";+import { TREMENDOUS_SUPPORTED_COUNTRIES } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import { NextResponse } from "next/server";+import * as z from "zod/v4";++const verifyOtpSchema = z.object({+ email: emailSchema,+ code: z.string().min(6, "OTP must be 6 characters long.").max(6),+});++// POST /api/embed/referrals/tremendous/verify-otp+export const POST = withReferralsEmbedToken(+ async ({ req, programEnrollment }) => {+ if (!TREMENDOUS_ENABLED_PROGRAM_IDS.includes(programEnrollment.programId)) {+ throw new DubApiError({+ code: "forbidden",+ message: "Gift card payouts are not available for this program.",+ });+ }++ const { email, code } = verifyOtpSchema.parse(await parseRequestBody(req));+ const { partnerId } = programEnrollment;++ const { success } = await ratelimit(10, "24 h").limit(+ `tremendous-verify-otp:${partnerId}`,+ );++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests. Please try again later.",+ });+ }++ const emailDomain = extractEmailDomain(email)!;++ // Check if the email domain is allowed by Tremendous+ const isProhibited = TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS.some((tld) =>+ emailDomain.endsWith(tld),+ );++ if (isProhibited) {+ throw new DubApiError({+ code: "forbidden",+ message:+ "This email address isn't eligible for gift card payouts. Please use a different email address.",+ });+ }++ const [isDisposableEmailDomain, isTremendousProhibited] = await Promise.all(+ [+ redis.sismember("disposableEmailDomains", emailDomain),+ redis.sismember("tremendousProhibitedEmailDomains", emailDomain),+ ],+ );++ if (isDisposableEmailDomain || isTremendousProhibited) {+ throw new DubApiError({+ code: "forbidden",+ message:+ "This email address isn't eligible for gift card payouts. Please use a different email address.",+ });+ }++ const [partner, duplicatePartner] = await prisma.$transaction([+ prisma.partner.findUniqueOrThrow({+ where: {+ id: partnerId,+ },+ select: {+ id: true,+ country: true,+ defaultPayoutMethod: true,+ },+ }),++ prisma.partner.findFirst({+ where: {+ tremendousEmail: email,+ id: {+ not: partnerId,+ },+ },+ select: {+ id: true,+ },+ }),+ ]);++ if (+ partner.country &&+ !TREMENDOUS_SUPPORTED_COUNTRIES.includes(partner.country)+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Gift card payouts are not available in your country.",+ });+ }++ if (partner.defaultPayoutMethod) {+ throw new DubApiError({+ code: "bad_request",+ message: "You already have a payout method connected.",+ });+ }++ if (duplicatePartner) {+ throw new DubApiError({+ code: "conflict",+ message:+ "Unable to save partner details. Please verify the email address and try again.",+ });+ }++ const identifier = `tremendous:${partnerId}:${email}`;++ const verificationToken = await prisma.emailVerificationToken.findUnique({+ where: {+ identifier_token: {+ identifier,+ token: code,+ },+ },+ });++ if (!verificationToken) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "The verification code is incorrect or has expired. Please request a new code and try again.",+ });+ }++ if (verificationToken.expires < new Date()) {+ waitUntil(+ prisma.emailVerificationToken.delete({+ where: {+ identifier_token: {+ identifier,+ token: code,+ },+ },+ }),+ );++ throw new DubApiError({+ code: "bad_request",+ message:+ "The verification code is incorrect or has expired. Please request a new code and try again.",+ });+ }++ try {+ await prisma.$transaction([+ prisma.emailVerificationToken.delete({+ where: {+ identifier_token: {+ identifier,+ token: code,+ },+ },+ }),++ prisma.partner.update({+ where: {+ id: partner.id,+ defaultPayoutMethod: null,+ payoutsEnabledAt: null,+ },+ data: {+ tremendousEmail: email,+ defaultPayoutMethod: "tremendous",+ payoutsEnabledAt: new Date(),+ },+ }),+ ]);+ } catch (error) {+ if (error.code === "P2025") {+ throw new DubApiError({+ code: "bad_request",+ message: "You already have a payout method connected.",+ });+ }++ throw error;+ }++ return NextResponse.json({ success: true });+ },+);diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.tsindex 8000f97449..0bf71117c1 100644--- a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.ts+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.ts@@ -24,6 +24,7 @@ export async function recipientAccountClosed(event: Stripe.ThinEvent) {paypalEmail: true,payoutsEnabledAt: true,defaultPayoutMethod: true,+ tremendousEmail: true,},});diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.tsindex 95e82c9164..40bec3618d 100644--- a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.ts+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.ts@@ -27,6 +27,7 @@ export async function recipientConfigurationUpdated(event: Stripe.ThinEvent) {payoutsEnabledAt: true,defaultPayoutMethod: true,cryptoWalletAddress: true,+ tremendousEmail: true,},});diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.tsindex a0a8199619..21f5cac1b4 100644--- a/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts@@ -23,6 +23,7 @@ export async function accountApplicationDeauthorized(paypalEmail: true,payoutsEnabledAt: true,defaultPayoutMethod: true,+ tremendousEmail: true,},});diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.tsindex 9027878437..47d1d3a75f 100644--- a/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts@@ -39,6 +39,7 @@ export async function accountUpdated(event: Stripe.AccountUpdatedEvent) {payoutsEnabledAt: true,defaultPayoutMethod: true,payoutMethodHash: true,+ tremendousEmail: true,},});diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsxindex 6cb5507afd..86556dd22d 100644--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx@@ -3,7 +3,13 @@ import { Button, InfoTooltip } from "@dub/ui";import { currencyFormatter } from "@dub/utils";import { useReferralsEmbedData } from "./page-client";-export function ReferralsEmbedEarningsSummary() {+export function ReferralsEmbedEarningsSummary({+ showSettingsTab,+ onSelectTab,+}: {+ showSettingsTab: boolean;+ onSelectTab: (tab: string) => void;+}) {const { program, partner, earnings } = useReferralsEmbedData();// for custom SSO login programs, we just redirect to the login page@@ -12,6 +18,15 @@ export function ReferralsEmbedEarningsSummary() {({ slug }) => slug === program.slug,);+ const settingsButton = (+ <Button+ text="Settings"+ variant="secondary"+ className="h-7 w-fit p-2 text-sm"+ onClick={showSettingsTab ? () => onSelectTab("Settings") : undefined}+ />+ );+return (<div className="border-border-subtle bg-bg-default flex flex-col justify-between gap-4 rounded-lg border p-4"><div className="flex items-center justify-between">@@ -19,20 +34,20 @@ export function ReferralsEmbedEarningsSummary() {<p className="text-content-subtle text-sm">Earnings</p><InfoTooltip content="Summary of your commission earnings from your referrals." /></div>- <a- href={`https://partners.dub.co/${program.slug}/${- isCustomSSOLoginProgram- ? "login"- : `register${partner.email ? `?email=${partner.email}` : ""}`- }`}- target="_blank"- >- <Button- text="Settings"- variant="secondary"- className="h-7 p-2 text-sm"- />- </a>+ {showSettingsTab ? (+ settingsButton+ ) : (+ <a+ href={`https://partners.dub.co/${program.slug}/${+ isCustomSSOLoginProgram+ ? "login"+ : `register${partner.email ? `?email=${partner.email}` : ""}`+ }`}+ target="_blank"+ >+ {settingsButton}+ </a>+ )}</div><div className="grid gap-1">{[diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.tsindex 7208a1b713..b52efbcaab 100644--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts@@ -27,6 +27,9 @@ export const getReferralsEmbedData = async (token: string) => {id: true,name: true,email: true,+ country: true,+ tremendousEmail: true,+ defaultPayoutMethod: true,platforms: {select: {type: true,@@ -118,6 +121,9 @@ export const getReferralsEmbedData = async (token: string) => {id: partner.id,name: partner.name,email: partner.email,+ country: partner.country,+ tremendousEmail: partner.tremendousEmail,+ defaultPayoutMethod: partner.defaultPayoutMethod,},partnerPlatforms: partner.platforms,links: z.array(ReferralsEmbedLinkSchema).parse(links),diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsxindex 4637ebb36c..7389024f7c 100644--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx@@ -2,6 +2,7 @@import { constructPartnerLink } from "@/lib/partners/construct-partner-link";import { QueryLinkStructureHelpText } from "@/lib/partners/query-link-structure-help-text";+import { TREMENDOUS_ENABLED_PROGRAM_IDS } from "@/lib/tremendous/constants";import {DiscountProps,PartnerBountyProps,@@ -37,7 +38,12 @@ import {Wordmark,} from "@dub/ui";import { ArrowTurnRight2 } from "@dub/ui/icons";-import { cn, getApexDomain, getPrettyUrl } from "@dub/utils";+import {+ cn,+ getApexDomain,+ getPrettyUrl,+ TREMENDOUS_SUPPORTED_COUNTRIES,+} from "@dub/utils";import { ChevronDown } from "lucide-react";import { AnimatePresence } from "motion/react";import {@@ -58,6 +64,7 @@ import { ReferralsEmbedLeaderboard } from "./leaderboard";import { ReferralsEmbedLinks } from "./links";import { ReferralsEmbedQuickstart } from "./quickstart";import { ReferralsEmbedResources } from "./resources";+import { ReferralsEmbedSettings } from "./settings";import { ThemeOptions } from "./theme-options";import { ReferralsReferralsEmbedToken } from "./token";import { ReferralsEmbedLink } from "./types";@@ -77,7 +84,15 @@ type ReferralsEmbedData = {programEnrollment: Pick<ProgramEnrollmentProps, "createdAt"> & {status: ProgramEnrollmentStatus;};- partner: Pick<Partner, "id" | "name" | "email">;+ partner: Pick<+ Partner,+ | "id"+ | "name"+ | "email"+ | "country"+ | "tremendousEmail"+ | "defaultPayoutMethod"+ >;partnerPlatforms: Array<{type: PlatformType;identifier: string;@@ -183,6 +198,18 @@ export function ReferralsEmbedPageClient({programEnrollment.status,);+ const isTremendousCountrySupported = Boolean(+ !partner.country ||+ TREMENDOUS_SUPPORTED_COUNTRIES.includes(partner.country),+ );++ // Show Tremendous payout settings if the partner already uses Tremendous,+ // or hasn't selected a payout method yet and is eligible based on country.+ const showSettingsTab =+ TREMENDOUS_ENABLED_PROGRAM_IDS.includes(program.id) &&+ (partner.defaultPayoutMethod === "tremendous" ||+ (!partner.defaultPayoutMethod && isTremendousCountrySupported));+const tabs = useMemo(() => [...(showQuickstart ? ["Quickstart"] : []),@@ -194,6 +221,7 @@ export function ReferralsEmbedPageClient({: ["Leaderboard"]),"FAQ",...(hasResources ? ["Resources"] : []),+ ...(showSettingsTab ? ["Settings"] : []),],[showQuickstart,@@ -201,6 +229,7 @@ export function ReferralsEmbedPageClient({group.additionalLinks,programEmbedData,hasResources,+ showSettingsTab,],);@@ -321,7 +350,10 @@ export function ReferralsEmbedPageClient({><ReferralsEmbedActivity />{!programEmbedData?.hideEarnings && (- <ReferralsEmbedEarningsSummary />+ <ReferralsEmbedEarningsSummary+ showSettingsTab={showSettingsTab}+ onSelectTab={setSelectedTab}+ />)}</div><div className="mt-4">@@ -383,6 +415,8 @@ export function ReferralsEmbedPageClient({<ReferralsEmbedFAQ />) : selectedTab === "Resources" ? (<ReferralsEmbedResources resources={resources} />+ ) : selectedTab === "Settings" ? (+ <ReferralsEmbedSettings />) : null}</AnimatePresence></div>diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsxindex 93841efa6d..e3841abe92 100644--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx@@ -1,4 +1,5 @@import { constructPartnerLink } from "@/lib/partners/construct-partner-link";+import { TREMENDOUS_ENABLED_PROGRAM_IDS } from "@/lib/tremendous/constants";import { programEmbedSchema } from "@/lib/zod/schemas/program-embed";import {Button,@@ -12,7 +13,7 @@ import {useCopyToClipboard,useMediaQuery,} from "@dub/ui";-import { cn, DUB_LOGO } from "@dub/utils";+import { cn, DUB_LOGO, TREMENDOUS_SUPPORTED_COUNTRIES } from "@dub/utils";import { motion } from "motion/react";import { useReferralsEmbedData } from "./page-client";@@ -24,13 +25,14 @@ export function ReferralsEmbedQuickstart({setSelectedTab,}: {hasResources: boolean;- setSelectedTab: (tab: "Links" | "Resources" | "FAQ") => void;+ setSelectedTab: (tab: "Links" | "Resources" | "FAQ" | "Settings") => void;}) {- const { program, group, links, earnings } = useReferralsEmbedData();+ const { isMobile } = useMediaQuery();+ const [copied, copyToClipboard] = useCopyToClipboard();+ const { partner, program, group, links, earnings } = useReferralsEmbedData();+const programEmbedData = programEmbedSchema.parse(program.embedData);- const [copied, copyToClipboard] = useCopyToClipboard();- const { isMobile } = useMediaQuery();const payoutsDisabled = earnings.upcoming === 0 && earnings.paid === 0;const items = [@@ -133,9 +135,29 @@ export function ReferralsEmbedQuickstart({? "You will be able to withdraw your earnings once you have made at least one sale.": undefined}- onClick={() =>- window.open("https://partners.dub.co/payouts", "_blank")- }+ onClick={() => {+ const isTremendousCountrySupported = Boolean(+ !partner.country ||+ TREMENDOUS_SUPPORTED_COUNTRIES.includes(partner.country),+ );++ const usesTremendous =+ partner.defaultPayoutMethod === "tremendous";++ // Show Tremendous payout settings if the partner already uses Tremendous,+ // or hasn't selected a payout method yet and is eligible based on country.+ const showTremendousSettings =+ TREMENDOUS_ENABLED_PROGRAM_IDS.includes(program.id) &&+ (usesTremendous ||+ (!partner.defaultPayoutMethod &&+ isTremendousCountrySupported));++ if (showTremendousSettings) {+ setSelectedTab("Settings");+ } else {+ window.open("https://partners.dub.co/payouts", "_blank");+ }+ }}text="Connect payouts"/>),diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/settings.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/settings.tsxnew file mode 100644index 0000000000..04e5da5dfb--- /dev/null+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/settings.tsx@@ -0,0 +1,540 @@+"use client";++import { TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS } from "@/lib/tremendous/constants";+import { AlertCircleFill } from "@/ui/shared/icons";+import {+ AnimatedSizeContainer,+ Badge,+ Button,+ Gift,+ MoneyBill,+ Tooltip,+ useMediaQuery,+} from "@dub/ui";+import { cn, currencyFormatter } from "@dub/utils/src";+import { OTPInput } from "input-otp";+import { AnimatePresence, motion } from "motion/react";+import { useRouter } from "next/navigation";+import type { ComponentType, Dispatch, FormEvent, SetStateAction } from "react";+import { useEffect, useState } from "react";+import { useEmbedToken } from "../use-embed-token";+import { useReferralsEmbedData } from "./page-client";++type GiftCardPanel = "collapsed" | "email" | "verify";++function PayoutMethodButton({+ text,+ variant,+ className,+ disabled,+ disabledTooltip,+ onClick,+}: {+ text: string;+ variant: "primary" | "secondary";+ className?: string;+ disabled?: boolean;+ disabledTooltip?: string;+ onClick?: () => void;+}) {+ if (disabledTooltip) {+ return (+ <Tooltip+ content={disabledTooltip}+ contentClassName="text-content-default dark:prose-invert dark:prose-a:text-neutral-400 dark:hover:prose-a:text-neutral-300"+ >+ <div+ className={cn(+ "border-border-subtle bg-bg-subtle text-content-subtle flex cursor-not-allowed items-center justify-center whitespace-nowrap rounded-lg border text-sm",+ className,+ )}+ >+ {text}+ </div>+ </Tooltip>+ );+ }++ return (+ <Button+ className={className}+ text={text}+ variant={variant}+ disabled={disabled}+ onClick={onClick}+ />+ );+}++function SettingsErrorAlert({ message }: { message: string }) {+ return (+ <div+ role="alert"+ className="bg-bg-error text-content-error border-border-error mb-3 flex items-start gap-2 rounded-lg border px-3 py-2.5"+ >+ <AlertCircleFill className="mt-0.5 size-4 shrink-0" />+ <p className="text-sm font-medium leading-5">{message}</p>+ </div>+ );+}++function TremendousEmailForm({+ initialEmail,+ onSuccess,+ errorMessage,+ setErrorMessage,+}: {+ initialEmail: string;+ onSuccess: (email: string) => void;+ errorMessage: string | null;+ setErrorMessage: Dispatch<SetStateAction<string | null>>;+}) {+ const token = useEmbedToken();+ const [email, setEmail] = useState(initialEmail);+ const [isSendingOtp, setIsSendingOtp] = useState(false);++ useEffect(() => {+ setEmail(initialEmail);+ }, [initialEmail]);++ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();++ if (!email) {+ setErrorMessage("Please enter an email address.");+ return;+ }++ setIsSendingOtp(true);+ setErrorMessage(null);++ try {+ const response = await fetch("/api/embed/referrals/tremendous/send-otp", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify({ email }),+ });++ const result = await response.json();++ if (!response.ok) {+ setErrorMessage(+ result.error?.message ?? "Something went wrong. Please try again.",+ );+ return;+ }++ onSuccess(email);+ } catch {+ setErrorMessage("Something went wrong. Please try again.");+ } finally {+ setIsSendingOtp(false);+ }+ };++ return (+ <div className="bg-bg-muted border-border-subtle border-t p-3">+ {errorMessage && <SettingsErrorAlert message={errorMessage} />}+ <form+ onSubmit={handleSubmit}+ className="flex items-end gap-3"+ noValidate={false}+ >+ <div className="min-w-0 flex-1 space-y-1.5">+ <label+ htmlFor="tremendous-email"+ className="text-content-emphasis block text-sm font-medium"+ >+ </label>+ <input+ id="tremendous-email"+ type="email"+ value={email}+ onChange={(e) => {+ setEmail(e.target.value);+ setErrorMessage(null);+ }}+ placeholder="[email protected]"+ required+ className="border-border-subtle text-content-default bg-bg-default focus:border-border-emphasis h-9 w-full rounded-lg border px-3 text-sm focus:outline-none focus:ring-neutral-500 dark:focus:border-neutral-400 dark:focus:ring-neutral-400"+ />+ </div>+ <Button+ type="submit"+ text={isSendingOtp ? "Saving..." : "Save"}+ className="h-9 w-fit shrink-0 rounded-lg px-4"+ loading={isSendingOtp}+ />+ </form>+ </div>+ );+}++function TremendousOtpVerifyForm({+ email,+ onSuccess,+ errorMessage,+ setErrorMessage,+}: {+ email: string;+ onSuccess: () => void;+ errorMessage: string | null;+ setErrorMessage: Dispatch<SetStateAction<string | null>>;+}) {+ const router = useRouter();+ const token = useEmbedToken();+ const { isMobile } = useMediaQuery();+ const [code, setCode] = useState("");+ const [isVerifying, setIsVerifying] = useState(false);++ const verifyOtp = async () => {+ if (code.length !== 6) {+ return;+ }++ setIsVerifying(true);+ setErrorMessage(null);++ try {+ const response = await fetch(+ "/api/embed/referrals/tremendous/verify-otp",+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify({ email, code }),+ },+ );++ const result = await response.json();++ if (!response.ok) {+ setErrorMessage(+ result.error?.message ?? "Something went wrong. Please try again.",+ );+ setCode("");+ return;+ }++ router.refresh();+ onSuccess();+ } catch {+ setErrorMessage("Something went wrong. Please try again.");+ } finally {+ setIsVerifying(false);+ }+ };++ return (+ <div className="bg-bg-muted border-border-subtle border-t p-3">+ {errorMessage && <SettingsErrorAlert message={errorMessage} />}+ <p className="text-content-subtle text-sm">+ Enter the six digit verification code sent to{" "}+ <span className="text-content-default font-medium">{email}</span>+ </p>+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <OTPInput+ maxLength={6}+ value={code}+ onChange={(value) => {+ setCode(value);+ setErrorMessage(null);+ }}+ autoFocus={!isMobile}+ render={({ slots }) => (+ <div className="flex items-center gap-1.5">+ {slots.map(({ char, isActive, hasFakeCaret }, idx) => (+ <div+ key={idx}+ className={cn(+ "relative flex size-10 items-center justify-center text-lg font-medium",+ "text-content-emphasis border-border-default bg-bg-default rounded-lg border transition-all",+ isActive &&+ "border-border-emphasis ring-border-emphasis z-10 ring-2",+ )}+ >+ {char}+ {hasFakeCaret && (+ <div className="animate-caret-blink pointer-events-none absolute inset-0 flex items-center justify-center">+ <div className="bg-content-emphasis h-4 w-px" />+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ onComplete={verifyOtp}+ />+ <Button+ text={isVerifying ? "Verifying..." : "Verify"}+ className="h-9 w-fit shrink-0 rounded-lg"+ loading={isVerifying}+ disabled={code.length !== 6}+ onClick={verifyOtp}+ />+ </div>+ </div>+ );+}++function PayoutMethodCard({+ label,+ icon: Icon,+ isConnected,+ showRecommendedBadge,+ buttonText,+ disabled,+ disabledTooltip,+ onClick,+}: {+ label: string;+ icon: ComponentType<{ className?: string }>;+ isConnected: boolean;+ showRecommendedBadge?: boolean;+ buttonText?: string;+ disabled?: boolean;+ disabledTooltip?: string;+ onClick?: () => void;+}) {+ return (+ <div+ className={cn(+ "border-border-subtle flex items-center rounded-lg border p-3",+ !isConnected && "bg-bg-muted",+ )}+ >+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="border-border-muted bg-bg-default flex size-8 shrink-0 items-center justify-center rounded-lg border">+ <Icon className="text-content-emphasis size-[18px]" />+ </div>+ <h2 className="text-content-emphasis text-sm font-semibold">{label}</h2>+ {showRecommendedBadge && (+ <Badge+ variant="blue"+ className="rounded-md px-1 py-0 text-xs font-semibold"+ >+ Recommended+ </Badge>+ )}++ {isConnected && (+ <Badge+ variant="green"+ className="rounded-md px-1 py-0 text-xs font-semibold"+ >+ Connected+ </Badge>+ )}+ </div>++ <PayoutMethodButton+ className="h-8 w-fit shrink-0 rounded-lg px-3 py-2"+ text={buttonText ?? (isConnected ? "Edit" : "Connect")}+ variant={isConnected ? "secondary" : "primary"}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ onClick={onClick}+ />+ </div>+ );+}++function TremendousGiftCardOption({+ isConnected,+ hasAnyConnected,+ tremendousEmail,+}: {+ isConnected: boolean;+ hasAnyConnected: boolean;+ tremendousEmail: string | null;+}) {+ const [panel, setPanel] = useState<GiftCardPanel>("collapsed");+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [verifiedEmail, setVerifiedEmail] = useState("");++ const disabled = (hasAnyConnected && !isConnected) || isConnected;+ const disabledTooltip = isConnected+ ? `Your payouts are currently connected to ${tremendousEmail ?? "your email"}. Please contact support if you need to update your payout email.`+ : disabled+ ? "This payout method is unavailable because you already have another payout method connected."+ : undefined;++ const isExpanded = panel !== "collapsed";++ return (+ <div+ className={cn(+ "border-border-subtle overflow-hidden rounded-lg border",+ !isConnected && "bg-bg-muted",+ hasAnyConnected && !isConnected && "opacity-50",+ )}+ >+ <div className="flex items-center gap-3 p-3">+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="border-border-muted bg-bg-default flex size-8 shrink-0 items-center justify-center rounded-lg border">+ <Gift className="text-content-emphasis size-[18px]" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-content-emphasis text-sm font-semibold">+ Gift Cards+ </h2>+ {!hasAnyConnected && (+ <Badge+ variant="blue"+ className="rounded-md px-1 py-0 text-xs font-semibold"+ >+ Recommended+ </Badge>+ )}+ {isConnected && (+ <Badge+ variant="green"+ className="rounded-md px-1 py-0 text-xs font-semibold"+ >+ Connected+ </Badge>+ )}+ </div>+ <p className="text-content-subtle mt-0.5 text-xs">+ Gift card payouts are limited to{" "}+ {currencyFormatter(TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS)} per+ payout.+ </p>+ </div>+ </div>++ {!isExpanded ? (+ <PayoutMethodButton+ text={isConnected ? "Edit" : "Connect"}+ className="h-8 w-fit shrink-0 rounded-lg px-3 py-2"+ variant={isConnected ? "secondary" : "primary"}+ disabled={disabled}+ disabledTooltip={disabledTooltip}+ onClick={() => {+ setPanel("email");+ setErrorMessage(null);+ }}+ />+ ) : (+ <Button+ text="Cancel"+ className="h-8 w-fit shrink-0 rounded-lg px-3 py-2"+ variant="secondary"+ onClick={() => {+ setPanel("collapsed");+ setErrorMessage(null);+ }}+ />+ )}+ </div>++ <AnimatePresence initial={false} mode="wait">+ {isExpanded && (+ <motion.div+ key={panel}+ initial={{ opacity: 0, y: -8 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -8 }}+ transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}+ >+ <AnimatedSizeContainer height>+ {panel === "email" ? (+ <TremendousEmailForm+ initialEmail={tremendousEmail ?? ""}+ onSuccess={(email) => {+ setVerifiedEmail(email);+ setPanel("verify");+ setErrorMessage(null);+ }}+ errorMessage={errorMessage}+ setErrorMessage={setErrorMessage}+ />+ ) : (+ <TremendousOtpVerifyForm+ email={verifiedEmail}+ onSuccess={() => {+ setPanel("collapsed");+ setErrorMessage(null);+ }}+ errorMessage={errorMessage}+ setErrorMessage={setErrorMessage}+ />+ )}+ </AnimatedSizeContainer>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ );+}++function CashPayoutMethod({+ isConnected,+ hasAnyConnected,+}: {+ isConnected: boolean;+ hasAnyConnected: boolean;+}) {+ const disabled = hasAnyConnected && !isConnected;++ return (+ <PayoutMethodCard+ label="Cash"+ icon={MoneyBill}+ isConnected={isConnected}+ buttonText={isConnected ? "Settings" : "Connect"}+ disabled={disabled}+ disabledTooltip={+ disabled+ ? "This payout method is unavailable because you already have another payout method connected."+ : undefined+ }+ onClick={() => {+ window.open("https://partners.dub.co/payouts?settings=true", "_blank");+ }}+ />+ );+}++export function ReferralsEmbedSettings() {+ const { partner } = useReferralsEmbedData();++ const hasAnyConnected = Boolean(partner.defaultPayoutMethod);+ const isGiftCardConnected = partner.defaultPayoutMethod === "tremendous";+ const isCashConnected = hasAnyConnected && !isGiftCardConnected;++ return (+ <div className="border-border-muted bg-bg-default space-y-4 rounded-lg border p-4 sm:p-6">+ <div className="space-y-1">+ <h3 className="text-content-emphasis text-base font-semibold">+ Payout method+ </h3>+ <p className="text-content-subtle text-sm">+ Select your payout method.{" "}+ <span className="text-content-default font-medium">+ This can't be changed after a method is connected.+ </span>+ </p>+ </div>++ <div className="space-y-4">+ <TremendousGiftCardOption+ isConnected={isGiftCardConnected}+ hasAnyConnected={hasAnyConnected}+ tremendousEmail={partner.tremendousEmail}+ />+ <CashPayoutMethod+ isConnected={isCashConnected}+ hasAnyConnected={hasAnyConnected}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsxindex 212412403c..2f083654ce 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx@@ -58,6 +58,8 @@ const failureTooltips: Record<PartnerPayoutMethod, string> = {"Payout failures are usually due to incorrect wallet configuration. Once you've [updated your account](/payouts?settings=true), you can retry the payout.",paypal:"Payout failures are usually due to incorrect PayPal account configuration. Once you've [updated your account](/payouts?settings=true), you can retry the payout.",+ tremendous:+ "Payout failures are usually due to an invalid gift card email or delivery issue. Once you've [updated your account](/payouts?settings=true), you can retry the payout.",};function PayoutDetailsSheetContent({ payout }: PayoutDetailsSheetProps) {diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsxindex eb010930de..0ffe5f0b2a 100644--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx@@ -65,6 +65,7 @@ async function PayoutRSC() {stripeRecipientId: true,paypalEmail: true,defaultPayoutMethod: true,+ tremendousEmail: true,},});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsxindex dfc360bfde..fe06cdd4f7 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx@@ -5,12 +5,17 @@ import { useFraudGroupCount } from "@/lib/swr/use-fraud-groups-count";import { usePayoutsCount } from "@/lib/swr/use-payouts-count";import useProgram from "@/lib/swr/use-program";import useWorkspace from "@/lib/swr/use-workspace";+import { TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS } from "@/lib/tremendous/constants";import { FraudGroupCountByPartner, PayoutResponse } from "@/lib/types";import { ExternalPayoutsIndicator } from "@/ui/partners/external-payouts-indicator";import { PartnerRowItem } from "@/ui/partners/partner-row-item";import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";-import { PayoutStatus, ProgramPayoutMode } from "@dub/prisma/client";+import {+ PartnerPayoutMethod,+ PayoutStatus,+ ProgramPayoutMode,+} from "@dub/prisma/client";import {AnimatedSizeContainer,Button,@@ -77,6 +82,13 @@ function isPayoutEligibleForBatchConfirm(return false;}+ if (+ payout.partner.defaultPayoutMethod === PartnerPayoutMethod.tremendous &&+ payout.amount > TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS+ ) {+ return false;+ }+return true;}@@ -271,6 +283,13 @@ export function PayoutTable() {(payout) => !isPayoutEligibleForBatchConfirm(payout, eligibilityCtx),);+ const maxGiftCardPayoutAmount = currencyFormatter(+ TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,+ {+ trailingZeroDisplay: "stripIfInteger",+ },+ );+return (<Buttonvariant="primary"@@ -296,6 +315,10 @@ export function PayoutTable() {</a></li><li>Partner has not connected payouts</li>+ <li>+ Exceeds the {maxGiftCardPayoutAmount} cap for gift card+ payouts+ </li><li>On hold due to{" "}<Link@@ -493,6 +516,28 @@ function AmountRowItem({</Tooltip>);}++ if (+ payout.partner.defaultPayoutMethod === PartnerPayoutMethod.tremendous &&+ payout.amount > TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS+ ) {+ const maxPayoutAmount = currencyFormatter(+ TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,+ {+ trailingZeroDisplay: "stripIfInteger",+ },+ );++ return (+ <Tooltip+ content={`This payout exceeds the ${maxPayoutAmount} cap for gift card payouts. The partner must connect another payout method to receive this amount.`}+ >+ <span className="cursor-help truncate text-neutral-400 underline decoration-dotted underline-offset-2">+ {display}+ </span>+ </Tooltip>+ );+ }}return display;diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsxindex fe7a9f3c65..e7bb7c51cf 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsx@@ -39,8 +39,7 @@ export default function WebhookLogsPageClient({);const [detailsSheetState, setDetailsSheetState] = useState<- | { open: false; eventId: string | null }- | { open: true; eventId: string }+ { open: false; eventId: string | null } | { open: true; eventId: string }>({ open: false, eventId: null });const currentEvent = useMemo(@@ -61,7 +60,9 @@ export default function WebhookLogsPageClient({return [currentIndex > 0 ? events[currentIndex - 1].event_id : null,- currentIndex < events.length - 1 ? events[currentIndex + 1].event_id : null,+ currentIndex < events.length - 1+ ? events[currentIndex + 1].event_id+ : null,];}, [events, detailsSheetState.eventId]);diff --git a/apps/web/lib/actions/partners/force-withdrawal.ts b/apps/web/lib/actions/partners/force-withdrawal.tsindex cb42fcb66e..e7164afb99 100644--- a/apps/web/lib/actions/partners/force-withdrawal.ts+++ b/apps/web/lib/actions/partners/force-withdrawal.ts@@ -3,6 +3,7 @@import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";import { createStablecoinPayout } from "@/lib/partners/create-stablecoin-payout";import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";+import { sendTremendousPayouts } from "@/lib/tremendous/send-tremendous-payouts";import { redis } from "@/lib/upstash";import { Partner } from "@dub/prisma/client";import { authPartnerActionClient } from "../safe-action";@@ -23,7 +24,11 @@ export const forceWithdrawalAction = authPartnerActionClient.action();}- if (!["connect", "stablecoin"].includes(partner.defaultPayoutMethod)) {+ if (+ !["connect", "stablecoin", "tremendous"].includes(+ partner.defaultPayoutMethod,+ )+ ) {throw new Error("Invalid default payout method found. Please contact support to set one.",);@@ -56,6 +61,11 @@ export const forceWithdrawal = async (partnerId: partner.id,forceWithdrawal: true,});+ } else if (partner.defaultPayoutMethod === "tremendous") {+ await sendTremendousPayouts({+ partnerId: partner.id,+ forceWithdrawal: true,+ });}} finally {await redis.del(lockKey);diff --git a/apps/web/lib/api/payouts/payout-eligibility-filter.ts b/apps/web/lib/api/payouts/payout-eligibility-filter.tsindex 733d04168b..fa2dcfaeb5 100644--- a/apps/web/lib/api/payouts/payout-eligibility-filter.ts+++ b/apps/web/lib/api/payouts/payout-eligibility-filter.ts@@ -1,4 +1,5 @@import { getPlanCapabilities } from "@/lib/plan-capabilities";+import { TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS } from "@/lib/tremendous/constants";import { Prisma, Program, Project } from "@dub/prisma/client";export function getPayoutEligibilityFilter({@@ -23,6 +24,15 @@ export function getPayoutEligibilityFilter({},},}),+ // Gift card payouts are capped at $2,000 per payout+ NOT: {+ partner: {+ defaultPayoutMethod: "tremendous",+ },+ amount: {+ gt: TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,+ },+ },};switch (program.payoutMode) {diff --git a/apps/web/lib/constants/payouts-supported-countries.ts b/apps/web/lib/constants/payouts-supported-countries.tsindex 0824960775..97c4d1415a 100644--- a/apps/web/lib/constants/payouts-supported-countries.ts+++ b/apps/web/lib/constants/payouts-supported-countries.ts@@ -3,6 +3,7 @@ import {COUNTRIES,PAYPAL_SUPPORTED_COUNTRIES,STABLECOIN_SUPPORTED_COUNTRIES,+ TREMENDOUS_SUPPORTED_COUNTRIES,} from "@dub/utils";import { getPayoutMethodsForCountry } from "../partners/get-payout-methods-for-country";@@ -11,6 +12,7 @@ export const PAYOUT_SUPPORTED_COUNTRIES = [...STABLECOIN_SUPPORTED_COUNTRIES,...CONNECT_SUPPORTED_COUNTRIES,...PAYPAL_SUPPORTED_COUNTRIES,+ ...TREMENDOUS_SUPPORTED_COUNTRIES,]),].sort((a, b) => COUNTRIES[a].localeCompare(COUNTRIES[b]))diff --git a/apps/web/lib/partners/create-stripe-transfer.ts b/apps/web/lib/partners/create-stripe-transfer.tsindex ec042d801a..6eb411dd2e 100644--- a/apps/web/lib/partners/create-stripe-transfer.ts+++ b/apps/web/lib/partners/create-stripe-transfer.ts@@ -77,18 +77,20 @@ export const createStripeTransfer = async ({},include: commonInclude,}),- prisma.payout.findMany({- where: {- partnerId: partner.id,- invoiceId,- status: "processing",- method: "connect",- },- orderBy: {- id: "asc",- },- include: commonInclude,- }),+ invoiceId+ ? prisma.payout.findMany({+ where: {+ partnerId: partner.id,+ invoiceId,+ status: "processing",+ method: "connect",+ },+ orderBy: {+ id: "asc",+ },+ include: commonInclude,+ })+ : Promise.resolve([]),],);diff --git a/apps/web/lib/payouts/get-partner-payout-methods.ts b/apps/web/lib/payouts/get-partner-payout-methods.tsindex 1b14daddc2..a47cfbd7fe 100644--- a/apps/web/lib/payouts/get-partner-payout-methods.ts+++ b/apps/web/lib/payouts/get-partner-payout-methods.ts@@ -13,6 +13,7 @@ export async function getPartnerPayoutMethods(| "stripeRecipientId"| "paypalEmail"| "defaultPayoutMethod"+ | "tremendousEmail">,) {const availablePayoutMethods = getPayoutMethodsForCountry({@@ -83,6 +84,17 @@ export async function getPartnerPayoutMethods(});}+ // Tremendous (gift cards) — only when connected via the referral embed+ if (partner.tremendousEmail) {+ payoutMethods.push({+ type: PartnerPayoutMethod.tremendous,+ label: "Gift Cards",+ default: partner.defaultPayoutMethod === PartnerPayoutMethod.tremendous,+ connected: true,+ identifier: partner.tremendousEmail,+ });+ }+const stablecoinConnected = payoutMethods.some((m) => m.type === PartnerPayoutMethod.stablecoin && m.connected,);diff --git a/apps/web/lib/payouts/recompute-partner-payout-state.ts b/apps/web/lib/payouts/recompute-partner-payout-state.tsindex 72d3a77644..0efefe979a 100644--- a/apps/web/lib/payouts/recompute-partner-payout-state.ts+++ b/apps/web/lib/payouts/recompute-partner-payout-state.ts@@ -8,6 +8,7 @@ const PAYOUT_METHOD_PRIORITY: PartnerPayoutMethod[] = [PartnerPayoutMethod.stablecoin,PartnerPayoutMethod.connect,PartnerPayoutMethod.paypal,+ PartnerPayoutMethod.tremendous,];/**@@ -23,6 +24,7 @@ export async function recomputePartnerPayoutState(| "paypalEmail"| "payoutsEnabledAt"| "defaultPayoutMethod"+ | "tremendousEmail">,) {const [connectAccount, stablecoinAccount] = await Promise.all([@@ -61,6 +63,8 @@ export async function recomputePartnerPayoutState(const paypalActive = Boolean(partner.paypalEmail);+ const tremendousActive = Boolean(partner.tremendousEmail);+const activePayoutMethods = PAYOUT_METHOD_PRIORITY.filter((method) => {switch (method) {case PartnerPayoutMethod.stablecoin:@@ -69,6 +73,8 @@ export async function recomputePartnerPayoutState(return connectActive;case PartnerPayoutMethod.paypal:return paypalActive;+ case PartnerPayoutMethod.tremendous:+ return tremendousActive;default:return false;}@@ -102,6 +108,7 @@ export async function recomputePartnerPayoutState(connectActive,stablecoinActive,paypalActive,+ tremendousActive,payoutsEnabledAt,defaultPayoutMethod,}),diff --git a/apps/web/lib/tremendous/configuration.ts b/apps/web/lib/tremendous/configuration.tsnew file mode 100644index 0000000000..c423b4bb01--- /dev/null+++ b/apps/web/lib/tremendous/configuration.ts@@ -0,0 +1,8 @@+import { Configuration, Environments } from "tremendous";++export const tremendousConfiguration = new Configuration({+ basePath: process.env.TREMENDOUS_API_KEY?.startsWith("TEST_")+ ? Environments.testflight+ : Environments.production,+ accessToken: process.env.TREMENDOUS_API_KEY,+});diff --git a/apps/web/lib/tremendous/constants.ts b/apps/web/lib/tremendous/constants.tsnew file mode 100644index 0000000000..aaa876aefb--- /dev/null+++ b/apps/web/lib/tremendous/constants.ts@@ -0,0 +1,32 @@+import { ACME_PROGRAM_ID } from "@dub/utils";++export const TREMENDOUS_ENABLED_PROGRAM_IDS = [+ ACME_PROGRAM_ID,+ "prog_1KPAZMF49X9A1WEWRBM55KZY7", // Upheal+];++export const TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS = 200_000;++// https://api.tremendous.com/prohibited_top_level_domains.txt+export const TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS = [+ ".af",+ ".by",+ ".cu",+ ".ir",+ ".iq",+ ".mm",+ ".kp",+ ".ru",+ ".su",+ ".рф",+ ".sy",+ ".ua",+ ".ve",+ ".ye",+];++export const TREMENDOUS_PRODUCT_IDS = [+ "A2J05SWPI2QG", // Virtual Visa+ "Q24BD9EZ332JT", // Physical Visa+ "OKMHM2X2OHYV", // Amazon.com+];diff --git a/apps/web/lib/tremendous/create-tremendous-campaign.ts b/apps/web/lib/tremendous/create-tremendous-campaign.tsnew file mode 100644index 0000000000..f47abbc7fe--- /dev/null+++ b/apps/web/lib/tremendous/create-tremendous-campaign.ts@@ -0,0 +1,37 @@+import { prisma } from "@dub/prisma";+import { Program } from "@dub/prisma/client";+import { CampaignsApi, CreateCampaign200Response } from "tremendous";+import { tremendousConfiguration } from "./configuration";+import { TREMENDOUS_PRODUCT_IDS } from "./constants";++export async function createTremendousCampaign(+ program: Pick<Program, "id" | "tremendousCampaignId" | "name" | "logo">,+) {+ if (program.tremendousCampaignId) {+ return;+ }++ const campaignsApi = new CampaignsApi(tremendousConfiguration);++ const { data } = await campaignsApi.createCampaign({+ name: `${program.name} Partners`,+ description: `Earn gift cards for referring new partners to ${program.name}`,+ products: TREMENDOUS_PRODUCT_IDS,+ fee_charged_to: "RECIPIENT",+ webpage_style: {+ headline: `${program.name} sent you a {{ amount }} gift card`,+ logo_image_url: program.logo,+ },+ });++ const { campaign } = data as CreateCampaign200Response;++ await prisma.program.update({+ where: {+ id: program.id,+ },+ data: {+ tremendousCampaignId: campaign.id,+ },+ });+}diff --git a/apps/web/lib/tremendous/send-tremendous-payouts.ts b/apps/web/lib/tremendous/send-tremendous-payouts.tsnew file mode 100644index 0000000000..13fd06383f--- /dev/null+++ b/apps/web/lib/tremendous/send-tremendous-payouts.ts@@ -0,0 +1,292 @@+import { sendEmail } from "@dub/email";+import PartnerTremendousPayout from "@dub/email/templates/partner-tremendous-payout";+import { prisma } from "@dub/prisma";+import { Prisma } from "@dub/prisma/client";+import {+ APP_DOMAIN_WITH_NGROK,+ chunk,+ currencyFormatter,+ log,+} from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import { CreateOrder200Response, OrdersApi } from "tremendous";+import { trackCommissionStatusUpdatesByProgram } from "../api/commissions/track-commission-update-activity-log";+import { enqueueBatchJobs } from "../cron/enqueue-batch-jobs";+import { createPayoutsIdempotencyKey } from "../payouts/create-payouts-idempotency-key";+import { markPayoutsAsProcessed } from "../payouts/mark-payouts-as-processed";+import { tremendousConfiguration } from "./configuration";+import { TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS } from "./constants";++export async function sendTremendousPayouts({+ partnerId,+ invoiceId,+ forceWithdrawal = false,+}: {+ partnerId: string;+ invoiceId?: string;+ forceWithdrawal?: boolean;+}) {+ console.log(`Processing Tremendous payouts....`, {+ partnerId,+ invoiceId,+ forceWithdrawal,+ });++ const partner = await prisma.partner.findUniqueOrThrow({+ where: {+ id: partnerId,+ },+ select: {+ id: true,+ name: true,+ email: true,+ tremendousEmail: true,+ payoutsEnabledAt: true,+ },+ });++ if (!partner.tremendousEmail || !partner.payoutsEnabledAt) {+ throw new Error(+ `Partner ${partner.email} does not have an active payout account.`,+ );+ }++ const commonInclude: Prisma.PayoutInclude = {+ program: {+ select: {+ id: true,+ name: true,+ logo: true,+ workspaceId: true,+ tremendousCampaignId: true,+ },+ },+ };++ const [previouslyProcessedPayouts, currentInvoicePayouts] = await Promise.all(+ [+ prisma.payout.findMany({+ where: {+ partnerId: partner.id,+ status: "processed",+ tremendousOrderId: null,+ mode: "internal",+ method: "tremendous",+ amount: {+ lte: TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,+ },+ },+ orderBy: {+ id: "asc",+ },+ include: commonInclude,+ }),+ invoiceId+ ? prisma.payout.findMany({+ where: {+ partnerId: partner.id,+ invoiceId,+ status: "processing",+ mode: "internal",+ method: "tremendous",+ tremendousOrderId: null,+ amount: {+ lte: TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS,+ },+ },+ orderBy: {+ id: "asc",+ },+ include: commonInclude,+ })+ : Promise.resolve([]),+ ],+ );++ const allPayouts = [...previouslyProcessedPayouts, ...currentInvoicePayouts];++ if (allPayouts.length === 0) {+ console.log("No payouts for sending via Tremendous, skipping...");+ return;+ }++ const totalTransferableAmount = allPayouts.reduce(+ (acc, payout) => acc + payout.amount,+ 0,+ );++ if (totalTransferableAmount === 0) {+ console.log("No payouts for sending via Tremendous, skipping...");+ return;+ }++ if (totalTransferableAmount > TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS) {+ throw new Error(+ `Tremendous payout amount is greater than the maximum allowed amount of ${currencyFormatter(TREMENDOUS_MAX_PAYOUT_AMOUNT_CENTS)}.`,+ );+ }++ const payoutIds = allPayouts.map((p) => p.id);++ const idempotencyKey = createPayoutsIdempotencyKey({+ partnerId: partner.id,+ invoiceId,+ payoutIds,+ });++ const program = allPayouts[0].program;++ if (!program.tremendousCampaignId) {+ throw new Error(+ "Tremendous campaign ID is not configured for this program.",+ );+ }++ const ordersApi = new OrdersApi(tremendousConfiguration);++ const { data } = await ordersApi.createOrder({+ external_id: idempotencyKey,+ payment: {+ funding_source_id: "balance",+ },+ reward: {+ campaign_id: program.tremendousCampaignId,+ value: {+ denomination: totalTransferableAmount / 100,+ currency_code: "USD",+ },+ recipient: {+ email: partner.tremendousEmail,+ name: partner.name || partner.tremendousEmail,+ },+ delivery: {+ method: "LINK",+ meta: {+ message: `Dub Partners payout (${[...new Set(allPayouts.map((p) => p.program.name))].join(", ")})`,+ },+ },+ },+ });++ const { order } = data as CreateOrder200Response;+ const reward = order.rewards?.[0];+ const redeemUrl = reward?.delivery?.link;++ if (order.status !== "EXECUTED") {+ console.error(+ `Tremendous order ${order.id} status is not EXECUTED: ${order.status}`,+ );+ await markPayoutsAsProcessed(currentInvoicePayouts);+ return;+ }++ if (!redeemUrl) {+ console.error(`No redeem URL found for Tremendous order: ${order.id}`);+ await markPayoutsAsProcessed(currentInvoicePayouts);+ return;+ }++ console.log("Tremendous order created", order);++ const commissions = await prisma.commission.findMany({+ where: {+ payoutId: {+ in: payoutIds,+ },+ },+ select: {+ id: true,+ amount: true,+ earnings: true,+ status: true,+ programId: true,+ },+ });++ await prisma.payout.updateMany({+ where: {+ id: {+ in: payoutIds,+ },+ },+ data: {+ tremendousOrderId: order.id,+ status: "completed",+ paidAt: new Date(),+ method: "tremendous",+ },+ });++ const commissionIds = commissions.map((c) => c.id);++ let totalUpdatedCommissions = 0;+ for (const commissionIdsBatch of chunk(commissionIds, 250)) {+ try {+ const { count } = await prisma.commission.updateMany({+ where: {+ id: {+ in: commissionIdsBatch,+ },+ },+ data: {+ status: "paid",+ },+ });++ totalUpdatedCommissions += count;+ console.log(+ `Marked ${totalUpdatedCommissions}/${commissionIds.length} commissions as paid`,+ );+ } catch (error) {+ await log({+ message: `[sendTremendousPayouts] Failed to mark commissions as paid for payouts ${payoutIds.join(+ ", ",+ )}: ${error.message}`,+ type: "errors",+ mention: true,+ });+ }+ }++ waitUntil(+ Promise.allSettled([+ trackCommissionStatusUpdatesByProgram({+ commissions,+ payouts: allPayouts,+ newStatus: "paid",+ }),++ enqueueBatchJobs(+ payoutIds.map((payoutId) => ({+ queueName: "create-referral-commissions",+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/queue`,+ body: {+ payoutId,+ },+ })),+ ),+ ]),+ );++ if (partner.email) {+ const payout = allPayouts[0];+ const formattedAmount = currencyFormatter(totalTransferableAmount);++ await sendEmail({+ variant: "notifications",+ to: partner.email,+ subject: forceWithdrawal+ ? `A withdrawal of ${formattedAmount} has been initiated from your Dub account`+ : `You've received a ${formattedAmount} reward from ${payout.program.name}`,+ react: PartnerTremendousPayout({+ email: partner.email,+ program: payout.program,+ payout: {+ ...payout,+ amount: totalTransferableAmount,+ },+ redeemUrl,+ }),+ });+ }+}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex ea80069ed9..977536375b 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -532,6 +532,7 @@ export type PartnerProps = z.infer<typeof PartnerSchema> & {userId: string;platforms: PartnerPlatformProps[];defaultPayoutMethod: PartnerPayoutMethod | null;+ tremendousEmail: string | null;};export type PartnerRewindProps = z.infer<typeof PartnerRewindSchema>;diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.tsindex f03267ce9e..907c581967 100644--- a/apps/web/lib/zod/schemas/auth.ts+++ b/apps/web/lib/zod/schemas/auth.ts@@ -11,6 +11,7 @@ export const passwordSchema = zexport const emailSchema = z.string()+ .trim().email().min(1).transform((email) => email.toLowerCase());diff --git a/apps/web/package.json b/apps/web/package.jsonindex 3386bd84e7..fca7af61a7 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -133,6 +133,7 @@"stripe": "^18.2.0","svix": "^1.76.1","swr": "^2.1.5",+ "tremendous": "4.12.0","unique-names-generator": "^4.7.1","unsplash-js": "^7.0.18","use-debounce": "^10.0.4",diff --git a/apps/web/playwright/workspaces/billing-trial.spec.ts b/apps/web/playwright/workspaces/billing-trial.spec.tsindex d676405ac0..cdb689e0fe 100644--- a/apps/web/playwright/workspaces/billing-trial.spec.ts+++ b/apps/web/playwright/workspaces/billing-trial.spec.ts@@ -122,7 +122,9 @@ test.describe("Free trial user navigation", () => {}});- test("billing settings page shows trial banner and CTAs", async ({ page }) => {+ 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({@@ -184,9 +186,7 @@ test.describe("Free trial user navigation", () => {"You'll be charged today and your trial will end.",),).toBeVisible();- await confirmModal- .getByRole("button", { name: "Start paid plan" })- .click();+ await confirmModal.getByRole("button", { name: "Start paid plan" }).click();await page.waitForURL((u) => {const url = new URL(u);diff --git a/apps/web/ui/partners/payout-status-descriptions.ts b/apps/web/ui/partners/payout-status-descriptions.tsindex 9fa2cb98fa..038063f0f7 100644--- a/apps/web/ui/partners/payout-status-descriptions.ts+++ b/apps/web/ui/partners/payout-status-descriptions.ts@@ -40,4 +40,14 @@ export const PAYOUT_STATUS_DESCRIPTIONS: Record<sent: "",completed: "Payouts that have been paid out to your PayPal account",},++ tremendous: {+ pending:+ "Payouts that have passed the [program's holding period](https://dub.co/help/article/commissions-payouts#what-does-holding-period-mean) and are awaiting payment from the program (once it reaches the [program's minimum payout amount](https://dub.co/help/article/commissions-payouts#what-does-minimum-payout-amount-mean)).",+ processing:+ "Payouts that are being processed by the program – this can take up to 5 business days.",+ processed: "",+ sent: "Payouts that are on their way to your gift card email – delivery is typically within minutes.",+ completed: "Payouts that have been delivered to your gift card email.",+ },};diff --git a/apps/web/ui/partners/payouts/payout-method-config.ts b/apps/web/ui/partners/payouts/payout-method-config.tsindex 9237f7b35c..1fbae81e87 100644--- a/apps/web/ui/partners/payouts/payout-method-config.ts+++ b/apps/web/ui/partners/payouts/payout-method-config.ts@@ -3,6 +3,7 @@ import type { PartnerPayoutMethod } from "@dub/prisma/client";import {Calendar6,CircleDollar,+ Gift,Globe,GreekTemple,Paypal,@@ -54,6 +55,14 @@ export const PAYOUT_METHODS = [},],},+ {+ id: "tremendous" as const,+ title: "Gift card",+ recommended: false,+ icon: Gift,+ iconWrapperClass: "border-[#1717171A] bg-white",+ features: [],+ },] as const;/** When bank or PayPal is the only choice (e.g. US), avoid international wire copy (FX / 15 days). */diff --git a/apps/web/ui/partners/payouts/payout-method-dropdown.tsx b/apps/web/ui/partners/payouts/payout-method-dropdown.tsxindex eb5805f1ee..0946e7b253 100644--- a/apps/web/ui/partners/payouts/payout-method-dropdown.tsx+++ b/apps/web/ui/partners/payouts/payout-method-dropdown.tsx@@ -180,13 +180,24 @@ function PayoutMethodItem({</span></div></div>- <Button- variant={method.connected ? "secondary" : "primary"}- text={method.connected ? "Manage" : "Connect"}- onClick={() => onAction(method.type, method.connected)}- loading={isActionPending}- className="h-7 w-fit shrink-0 cursor-pointer text-xs"- />++ {method.type === "tremendous" ? (+ <Button+ variant="secondary"+ text="Manage"+ disabled={true}+ disabledTooltip="Contact support if you need to update this email."+ className="h-7 w-fit shrink-0 cursor-pointer text-xs"+ />+ ) : (+ <Button+ variant={method.connected ? "secondary" : "primary"}+ text={method.connected ? "Manage" : "Connect"}+ onClick={() => onAction(method.type, method.connected)}+ loading={isActionPending}+ className="h-7 w-fit shrink-0 cursor-pointer text-xs"+ />+ )}</div>);}diff --git a/packages/email/src/templates/partner-payout-confirmed.tsx b/packages/email/src/templates/partner-payout-confirmed.tsxindex 927702b8db..d86a65f302 100644--- a/packages/email/src/templates/partner-payout-confirmed.tsx+++ b/packages/email/src/templates/partner-payout-confirmed.tsx@@ -20,6 +20,7 @@ const PAYOUT_METHOD_LABELS: Record<PartnerPayoutMethod, string> = {connect: "Stripe Express",stablecoin: "USDC wallet",paypal: "PayPal",+ tremendous: "Gift card",} as const;// Send this email when the payout is confirmed when payment is send using ACHdiff --git a/packages/email/src/templates/partner-tremendous-payout.tsx b/packages/email/src/templates/partner-tremendous-payout.tsxnew file mode 100644index 0000000000..8d121d029b--- /dev/null+++ b/packages/email/src/templates/partner-tremendous-payout.tsx@@ -0,0 +1,134 @@+import { currencyFormatter, DUB_WORDMARK, formatDate } 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 PartnerTremendousPayout({+ email = "[email protected]",+ program = {+ name: "Acme",+ logo: DUB_WORDMARK,+ },+ payout = {+ id: "po_8VuCr2i7WnG65d4TNgZO19fT",+ amount: 200,+ periodStart: new Date("2026-02-01"),+ periodEnd: new Date("2026-02-01"),+ },+ redeemUrl = "https://www.tremendous.com/rewards/example",+}: {+ email: string;+ program: {+ name: string;+ logo: string | null;+ };+ payout: {+ id: string;+ amount: number;+ periodStart?: Date | null;+ periodEnd?: Date | null;+ };+ redeemUrl: string;+}) {+ const payoutAmountInDollars = currencyFormatter(payout.amount);++ const startDate = payout.periodStart+ ? formatDate(payout.periodStart, {+ year: "numeric",+ month: "short",+ day: "numeric",+ timeZone: "UTC",+ })+ : null;++ const endDate = payout.periodEnd+ ? formatDate(payout.periodEnd, {+ year: "numeric",+ month: "short",+ day: "numeric",+ timeZone: "UTC",+ })+ : null;++ let preview = `${program.name} has sent you a ${payoutAmountInDollars} reward`;++ if (startDate && endDate) {+ preview += ` for affiliate commissions made ${+ startDate === endDate+ ? `on ${startDate}`+ : `from ${startDate} to ${endDate}`+ }`;+ }++ const payoutPeriodMessage =+ startDate && endDate ? (+ startDate === endDate ? (+ <>+ on <strong className="text-black">{startDate}</strong>.+ </>+ ) : (+ <>+ from <strong className="text-black">{startDate}</strong> to{" "}+ <strong className="text-black">{endDate}</strong>.+ </>+ )+ ) : (+ "."+ );++ return (+ <Html>+ <Head />+ <Preview>{preview}</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-10 max-w-[600px] 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-lg font-medium text-black">+ You've been paid!+ </Heading>++ <Text className="text-sm leading-6 text-neutral-600">+ Good news! <strong className="text-black">{program.name}</strong>{" "}+ has sent you{" "}+ <strong className="text-black">+ {currencyFormatter(payout.amount)}+ </strong>{" "}+ for affiliate commissions made via Dub Partners{" "}+ {payoutPeriodMessage}+ </Text>++ <Text className="text-sm leading-6 text-neutral-600">+ Click the button below to redeem your reward.+ </Text>++ <Section className="my-8">+ <Link+ className="rounded-lg bg-neutral-900 px-4 py-2.5 text-[12px] font-semibold text-white no-underline"+ href={redeemUrl}+ >+ Redeem reward+ </Link>+ </Section>++ <Footer email={email} />+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/packages/email/src/templates/partner-tremendous-verify-email.tsx b/packages/email/src/templates/partner-tremendous-verify-email.tsxnew file mode 100644index 0000000000..2d53006ee4--- /dev/null+++ b/packages/email/src/templates/partner-tremendous-verify-email.tsx@@ -0,0 +1,61 @@+import { DUB_WORDMARK } from "@dub/utils";+import {+ Body,+ Container,+ Head,+ Heading,+ Html,+ Img,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";+import { Footer } from "../components/footer";++export default function PartnerTremendousVerifyEmail({+ email = "[email protected]",+ code = "123456",+ expiryMinutes = 5,+}: {+ email: string;+ code: string;+ expiryMinutes?: number;+}) {+ return (+ <Html>+ <Head />+ <Preview>Verify your gift card payout email</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">+ Verify your gift card payout email+ </Heading>++ <Text className="mx-auto text-sm leading-6 text-neutral-600">+ Enter this code to verify your email address for gift card payouts+ via Dub Partners:+ </Text>++ <Section className="my-8 rounded-lg border border-solid border-neutral-200">+ <div className="mx-auto w-fit px-6 py-3 text-center font-mono text-2xl font-semibold tracking-[0.25em]">+ {code}+ </div>+ </Section>++ <Text className="text-sm leading-6 text-black">+ This code expires in {expiryMinutes} minutes.+ </Text>++ <Footer email={email} />+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/packages/email/src/types.ts b/packages/email/src/types.tsindex 7b50fd7d7e..430e15a938 100644--- a/packages/email/src/types.ts+++ b/packages/email/src/types.ts@@ -8,7 +8,11 @@ export type WorkspaceProps = {defaultProgramId: string | null;};-export type PartnerPayoutMethod = "connect" | "stablecoin" | "paypal";+export type PartnerPayoutMethod =+ | "connect"+ | "stablecoin"+ | "paypal"+ | "tremendous";export type TrialMarketingEmailProps = {email: string;diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prismaindex b852821417..232443f8c4 100644--- a/packages/prisma/schema/partner.prisma+++ b/packages/prisma/schema/partner.prisma@@ -28,6 +28,7 @@ enum PartnerPayoutMethod {connectstablecoinpaypal+ tremendous}// https://devdocs.veriff.com/v1/docs/how-to-generate-sessions-manually#verification-session-statuses@@ -69,6 +70,7 @@ model Partner {stripeRecipientId String? @uniquepayoutMethodHash String?cryptoWalletAddress String?+ tremendousEmail String? @unique// timestamp fieldscreatedAt DateTime @default(now())@@ -117,6 +119,7 @@ model Partner {@@index(cryptoWalletAddress)@@index(identityVerifiedAt)@@index(referredByPartnerId)+ @@index(tremendousEmail)@@fulltext([email, name, companyName]) // For full-text search}diff --git a/packages/prisma/schema/payout.prisma b/packages/prisma/schema/payout.prismaindex 5105fdbdfa..a680629c50 100644--- a/packages/prisma/schema/payout.prisma+++ b/packages/prisma/schema/payout.prisma@@ -30,6 +30,7 @@ model Payout {stripeTransferId String?stripePayoutId String?stripePayoutTraceId String? @db.Text+ tremendousOrderId String?failureReason String? @db.TextwebhookEventId String? @unique // only for external payoutscreatedAt DateTime @default(now())@@ -55,4 +56,5 @@ model Payout {@@index(userId)@@index(stripePayoutId)@@index(stripeTransferId)+ @@index(tremendousOrderId)}diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prismaindex 6fa6a494b9..7d88029486 100644--- a/packages/prisma/schema/program.prisma+++ b/packages/prisma/schema/program.prisma@@ -47,6 +47,7 @@ model Program {termsUrl String? @db.TexthelpUrl String? @db.TextsupportEmail String?+ tremendousCampaignId String?messagingEnabledAt DateTime?partnerNetworkEnabledAt DateTime?diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.tsindex 3a716300c1..e25351f3b2 100644--- a/packages/utils/src/constants/index.ts+++ b/packages/utils/src/constants/index.ts@@ -17,6 +17,7 @@ export * from "./regions";export * from "./reserved-slugs";export * from "./saml";export * from "./stablecoin-supported-countries";+export * from "./tremendous-supported-countries";// pricing copy & valuesexport * from "./pricing/pricing-plan-compare-features";diff --git a/packages/utils/src/constants/tremendous-supported-countries.ts b/packages/utils/src/constants/tremendous-supported-countries.tsnew file mode 100644index 0000000000..a3df3d279e--- /dev/null+++ b/packages/utils/src/constants/tremendous-supported-countries.ts@@ -0,0 +1,20 @@+import { COUNTRIES } from "./countries";++// @see: https://tremendous.notion.site/Tremendous-Prohibited-Jurisdictions-cbf4040538db4e6d8867a70629526870+const TREMENDOUS_NOT_SUPPORTED_COUNTRIES = [+ "AF", // Afghanistan+ "BY", // Belarus+ "CU", // Cuba+ "IR", // Iran+ "IQ", // Iraq+ "KP", // North Korea+ "RU", // Russia+ "SY", // Syria+ "UA", // Ukraine+ "VE", // Venezuela+ "YE", // Yemen+];++export const TREMENDOUS_SUPPORTED_COUNTRIES = Object.keys(COUNTRIES).filter(+ (country) => !TREMENDOUS_NOT_SUPPORTED_COUNTRIES.includes(country),+);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4af49b16e7..0ba6f4012c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -377,6 +377,9 @@ importers:swr:specifier: ^2.1.5version: 2.1.5([email protected])+ tremendous:+ specifier: 4.12.0+ version: 4.12.0unique-names-generator:specifier: ^4.7.1version: 4.7.1@@ -12524,6 +12527,10 @@ packages:resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}hasBin: true+ resolution: {integrity: sha512-u9JB8vkyR7VIu9HdXWtbrSsNr9+3teeDapZplpN8CrkWtJpgIFBOU4p5JAeuJnBvrLKPLZZpjsb75P+d3X/9Ww==}+ engines: {node: '>=20.0.0', npm: '>=8.0.0'}+resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}@@ -14670,7 +14677,7 @@ snapshots:'@boxyhq/saml20': 1.12.1'@googleapis/admin': 23.5.0([email protected])'@libsql/sqlite3': 0.3.1([email protected])- axios: 1.9.0([email protected])+ axios: 1.9.0encoding: 0.1.13ipaddr.js: 2.2.0jose: 6.0.11@@ -18262,7 +18269,7 @@ snapshots:'@slack/types': 2.20.1'@types/node': 18.11.9'@types/retry': 0.12.0- axios: 1.15.2+ axios: 1.15.2([email protected])eventemitter3: 5.0.1form-data: 4.0.4is-electron: 2.2.2@@ -20432,9 +20439,9 @@ snapshots:dependencies:- follow-redirects: 1.16.0+ follow-redirects: 1.16.0([email protected])form-data: 4.0.5proxy-from-env: 2.1.0transitivePeerDependencies:@@ -20464,7 +20471,7 @@ snapshots:transitivePeerDependencies:- debugdependencies:follow-redirects: 1.15.6([email protected])form-data: 4.0.4@@ -22637,7 +22644,9 @@ snapshots:optionalDependencies:debug: 4.4.0- [email protected]: {}+ optionalDependencies:+ debug: 4.4.0dependencies:@@ -28000,6 +28009,12 @@ snapshots:+ dependencies:+ axios: 1.15.2([email protected])+ transitivePeerDependencies:+ - debug+@@ -28811,7 +28826,7 @@ snapshots:[email protected]([email protected])([email protected](@types/[email protected])([email protected])):dependencies:'@octokit/rest': 19.0.13([email protected])- axios: 1.9.0([email protected])+ axios: 1.15.2([email protected])debug: 4.4.0picocolors: 1.1.1vite: 5.4.8(@types/[email protected])([email protected])