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.

Partner referrals (#3858)

Kiran K81e57fc6b63f
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx
index 3931c0e012..77852848a9 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-application-sheet.tsx
@@ -2,6 +2,7 @@
import { AdminNetworkPartner } from "@/lib/types";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { CountryCombobox } from "@/ui/partners/country-combobox";
import { PartnerAbout } from "@/ui/partners/partner-about";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
import { PartnerInfoCards } from "@/ui/partners/partner-info-cards";
@@ -25,7 +26,7 @@ import {
import { cn, COUNTRIES, currencyFormatter, OG_AVATAR_URL } from "@dub/utils";
import { LayoutGroup, motion } from "motion/react";
import Link from "next/link";
-import { useId, useState } from "react";
+import { useEffect, useId, useState } from "react";
import { NetworkPartnerChangeHistory } from "./network-partner-change-history";
type NetworkPartnerSheetTabId = "about" | "programs" | "duplicates";
@@ -55,6 +56,7 @@ export function NetworkPartnerApplicationSheet({
onPrevious,
onNext,
onReview,
+ onUpdateCountry,
}: {
isOpen: boolean;
setIsOpen: (open: boolean) => void;
@@ -65,13 +67,38 @@ export function NetworkPartnerApplicationSheet({
partner: AdminNetworkPartner,
status: "approved" | "rejected" | "draft",
) => Promise<void>;
+ onUpdateCountry: (
+ partner: AdminNetworkPartner,
+ country: string,
+ ) => Promise<void>;
}) {
const [currentTabId, setCurrentTabId] =
useState<NetworkPartnerSheetTabId>("about");
+ const [selectedCountry, setSelectedCountry] = useState(partner.country ?? "");
+ const [isUpdatingCountry, setIsUpdatingCountry] = useState(false);
const { queryParams } = useRouterStuff();
const showRevertToDraftInsteadOfReject =
isDirectDraftToApprovedNetworkApproval(partner);
+ const isCountryChanged =
+ selectedCountry.length > 0 && selectedCountry !== partner.country;
+
+ useEffect(() => {
+ setSelectedCountry(partner.country ?? "");
+ }, [partner.country, partner.id]);
+
+ const handleUpdateCountry = async () => {
+ if (!isCountryChanged || isUpdatingCountry) {
+ return;
+ }
+
+ setIsUpdatingCountry(true);
+ try {
+ await onUpdateCountry(partner, selectedCountry);
+ } finally {
+ setIsUpdatingCountry(false);
+ }
+ };
const PartnerDetails = (
<div className="rounded-lg border border-neutral-200 bg-neutral-100 p-3">
@@ -131,6 +158,35 @@ export function NetworkPartnerApplicationSheet({
confirmShortcutOptions: { sheet: true, modal: true },
});
+ const {
+ setShowConfirmModal: setShowUpdateCountryConfirm,
+ confirmModal: updateCountryModal,
+ } = useConfirmModal({
+ title: "Update partner country",
+ description: (
+ <div className="space-y-2">
+ <p className="text-sm text-neutral-600">
+ Change country from{" "}
+ <span className="font-medium text-neutral-900">
+ {partner.country ? COUNTRIES[partner.country] : "Unknown"}
+ </span>{" "}
+ to{" "}
+ <span className="font-medium text-neutral-900">
+ {selectedCountry ? COUNTRIES[selectedCountry] : "Unknown"}
+ </span>
+ ?
+ </p>
+ <p className="text-xs text-neutral-500">
+ This will reset the connected Stripe account and payout settings.
+ </p>
+ </div>
+ ),
+ confirmText: "Update country",
+ onConfirm: async () => {
+ await handleUpdateCountry();
+ },
+ });
+
useKeyboardShortcut(
"ArrowRight",
() => {
@@ -180,6 +236,7 @@ export function NetworkPartnerApplicationSheet({
{approveModal}
{rejectModal}
{revertToDraftModal}
+ {updateCountryModal}
<div className="flex size-full flex-col">
<div className="flex h-16 shrink-0 items-center justify-between border-b border-neutral-200 px-6 py-4">
@@ -222,11 +279,34 @@ export function NetworkPartnerApplicationSheet({
partner={partner}
showApplicationRiskAnalysis
/>
- <ScrollContainer className="@3xl/sheet:max-h-[50dvh] @3xl/sheet:pr-1">
+ <div className="rounded-lg border border-neutral-200 bg-neutral-50 p-3">
+ <h3 className="text-sm font-medium text-neutral-900">Country</h3>
+ <p className="mt-1 text-xs text-neutral-500">
+ Updating country clears connected Stripe account and may trigger
+ reverification.
+ </p>
+ <div className="mt-2 flex flex-col gap-2 sm:flex-row sm:items-start">
+ <div className="min-w-0 grow">
+ <CountryCombobox
+ value={selectedCountry}
+ onChange={setSelectedCountry}
+ />
+ </div>
+ <Button
+ type="button"
+ text="Update"
+ className="w-full shrink-0 sm:mt-1.5 sm:w-fit"
+ loading={isUpdatingCountry}
+ onClick={() => setShowUpdateCountryConfirm(true)}
+ disabled={!isCountryChanged || isUpdatingCountry}
+ />
+ </div>
+ </div>
+ <div className="@3xl/sheet:max-h-[50dvh] @3xl/sheet:overflow-y-auto @3xl/sheet:pr-1 overflow-x-hidden">
<NetworkPartnerChangeHistory
changeHistoryLog={partner.changeHistoryLog}
/>
- </ScrollContainer>
+ </div>
</div>
<div className="@3xl/sheet:order-1">
<div className="border-border-subtle overflow-hidden rounded-xl border bg-neutral-100">
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history-item.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history-item.tsx
index 4c744ee039..a4bf39d0d9 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history-item.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history-item.tsx
@@ -6,7 +6,9 @@ import { CountryFlag } from "@/ui/shared/country-flag";
import { StatusBadge, TimestampTooltip } from "@dub/ui";
import { capitalize, COUNTRIES, formatDate } from "@dub/utils";
-type PartnerChangeLogEntry = NonNullable<AdminNetworkPartner["changeHistoryLog"]>[number];
+type PartnerChangeLogEntry = NonNullable<
+ AdminNetworkPartner["changeHistoryLog"]
+>[number];
const FIELD_LABELS: Record<PartnerChangeLogEntry["field"], string> = {
country: "Country",
@@ -20,9 +22,9 @@ export function NetworkPartnerChangeHistoryItem({
entry: PartnerChangeLogEntry;
}) {
return (
- <li className="rounded-lg border border-neutral-200 bg-white p-3">
- <div className="flex items-center justify-between gap-2">
- <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">
+ <li className="min-w-0 overflow-x-hidden rounded-lg border border-neutral-200 bg-white p-3">
+ <div className="flex min-w-0 flex-col items-start justify-between gap-2 sm:flex-row sm:items-center">
+ <p className="min-w-0 text-xs font-medium uppercase tracking-wide text-neutral-500">
{FIELD_LABELS[entry.field]}
</p>
<TimestampTooltip
@@ -30,7 +32,7 @@ export function NetworkPartnerChangeHistoryItem({
side="left"
rows={["local", "utc", "unix"]}
>
- <time className="text-xs text-neutral-500">
+ <time className="block max-w-full truncate text-xs text-neutral-500">
{formatDate(entry.changedAt, {
month: "short",
day: "numeric",
@@ -42,10 +44,14 @@ export function NetworkPartnerChangeHistoryItem({
</TimestampTooltip>
</div>
- <div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
- {renderChangeValue(entry.field, entry.from)}
+ <div className="mt-2 grid min-w-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2 text-sm">
+ <div className="min-w-0 overflow-hidden">
+ {renderChangeValue(entry.field, entry.from)}
+ </div>
<span className="text-neutral-400">→</span>
- {renderChangeValue(entry.field, entry.to)}
+ <div className="min-w-0 overflow-hidden">
+ {renderChangeValue(entry.field, entry.to)}
+ </div>
</div>
</li>
);
@@ -58,29 +64,28 @@ function renderChangeValue(
if (field === "networkStatus" && value) {
const { label, icon, variant } = NetworkStatusBadges[value];
return (
- <StatusBadge variant={variant} icon={icon}>
- {label}
- </StatusBadge>
+ <span className="inline-flex min-w-0 max-w-full">
+ <StatusBadge variant={variant} icon={icon}>
+ {label}
+ </StatusBadge>
+ </span>
);
}
if (field === "country" && value) {
return (
- <span className="inline-flex items-center gap-1 rounded-md border border-neutral-200 bg-neutral-50 px-2 py-0.5 text-xs font-medium text-neutral-700">
+ <span className="inline-flex min-w-0 max-w-full items-center gap-1 rounded-md border border-neutral-200 bg-neutral-50 px-2 py-0.5 text-xs font-medium text-neutral-700">
<CountryFlag countryCode={value} className="size-3.5" />
- {COUNTRIES[value] || value}
+ <span className="truncate">{COUNTRIES[value] || value}</span>
</span>
);
}
- const label =
- value === null
- ? "Not set"
- : capitalize(value);
+ const label = value === null ? "Not set" : capitalize(value);
return (
- <span className="inline-flex items-center rounded-md border border-neutral-200 bg-neutral-50 px-2 py-0.5 text-xs font-medium text-neutral-700">
- {label}
+ <span className="inline-flex min-w-0 max-w-full items-center rounded-md border border-neutral-200 bg-neutral-50 px-2 py-0.5 text-xs font-medium text-neutral-700">
+ <span className="truncate">{label}</span>
</span>
);
}
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history.tsx
index 158a49121e..5eca4ffb1d 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/network-partner-change-history.tsx
@@ -10,15 +10,16 @@ export function NetworkPartnerChangeHistory({
changeHistoryLog: AdminNetworkPartner["changeHistoryLog"];
}) {
const entries = (changeHistoryLog ?? []).toSorted(
- (a, b) =>
- new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime(),
+ (a, b) => new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime(),
);
return (
- <section className="rounded-xl border border-neutral-200 bg-neutral-100 p-4">
+ <section className="w-full min-w-0 max-w-full overflow-x-hidden rounded-xl border border-neutral-200 bg-neutral-100 p-4">
<div className="flex items-center gap-2">
<History className="size-4 text-neutral-500" />
- <h3 className="text-sm font-semibold text-neutral-900">Change history</h3>
+ <h3 className="text-sm font-semibold text-neutral-900">
+ Change history
+ </h3>
</div>
{entries.length === 0 ? (
@@ -26,7 +27,7 @@ export function NetworkPartnerChangeHistory({
No changes have been recorded yet.
</p>
) : (
- <ul className="mt-3 space-y-2">
+ <ul className="mt-3 w-full min-w-0 max-w-full space-y-2 overflow-x-hidden">
{entries.map((entry, index) => (
<NetworkPartnerChangeHistoryItem
key={`${entry.field}-${new Date(entry.changedAt).toISOString()}-${index}`}
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx
index 89166867f0..117872b4dc 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx
@@ -258,6 +258,32 @@ export default function NetworkApplicationsPage() {
}
};
+ const handleUpdatePartnerCountry = async (
+ partner: AdminNetworkPartner,
+ country: string,
+ ) => {
+ try {
+ const response = await fetch(`/api/admin/partners/${partner.id}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ country }),
+ });
+
+ if (!response.ok) {
+ throw new Error((await response.text()) || "Failed to update country.");
+ }
+
+ toast.success(`Partner country updated to ${COUNTRIES[country]}.`);
+ await mutate();
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : "Failed to update country.";
+ toast.error(message);
+ }
+ };
+
const columns = useMemo(
() => [
{
@@ -405,6 +431,7 @@ export default function NetworkApplicationsPage() {
setDetailsSheetState((state) => ({ ...state, open }) as any);
}}
onReview={handleReviewPartner}
+ onUpdateCountry={handleUpdatePartnerCountry}
/>
)}
<div className="mb-4 flex flex-col gap-3">
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/program-categories-list.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/program-categories-list.tsx
index 8775f49a0f..0bd66ac1bf 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/program-categories-list.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/program-categories-list.tsx
@@ -4,14 +4,7 @@ import {
PROGRAM_CATEGORIES_MAP,
} from "@/lib/network/program-categories";
import { Category } from "@dub/prisma/client";
-import {
- Button,
- Checkbox,
- Modal,
- Tag,
- Tooltip,
- TruncatedList,
-} from "@dub/ui";
+import { Button, Checkbox, Modal, Tag, Tooltip, TruncatedList } from "@dub/ui";
import { cn } from "@dub/utils";
import {
Dispatch,
@@ -133,11 +126,17 @@ export function UpdateProgramCategoriesModal({
const hasChanges = useMemo(() => {
if (draftCategories.length !== selectedCategories.length) return true;
- return draftCategories.some((category) => !selectedCategories.includes(category));
+ return draftCategories.some(
+ (category) => !selectedCategories.includes(category),
+ );
}, [draftCategories, selectedCategories]);
return (
- <Modal showModal={showModal} setShowModal={setShowModal} className="sm:max-w-lg">
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="sm:max-w-lg"
+ >
<div className="border-b border-neutral-200 p-4 sm:p-6">
<h3 className="text-lg font-medium leading-none">Program categories</h3>
<p className="mt-1 text-sm text-neutral-500">{programName}</p>
@@ -163,38 +162,40 @@ export function UpdateProgramCategoriesModal({
</div>
) : (
filteredCategories.map(({ id, label, icon: Icon }) => {
- const isChecked = draftSet.has(id);
- const maxReached =
- !isChecked && draftCategories.length >= MAX_PROGRAM_CATEGORIES;
+ const isChecked = draftSet.has(id);
+ const maxReached =
+ !isChecked && draftCategories.length >= MAX_PROGRAM_CATEGORIES;
- return (
- <label
- key={id}
- className={cn(
- "flex cursor-pointer items-center justify-between rounded-lg border border-neutral-200 px-3 py-2.5",
- "transition-colors hover:bg-neutral-50",
- maxReached && "cursor-not-allowed opacity-60",
- )}
- >
- <div className="flex items-center gap-2">
- <Icon className="size-4 text-neutral-600" />
- <span className="text-sm font-medium text-neutral-800">{label}</span>
- </div>
- <Checkbox
- checked={isChecked}
- onCheckedChange={(checked) => {
- if (!checked) {
- setDraftCategories((prev) =>
- prev.filter((category) => category !== id),
- );
- return;
- }
- if (maxReached) return;
- setDraftCategories((prev) => [...prev, id]);
- }}
- />
- </label>
- );
+ return (
+ <label
+ key={id}
+ className={cn(
+ "flex cursor-pointer items-center justify-between rounded-lg border border-neutral-200 px-3 py-2.5",
+ "transition-colors hover:bg-neutral-50",
+ maxReached && "cursor-not-allowed opacity-60",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <Icon className="size-4 text-neutral-600" />
+ <span className="text-sm font-medium text-neutral-800">
+ {label}
+ </span>
+ </div>
+ <Checkbox
+ checked={isChecked}
+ onCheckedChange={(checked) => {
+ if (!checked) {
+ setDraftCategories((prev) =>
+ prev.filter((category) => category !== id),
+ );
+ return;
+ }
+ if (maxReached) return;
+ setDraftCategories((prev) => [...prev, id]);
+ }}
+ />
+ </label>
+ );
})
)}
</div>
diff --git a/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts b/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts
index a684386456..13ea4d123d 100644
--- a/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts
+++ b/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts
@@ -1,6 +1,11 @@
import { withAdmin } from "@/lib/auth";
+import { qstash } from "@/lib/cron";
+import { partnerProfileChangeHistoryLogSchema } from "@/lib/zod/schemas/partner-profile";
import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK, COUNTRIES } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
+import * as z from "zod/v4";
// GET /api/admin/partners/[partnerId]
export const GET = withAdmin(async ({ params }) => {
@@ -95,3 +100,71 @@ export const GET = withAdmin(async ({ params }) => {
payouts,
});
});
+
+const adminUpdatePartnerSchema = z.object({
+ country: z.enum(Object.keys(COUNTRIES) as [string, ...string[]]),
+});
+
+export const PATCH = withAdmin(async ({ params, req }) => {
+ const { partnerId } = params;
+ const { country } = adminUpdatePartnerSchema.parse(await req.json());
+
+ const partner = await prisma.partner.findUnique({
+ where: {
+ id: partnerId,
+ },
+ select: {
+ id: true,
+ country: true,
+ changeHistoryLog: true,
+ veriffSessionId: true,
+ },
+ });
+
+ if (!partner) {
+ return new Response("Partner not found.", { status: 404 });
+ }
+
+ if (partner.country === country) {
+ return new Response("Partner is already in this country.", { status: 400 });
+ }
+
+ const partnerChangeHistoryLog = partner.changeHistoryLog
+ ? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)
+ : [];
+
+ partnerChangeHistoryLog.push({
+ field: "country",
+ from: partner.country,
+ to: country,
+ changedAt: new Date(),
+ });
+
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ country,
+ stripeConnectId: null, // reset stripe connect account
+ payoutsEnabledAt: null,
+ defaultPayoutMethod: null,
+ payoutMethodHash: null,
+ changeHistoryLog: partnerChangeHistoryLog,
+ },
+ });
+
+ // if there was an existing veriff session, trigger a country change verification
+ if (partner.veriffSessionId) {
+ waitUntil(
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/verify-country-change`,
+ body: {
+ partnerId: partner.id,
+ },
+ }),
+ );
+ }
+
+ return NextResponse.json({ success: true });
+});
diff --git a/apps/web/app/(ee)/api/cron/commissions/referrals/create/route.ts b/apps/web/app/(ee)/api/cron/commissions/referrals/create/route.ts
new file mode 100644
index 0000000000..1f24ae8724
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/commissions/referrals/create/route.ts
@@ -0,0 +1,26 @@
+import { withCron } from "@/lib/cron/with-cron";
+import { createReferralCommission } from "@/lib/partner-referrals/create-referral-commission";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../../utils";
+
+export const dynamic = "force-dynamic";
+
+const inputSchema = z.union([
+ z.object({ sourceCommissionId: z.string() }),
+ z.object({ programId: z.string(), partnerId: z.string() }),
+]);
+
+// POST /api/cron/commissions/referrals/create
+export const POST = withCron(async ({ rawBody }) => {
+ const inputParsed = inputSchema.parse(JSON.parse(rawBody));
+
+ const referralCommission = await createReferralCommission(inputParsed);
+
+ if (referralCommission === null) {
+ return logAndRespond("Referral commission creation skipped.");
+ }
+
+ return logAndRespond(
+ `Referral commission ${referralCommission.id} created successfully.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/cron/commissions/referrals/queue/route.ts b/apps/web/app/(ee)/api/cron/commissions/referrals/queue/route.ts
new file mode 100644
index 0000000000..fa104f1d9d
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/commissions/referrals/queue/route.ts
@@ -0,0 +1,161 @@
+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
+import { withCron } from "@/lib/cron/with-cron";
+import { createNetworkReferralCommission } from "@/lib/partner-referrals/create-network-referral-commission";
+import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { prisma } from "@dub/prisma";
+import { CommissionType } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK, NETWORK_PROGRAM_ID } from "@dub/utils";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../../utils";
+
+export const dynamic = "force-dynamic";
+
+const inputSchema = z.object({
+ payoutId: z.string(),
+});
+
+// POST /api/cron/commissions/referrals/queue
+export const POST = withCron(async ({ rawBody }) => {
+ const { payoutId } = inputSchema.parse(JSON.parse(rawBody));
+
+ const payout = await prisma.payout.findUnique({
+ where: {
+ id: payoutId,
+ },
+ select: {
+ id: true,
+ status: true,
+ programId: true,
+ amount: true,
+ partner: {
+ select: {
+ id: true,
+ referredByPartnerId: true,
+ },
+ },
+ programEnrollment: {
+ select: {
+ applicationEvent: {
+ select: {
+ referredByPartnerId: true,
+ },
+ },
+ },
+ },
+ commissions: {
+ where: {
+ type: CommissionType.sale,
+ },
+ select: {
+ id: true,
+ },
+ },
+ invoice: {
+ select: {
+ amount: true,
+ fee: true,
+ },
+ },
+ },
+ });
+
+ if (!payout) {
+ return logAndRespond(`Payout ${payoutId} not found.`);
+ }
+
+ if (payout.programId === NETWORK_PROGRAM_ID) {
+ return logAndRespond(
+ `Payout ${payoutId} is from Network program. Skipping...`,
+ );
+ }
+
+ if (!["sent", "completed"].includes(payout.status)) {
+ return logAndRespond(
+ `Payout ${payoutId} is not in a valid status to create referrals.`,
+ );
+ }
+
+ const { programId, partner, programEnrollment, commissions } = payout;
+
+ // Check the program level referral reward
+ const referredByPartnerId =
+ programEnrollment?.applicationEvent?.referredByPartnerId;
+
+ if (referredByPartnerId) {
+ const referrerEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ programId,
+ partnerId: referredByPartnerId,
+ },
+ },
+ select: {
+ partnerId: true,
+ referralReward: true,
+ },
+ });
+
+ if (!referrerEnrollment) {
+ return logAndRespond(
+ `Referrer partner ${referredByPartnerId} is not enrolled in program ${programId}.`,
+ );
+ }
+
+ const { referralReward } = referrerEnrollment;
+
+ if (referralReward) {
+ const { trigger } = referralRewardConfigSchema.parse(
+ referralReward.config,
+ );
+
+ if (trigger === "commissionThreshold") {
+ await enqueueBatchJobs([
+ {
+ queueName: "create-referral-commissions",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/create`,
+ deduplicationId: `create-referral-commissions-${payout.id}`,
+ body: {
+ programId,
+ partnerId: partner.id,
+ },
+ },
+ ]);
+
+ return logAndRespond(`Enqueued referral-eligible payout ${payout.id}.`);
+ }
+
+ await enqueueBatchJobs(
+ commissions.map((commission) => ({
+ queueName: "create-referral-commissions",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/create`,
+ deduplicationId: `create-referral-commissions-${commission.id}`,
+ body: {
+ sourceCommissionId: commission.id,
+ },
+ })),
+ );
+
+ return logAndRespond(
+ `Enqueued ${commissions.length} referral-eligible commissions for payout ${payout.id}.`,
+ );
+ }
+ }
+
+ // Fallback to network level bonus
+ if (partner.referredByPartnerId) {
+ const commission = await createNetworkReferralCommission({
+ partner,
+ payout,
+ });
+
+ if (commission) {
+ return logAndRespond(
+ `Created network referral commission for payout ${payout.id}.`,
+ );
+ }
+ }
+
+ return logAndRespond(
+ `No referral commission created for payout ${payout.id}.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts b/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts
index 85a9183ff6..33c9dbe838 100644
--- a/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts
+++ b/apps/web/app/(ee)/api/cron/partners/auto-reject/route.ts
@@ -89,6 +89,7 @@ export const POST = withCron(async ({ rawBody }) => {
clickRewardId: null,
leadRewardId: null,
saleRewardId: null,
+ referralRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts b/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts
index 7386733071..7dc768e477 100644
--- a/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts
@@ -89,7 +89,10 @@ async function handler(req: Request) {
? {
OR: [
{
- type: "custom", // includes manual commissions + clawbacks
+ type: {
+ // includes manual + referral commissions + clawbacks
+ in: ["custom", "referral"],
+ },
},
{
createdAt: {
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts
index f1683e3cc8..041749c5ca 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts
@@ -1,9 +1,11 @@
+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
import { queueBatchEmail } from "@/lib/email/queue-batch-email";
import { createPayPalBatchPayout } from "@/lib/paypal/create-batch-payout";
import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
import { prisma } from "@dub/prisma";
import { Invoice } from "@dub/prisma/client";
-import { currencyFormatter } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, currencyFormatter } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
export async function sendPaypalPayouts(invoice: Pick<Invoice, "id">) {
const payouts = await prisma.payout.findMany({
@@ -62,17 +64,31 @@ export async function sendPaypalPayouts(invoice: Pick<Invoice, "id">) {
console.log(`Updated ${updatedPayouts.count} payouts to "sent" status`);
- await queueBatchEmail<typeof PartnerPayoutProcessed>(
- payouts.map((payout) => ({
- variant: "notifications",
- to: payout.partner.email!,
- subject: `You've received a ${currencyFormatter(payout.amount)} payout from ${payout.program.name}`,
- templateName: "PartnerPayoutProcessed",
- templateProps: {
- email: payout.partner.email!,
- program: payout.program,
- payout,
- },
- })),
+ waitUntil(
+ Promise.allSettled([
+ queueBatchEmail<typeof PartnerPayoutProcessed>(
+ payouts.map((payout) => ({
+ variant: "notifications",
+ to: payout.partner.email!,
+ subject: `You've received a ${currencyFormatter(payout.amount)} payout from ${payout.program.name}`,
+ templateName: "PartnerPayoutProcessed",
+ templateProps: {
+ email: payout.partner.email!,
+ program: payout.program,
+ payout,
+ },
+ })),
+ ),
+
+ enqueueBatchJobs(
+ payouts.map((payout) => ({
+ queueName: "create-referral-commissions",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/queue`,
+ body: {
+ payoutId: payout.id,
+ },
+ })),
+ ),
+ ]),
);
}
diff --git a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
index 8763d8f55f..2f078aa7af 100644
--- a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
+++ b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
@@ -162,6 +162,7 @@ export const PATCH = withWorkspace(
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
},
}),
@@ -341,6 +342,7 @@ export const DELETE = withWorkspace(
group.clickRewardId,
group.leadRewardId,
group.saleRewardId,
+ group.referralRewardId,
].filter(Boolean) as string[];
if (groupRewardIds.length > 0) {
diff --git a/apps/web/app/(ee)/api/groups/route.ts b/apps/web/app/(ee)/api/groups/route.ts
index 0bd41ae901..069fed13ec 100644
--- a/apps/web/app/(ee)/api/groups/route.ts
+++ b/apps/web/app/(ee)/api/groups/route.ts
@@ -153,6 +153,7 @@ export const POST = withWorkspace(
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
},
});
diff --git a/apps/web/app/(ee)/api/network/programs/route.ts b/apps/web/app/(ee)/api/network/programs/route.ts
index fe80d478b8..0a771b6777 100644
--- a/apps/web/app/(ee)/api/network/programs/route.ts
+++ b/apps/web/app/(ee)/api/network/programs/route.ts
@@ -89,6 +89,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
},
},
diff --git a/apps/web/app/(ee)/api/partner-profile/messages/count/route.ts b/apps/web/app/(ee)/api/partner-profile/messages/count/route.ts
index c1d422742b..fc50204a57 100644
--- a/apps/web/app/(ee)/api/partner-profile/messages/count/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/messages/count/route.ts
@@ -1,6 +1,7 @@
import { withPartnerProfile } from "@/lib/auth/partner";
import { countMessagesQuerySchema } from "@/lib/zod/schemas/messages";
import { prisma } from "@dub/prisma";
+import { NETWORK_PROGRAM_ID } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/partner-profile/messages/count - count messages for a partner
@@ -10,6 +11,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
const count = await prisma.message.count({
where: {
partnerId: partner.id,
+ programId: { not: NETWORK_PROGRAM_ID },
...(unread !== undefined && {
// Only count messages from the program
senderPartnerId: null,
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/count/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/count/route.ts
new file mode 100644
index 0000000000..ab00ffa4c6
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/count/route.ts
@@ -0,0 +1,80 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { getReferredPartnersCountQuerySchema } from "@/lib/partner-referrals/schemas";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/programs/:programId/referrals/count
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId } = params;
+ const { country, status, groupBy } =
+ getReferredPartnersCountQuerySchema.parse(searchParams);
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId,
+ include: {},
+ });
+
+ if (!programEnrollment.referralRewardId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Referral rewards are not enabled for the partner's group.",
+ });
+ }
+
+ const baseWhere: Prisma.ProgramEnrollmentWhereInput = {
+ programId: programEnrollment.programId,
+ applicationEvent: {
+ referredByPartnerId: partner.id,
+ },
+ ...(country &&
+ groupBy !== "country" && {
+ partner: { country },
+ }),
+ ...(status &&
+ groupBy !== "status" && {
+ status,
+ }),
+ };
+
+ if (groupBy === "status") {
+ const data = await prisma.programEnrollment.groupBy({
+ by: ["status"],
+ where: baseWhere,
+ _count: true,
+ });
+
+ return NextResponse.json(data);
+ }
+
+ if (groupBy === "country") {
+ const data = await prisma.partner.groupBy({
+ by: ["country"],
+ where: {
+ country: { not: null },
+ programs: {
+ some: baseWhere,
+ },
+ },
+ _count: true,
+ orderBy: {
+ _count: {
+ country: "desc",
+ },
+ },
+ });
+
+ return NextResponse.json(data);
+ }
+
+ const count = await prisma.programEnrollment.count({
+ where: baseWhere,
+ });
+
+ return NextResponse.json(count);
+ },
+);
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts
new file mode 100644
index 0000000000..dea9e0b173
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/referrals/route.ts
@@ -0,0 +1,107 @@
+import { DubApiError } from "@/lib/api/errors";
+import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ getReferredPartnersQuerySchema,
+ referredPartnerSchema,
+} from "@/lib/partner-referrals/schemas";
+import { prisma } from "@dub/prisma";
+import { CommissionType } from "@dub/prisma/client";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+// GET /api/partner-profile/programs/:programId/referrals
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId } = params;
+ const {
+ country,
+ status,
+ page = 1,
+ pageSize,
+ } = getReferredPartnersQuerySchema.parse(searchParams);
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId,
+ include: {},
+ });
+
+ if (!programEnrollment.referralRewardId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Referral rewards are not enabled for the partner's group.",
+ });
+ }
+
+ const enrollments = await prisma.programEnrollment.findMany({
+ where: {
+ programId: programEnrollment.programId,
+ applicationEvent: {
+ referredByPartnerId: partner.id,
+ },
+ ...(status && { status }),
+ ...(country && {
+ partner: { country },
+ }),
+ },
+ include: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ email: true,
+ country: true,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ });
+
+ const commissionsMap = new Map<string, number>();
+
+ if (enrollments.length > 0) {
+ const commissions = await prisma.commission.groupBy({
+ by: ["sourcePartnerId"],
+ where: {
+ programId: programEnrollment.programId,
+ partnerId: partner.id,
+ type: CommissionType.referral,
+ sourcePartnerId: {
+ in: enrollments.map((e) => e.partner.id),
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ });
+
+ for (const commission of commissions) {
+ if (commission.sourcePartnerId) {
+ commissionsMap.set(
+ commission.sourcePartnerId,
+ commission._sum.earnings ?? 0,
+ );
+ }
+ }
+ }
+
+ const result = enrollments.map((enrollment) => ({
+ id: enrollment.partner.id,
+ email: obfuscateCustomerEmail(enrollment.partner.email ?? ""),
+ country: enrollment.partner.country,
+ programEnrollment: {
+ ...enrollment,
+ earnings: commissionsMap.get(enrollment.partner.id) ?? 0,
+ },
+ }));
+
+ return NextResponse.json(z.array(referredPartnerSchema).parse(result));
+ },
+);
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
index c3e1d9c479..596bfeb9b9 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/route.ts
@@ -16,6 +16,7 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
partnerGroup: true,
application: {
@@ -32,6 +33,7 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
programEnrollment.clickReward,
programEnrollment.leadReward,
programEnrollment.saleReward,
+ programEnrollment.referralReward,
].filter((r): r is Reward => r !== null);
return NextResponse.json(
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/count/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/count/route.ts
index 7a1183b490..7ce9124154 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/count/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/count/route.ts
@@ -1,6 +1,7 @@
import { withPartnerProfile } from "@/lib/auth/partner";
import { partnerProfileProgramsCountQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { prisma } from "@dub/prisma";
+import { NETWORK_PROGRAM_ID } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/partner-profile/programs/count - count program enrollments for a given partnerId
@@ -10,6 +11,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
const count = await prisma.programEnrollment.count({
where: {
partnerId: partner.id,
+ programId: { not: NETWORK_PROGRAM_ID },
...(status && { status }),
},
});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
index e2625420ac..91adef186a 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
@@ -3,6 +3,7 @@ import { partnerProfileProgramsQuerySchema } from "@/lib/zod/schemas/partner-pro
import { ProgramEnrollmentSchema } from "@/lib/zod/schemas/programs";
import { prisma } from "@dub/prisma";
import { Reward } from "@dub/prisma/client";
+import { NETWORK_PROGRAM_ID } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -14,6 +15,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
partnerId: partner.id,
+ programId: { not: NETWORK_PROGRAM_ID },
...(status && { status }),
program: {
deactivatedAt: null,
@@ -46,6 +48,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
}),
},
diff --git a/apps/web/app/(ee)/api/partner-profile/referrals/route.ts b/apps/web/app/(ee)/api/partner-profile/referrals/route.ts
new file mode 100644
index 0000000000..8cfd514285
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/referrals/route.ts
@@ -0,0 +1,154 @@
+import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
+import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { triggerWorkflows } from "@/lib/cron/qstash-workflow";
+import {
+ getNetworkReferralsQuerySchema,
+ networkReferralSchema,
+} from "@/lib/partner-referrals/schemas";
+import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { prisma } from "@dub/prisma";
+import { CommissionType } from "@dub/prisma/client";
+import {
+ NETWORK_PROGRAM_DEFAULT_GROUP_ID,
+ NETWORK_PROGRAM_DEFAULT_SALE_REWARD_ID,
+ NETWORK_PROGRAM_ID,
+ NETWORK_USER_ID,
+} from "@dub/utils/src/constants/main";
+import { waitUntil } from "@vercel/functions";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+// GET /api/partner-profile/referrals
+export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
+ if (!["approved", "trusted"].includes(partner.networkStatus)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "You must be approved in the Dub Partner Network to view referrals.",
+ });
+ }
+
+ waitUntil(
+ prisma.programEnrollment
+ .upsert({
+ where: {
+ partnerId_programId: {
+ partnerId: partner.id,
+ programId: NETWORK_PROGRAM_ID,
+ },
+ },
+ create: {
+ id: createId({ prefix: "pge_" }),
+ partnerId: partner.id,
+ programId: NETWORK_PROGRAM_ID,
+ status: "approved",
+ groupId: NETWORK_PROGRAM_DEFAULT_GROUP_ID,
+ saleRewardId: NETWORK_PROGRAM_DEFAULT_SALE_REWARD_ID,
+ },
+ update: {},
+ })
+ .then(async (res) => {
+ console.log("Program enrollment upserted:", res.id);
+ // if program enrollment is created in the last 1 min, most likely it's a new partner
+ if (res.createdAt > new Date(Date.now() - 1 * 60 * 1000)) {
+ console.log(
+ "Program enrollment created in the last 1 min, most likely it's a new partner",
+ );
+ await triggerWorkflows({
+ workflowId: "partner-approved",
+ body: {
+ programId: NETWORK_PROGRAM_ID,
+ partnerId: partner.id,
+ userId: NETWORK_USER_ID,
+ },
+ });
+ }
+ }),
+ );
+
+ const { page = 1, pageSize } =
+ getNetworkReferralsQuerySchema.parse(searchParams);
+
+ const referredPartners = await prisma.partner.findMany({
+ where: {
+ referredByPartnerId: partner.id,
+ },
+ select: {
+ id: true,
+ email: true,
+ country: true,
+ createdAt: true,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ });
+
+ const commissionsMap = new Map<string, number>();
+ const activeProgramsCountMap = new Map<string, number>();
+
+ if (referredPartners.length > 0) {
+ const [commissions, programEnrollments] = await Promise.all([
+ prisma.commission.groupBy({
+ by: ["sourcePartnerId"],
+ where: {
+ partnerId: partner.id,
+ programId: NETWORK_PROGRAM_ID,
+ type: CommissionType.referral,
+ sourcePartnerId: {
+ in: referredPartners.map((p) => p.id),
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+
+ prisma.programEnrollment.groupBy({
+ by: ["partnerId"],
+ where: {
+ partnerId: {
+ in: referredPartners.map((p) => p.id),
+ },
+ programId: {
+ not: NETWORK_PROGRAM_ID,
+ },
+ status: {
+ in: ACTIVE_ENROLLMENT_STATUSES,
+ },
+ },
+ _count: true,
+ }),
+ ]);
+
+ for (const commission of commissions) {
+ if (commission.sourcePartnerId) {
+ commissionsMap.set(
+ commission.sourcePartnerId,
+ commission._sum.earnings ?? 0,
+ );
+ }
+ }
+
+ for (const count of programEnrollments) {
+ if (count.partnerId) {
+ activeProgramsCountMap.set(count.partnerId, count._count);
+ }
+ }
+ }
+
+ const result = referredPartners.map((p) => ({
+ id: p.id,
+ email: obfuscateCustomerEmail(p.email ?? ""),
+ country: p.country,
+ createdAt: p.createdAt,
+ totalEarnings: commissionsMap.get(p.id) ?? 0,
+ activeProgramsCount: activeProgramsCountMap.get(p.id) ?? 0,
+ }));
+
+ return NextResponse.json(z.array(networkReferralSchema).parse(result));
+});
diff --git a/apps/web/app/(ee)/api/partner-profile/referrals/stats/route.ts b/apps/web/app/(ee)/api/partner-profile/referrals/stats/route.ts
new file mode 100644
index 0000000000..2807db06d1
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/referrals/stats/route.ts
@@ -0,0 +1,44 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { networkReferralsStatsSchema } from "@/lib/partner-referrals/schemas";
+import { prisma } from "@dub/prisma";
+import { CommissionType } from "@dub/prisma/client";
+import { NETWORK_PROGRAM_ID } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/referrals/stats
+export const GET = withPartnerProfile(async ({ partner }) => {
+ if (!["approved", "trusted"].includes(partner.networkStatus)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "You must be approved in the Dub Partner Network to view referrals.",
+ });
+ }
+
+ const [count, earningsAggregate] = await Promise.all([
+ prisma.partner.count({
+ where: {
+ referredByPartnerId: partner.id,
+ },
+ }),
+
+ prisma.commission.aggregate({
+ where: {
+ partnerId: partner.id,
+ programId: NETWORK_PROGRAM_ID,
+ type: CommissionType.referral,
+ },
+ _sum: {
+ earnings: true,
+ },
+ }),
+ ]);
+
+ const response = networkReferralsStatsSchema.parse({
+ count,
+ totalEarnings: earningsAggregate._sum.earnings ?? 0,
+ });
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/(ee)/api/partner-profile/referrals/timeseries/route.ts b/apps/web/app/(ee)/api/partner-profile/referrals/timeseries/route.ts
new file mode 100644
index 0000000000..9d561963bc
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/referrals/timeseries/route.ts
@@ -0,0 +1,108 @@
+import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+import { DubApiError } from "@/lib/api/errors";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { networkReferralsTimeseriesSchema } from "@/lib/partner-referrals/schemas";
+import { NetworkReferralsTimeseries } from "@/lib/partner-referrals/types";
+import { sqlGranularityMap } from "@/lib/planetscale/granularity";
+import { prisma } from "@dub/prisma";
+import { CommissionType, Prisma } from "@dub/prisma/client";
+import { NETWORK_PROGRAM_ID } from "@dub/utils";
+import { format } from "date-fns";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const querySchema = z.object({
+ interval: z.enum(DATE_RANGE_INTERVAL_PRESETS).optional().default("1y"),
+ timezone: z.string().optional(),
+});
+
+// GET /api/partner-profile/referrals/timeseries
+export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
+ if (!["approved", "trusted"].includes(partner.networkStatus)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "You must be approved in the Dub Partner Network to view referrals.",
+ });
+ }
+
+ const { interval, timezone } = querySchema.parse(searchParams);
+
+ const { startDate, endDate, granularity } = getStartEndDates({
+ interval,
+ timezone,
+ });
+
+ const { dateFormat, dateIncrement, startFunction, formatString } =
+ sqlGranularityMap[granularity];
+
+ const [partnersResult, earningsResult] = await Promise.all([
+ prisma.$queryRaw<{ start: string; partners: number }[]>(
+ Prisma.sql`
+ SELECT
+ DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
+ COUNT(*) AS partners
+ FROM Partner
+ WHERE
+ referredByPartnerId = ${partner.id}
+ AND createdAt >= ${startDate}
+ AND createdAt < ${endDate}
+ GROUP BY start
+ ORDER BY start ASC
+ `,
+ ),
+
+ prisma.$queryRaw<{ start: string; earnings: number }[]>(
+ Prisma.sql`
+ SELECT
+ DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
+ SUM(earnings) AS earnings
+ FROM Commission
+ WHERE
+ partnerId = ${partner.id}
+ AND programId = ${NETWORK_PROGRAM_ID}
+ AND type = ${CommissionType.referral}
+ AND createdAt >= ${startDate}
+ AND createdAt < ${endDate}
+ GROUP BY start
+ ORDER BY start ASC
+ `,
+ ),
+ ]);
+
+ const partnersLookup = partnersResult.reduce(
+ (acc, item) => {
+ acc[item.start] = Number(item.partners);
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+
+ const earningsLookup = earningsResult.reduce(
+ (acc, item) => {
+ acc[item.start] = Number(item.earnings);
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+
+ const timeseries: NetworkReferralsTimeseries[] = [];
+ let currentDate = startFunction(startDate);
+
+ while (currentDate < endDate) {
+ const periodKey = format(currentDate, formatString);
+
+ timeseries.push({
+ start: currentDate.toISOString(),
+ partners: partnersLookup[periodKey] ?? 0,
+ earnings: earningsLookup[periodKey] ?? 0,
+ });
+
+ currentDate = dateIncrement(currentDate);
+ }
+
+ return NextResponse.json(
+ z.array(networkReferralsTimeseriesSchema).parse(timeseries),
+ );
+});
diff --git a/apps/web/app/(ee)/api/partners/[partnerId]/referral/route.ts b/apps/web/app/(ee)/api/partners/[partnerId]/referral/route.ts
new file mode 100644
index 0000000000..eac773ef2d
--- /dev/null
+++ b/apps/web/app/(ee)/api/partners/[partnerId]/referral/route.ts
@@ -0,0 +1,94 @@
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import { partnerReferralSchema } from "@/lib/partner-referrals/schemas";
+import { prisma } from "@dub/prisma";
+import { toCentsNumber } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// GET /api/partners/:partnerId/referral – referral snapshot for a partner in the program.
+export const GET = withWorkspace(
+ async ({ workspace, params }) => {
+ const { partnerId } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId,
+ programId,
+ include: {
+ applicationEvent: {
+ select: {
+ referredByPartnerId: true,
+ },
+ },
+ },
+ });
+
+ const referredByPartnerId =
+ programEnrollment.applicationEvent?.referredByPartnerId;
+
+ const [referredByProgramEnrollment, programEnrollmentStats] =
+ await Promise.all([
+ referredByPartnerId
+ ? prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId: referredByPartnerId,
+ programId,
+ },
+ },
+ select: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ },
+ },
+ })
+ : Promise.resolve(null),
+
+ prisma.programEnrollment.aggregate({
+ where: {
+ programId,
+ applicationEvent: {
+ referredByPartnerId: partnerId,
+ },
+ },
+ _sum: {
+ totalConversions: true,
+ totalSaleAmount: true,
+ },
+ _count: {
+ _all: true,
+ },
+ }),
+ ]);
+
+ return NextResponse.json(
+ partnerReferralSchema.parse({
+ referredBy: referredByProgramEnrollment?.partner ?? null,
+ stats: {
+ totalPartners: programEnrollmentStats._count._all,
+ totalConversions: toCentsNumber(
+ programEnrollmentStats._sum.totalConversions,
+ ),
+ totalSaleAmount: toCentsNumber(
+ programEnrollmentStats._sum.totalSaleAmount,
+ ),
+ },
+ }),
+ );
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/(ee)/api/track/application/route.ts b/apps/web/app/(ee)/api/track/application/route.ts
index db7f5e5db7..a45f3f7789 100644
--- a/apps/web/app/(ee)/api/track/application/route.ts
+++ b/apps/web/app/(ee)/api/track/application/route.ts
@@ -1,6 +1,7 @@
import { COMMON_CORS_HEADERS } from "@/lib/api/cors";
import { createId } from "@/lib/api/create-id";
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { parseRequestBody } from "@/lib/api/utils";
import { getIP } from "@/lib/api/utils/get-ip";
import {
@@ -12,6 +13,10 @@ import { getSession } from "@/lib/auth";
import { withAxiom } from "@/lib/axiom/server";
import { detectBot } from "@/lib/middleware/utils/detect-bot";
import { getIdentityHash } from "@/lib/middleware/utils/get-identity-hash";
+import {
+ recordClickZod,
+ recordClickZodSchema,
+} from "@/lib/tinybird/record-click-zod";
import { ratelimit } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
import { Partner, Program } from "@dub/prisma/client";
@@ -22,8 +27,12 @@ import {
getSearchParams,
LOCALHOST_GEO_DATA,
LOCALHOST_IP,
+ nanoid,
+ NETWORK_PROGRAM_ID,
+ NETWORK_PROGRAM_SLUG,
+ NETWORK_WORKSPACE_ID,
} from "@dub/utils";
-import { geolocation, ipAddress } from "@vercel/functions";
+import { geolocation, ipAddress, waitUntil } from "@vercel/functions";
import { cookies } from "next/headers";
import { NextRequest, NextResponse, userAgent } from "next/server";
@@ -63,14 +72,22 @@ export const POST = withAxiom(async (req) => {
});
}
- const program = await prisma.program.findUnique({
- where: {
- slug: programSlug.toLowerCase(),
- },
- select: {
- id: true,
- },
- });
+ let program: Pick<Program, "id"> | null = null;
+
+ if (programSlug === NETWORK_PROGRAM_SLUG) {
+ program = {
+ id: NETWORK_PROGRAM_ID,
+ };
+ } else {
+ program = await prisma.program.findUnique({
+ where: {
+ slug: programSlug.toLowerCase(),
+ },
+ select: {
+ id: true,
+ },
+ });
+ }
if (!program) {
throw new DubApiError({
@@ -158,7 +175,7 @@ async function trackVisitEvent({
}
const session = await getSession();
- const requestContext = await getRequestContext(req);
+ const requestContext = await getRequestContext(req, { referrer, url });
try {
const programApplicationEvent = await prisma.programApplicationEvent.create(
@@ -175,11 +192,7 @@ async function trackVisitEvent({
partnerId: session?.user?.defaultPartnerId,
visitedAt: new Date(),
country: requestContext.country,
- metadata: {
- ...requestContext,
- url,
- referrer,
- },
+ metadata: requestContext,
},
},
);
@@ -197,7 +210,65 @@ async function trackVisitEvent({
sameSite: "lax",
path: "/",
});
- } catch {}
+ } catch (e) {
+ console.error(`Error tracking "visit" event for program ${program.id}`, e);
+ }
+
+ // for network program application events, track the click event
+ if (program.id === NETWORK_PROGRAM_ID && referredByPartner) {
+ waitUntil(
+ (async () => {
+ const networkPartnerLink = await prisma.link.findFirst({
+ where: {
+ programId: NETWORK_PROGRAM_ID,
+ partnerId: referredByPartner.id,
+ },
+ });
+
+ if (!networkPartnerLink) {
+ console.log(
+ `No network partner link found for partner ${referredByPartner.id}, skipping...`,
+ );
+ return;
+ }
+
+ // add additional click event data to the request context
+ const generatedClickEvent = recordClickZodSchema.parse({
+ ...requestContext,
+ timestamp: new Date().toISOString(),
+ workspace_id: NETWORK_WORKSPACE_ID,
+ link_id: networkPartnerLink.id,
+ domain: networkPartnerLink.domain,
+ key: networkPartnerLink.key,
+ });
+
+ await recordClickZod(generatedClickEvent);
+ console.log(
+ `Tracked click event for network partner ${referredByPartner.id}`,
+ );
+
+ await prisma.link.update({
+ where: {
+ id: networkPartnerLink.id,
+ },
+ data: {
+ clicks: { increment: 1 },
+ lastClicked: new Date(),
+ },
+ });
+ console.log(
+ `Updated link ${networkPartnerLink.id} to ${networkPartnerLink.clicks + 1} clicks`,
+ );
+
+ await syncPartnerLinksStats({
+ partnerId: referredByPartner.id,
+ programId: NETWORK_PROGRAM_ID,
+ eventType: "click",
+ });
+ console.log(`Synced click stats for partner ${referredByPartner.id}`);
+ })(),
+ );
+ }
}
// Track the "start" event
@@ -240,10 +311,14 @@ async function trackStartEvent({
}
// Get the request context
-async function getRequestContext(req: NextRequest) {
+async function getRequestContext(
+ req: NextRequest,
+ { referrer, url }: { referrer: string | null | undefined; url: string },
+) {
const isVercel = process.env.VERCEL === "1";
- const identityHash = await getIdentityHash(req);
+ const click_id = nanoid(16);
+ const identity_hash = await getIdentityHash(req);
const ua = userAgent(req);
const ip = isVercel ? ipAddress(req) : LOCALHOST_IP;
@@ -260,7 +335,13 @@ async function getRequestContext(req: NextRequest) {
const isEuCountry = geo.country && EU_COUNTRY_CODES.includes(geo.country);
return {
- identityHash,
+ identity_hash,
+ click_id,
+ url,
+ ip:
+ typeof ip === "string" && ip.trim().length > 0 && !isEuCountry
+ ? ip
+ : undefined,
continent,
country: geo.country,
region,
@@ -279,10 +360,8 @@ async function getRequestContext(req: NextRequest) {
os_version: ua.os.version,
cpu_architecture: ua.cpu?.architecture,
ua: ua.ua,
- ip:
- typeof ip === "string" && ip.trim().length > 0 && !isEuCountry
- ? ip
- : undefined,
+ referer: referrer ? getDomainWithoutWWW(referrer) || "direct" : "direct",
+ referer_url: referrer || "direct",
};
}
@@ -291,6 +370,7 @@ async function getRequestContext(req: NextRequest) {
// - https://partners.dub.co/{programSlug}
// - https://partners.dub.co/programs/{programSlug}/apply
// - https://partners.dub.co/programs/marketplace/{programSlug}
+// - https://partners.dub.co/register (platform-level signup -> network program)
function identityProgramSlug(url: string) {
try {
const urlObj = new URL(url);
@@ -300,6 +380,11 @@ function identityProgramSlug(url: string) {
return { programSlug: null, isMarketplace: false };
}
+ // Platform-level /register page is associated with the network program
+ if (parts[0] === "register") {
+ return { programSlug: NETWORK_PROGRAM_SLUG, isMarketplace: false };
+ }
+
const isMarketplace = parts[0] === "programs" && parts[1] === "marketplace";
const programSlug = isMarketplace // e.g. https://partners.dub.co/programs/marketplace/acme
? parts[2]
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index d0e227d58c..6484442ad4 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -5,6 +5,7 @@ import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";
import { createWorkflowLogger } from "@/lib/cron/qstash-workflow-logger";
import { generateDiscountCodeForPartner } from "@/lib/discounts/generate-discount-code-for-partner";
+import { createReferralCommission } from "@/lib/partner-referrals/create-referral-commission";
import { polyfillSocialMediaFields } from "@/lib/social-utils";
import { PlanProps } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
@@ -13,6 +14,7 @@ import { ProgramPartnerLinkSchema } from "@/lib/zod/schemas/programs";
import { sendBatchEmail } from "@dub/email";
import PartnerApplicationApproved from "@dub/email/templates/partner-application-approved";
import { prisma } from "@dub/prisma";
+import { NETWORK_PROGRAM_ID } from "@dub/utils";
import { serve } from "@upstash/workflow/nextjs";
import * as z from "zod/v4";
@@ -120,6 +122,13 @@ export const { POST } = serve<Payload>(
}
}
+ if (partnerGroupDefaultLinks.length === 0) {
+ logger.error({
+ message: `Already created default links for partner ${partnerId}.`,
+ });
+ return;
+ }
+
// Find the workspace
const workspace = await prisma.project.findUniqueOrThrow({
where: {
@@ -167,6 +176,11 @@ export const { POST } = serve<Payload>(
return;
});
+ // for network program, only need to create default links
+ if (program.id === NETWORK_PROGRAM_ID) {
+ return;
+ }
+
// Step 2: Auto-provision discount code if enabled
await context.run("create-discount-codes", async () => {
logger.info({
@@ -349,6 +363,20 @@ export const { POST } = serve<Payload>(
},
});
});
+
+ // Step 7: Create referral commission if enabled
+ await context.run("create-referral-commission", async () => {
+ logger.info({
+ message:
+ "Started executing workflow step 'create-referral-commission'.",
+ data: input,
+ });
+
+ await createReferralCommission({
+ partnerId,
+ programId,
+ });
+ });
},
{
initialPayloadParser: (requestPayload) => {
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.ts
index af13c18059..92801681de 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
@@ -63,10 +63,11 @@ export const getReferralsEmbedData = async (token: string) => {
},
links: true,
partnerGroup: true,
- discount: true,
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
+ discount: true,
},
});
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.tsx
index 99dce0dcab..0dc11b23f1 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
@@ -524,7 +524,7 @@ function ReferralLinkDisplay({ onSelectTab }) {
</div>
{partnerLink && group.linkStructure === "query" && (
- <QueryLinkStructureHelpText link={selectedLink} />
+ <QueryLinkStructureHelpText link={selectedLink} className="mt-1.5" />
)}
</>
);
diff --git a/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/register/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/register/page-client.tsx
index 80d711355e..98dc05296e 100644
--- a/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/register/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/register/page-client.tsx
@@ -1,6 +1,7 @@
"use client";
import { emailSchema } from "@/lib/zod/schemas/auth";
+import { ApplicationAnalytics } from "@/ui/application-analytics";
import { AuthAlternativeBanner } from "@/ui/auth/auth-alternative-banner";
import {
RegisterProvider,
@@ -36,6 +37,7 @@ export default function RegisterPageClient({
}
lockEmail={searchEmailResult.success || lockEmail}
>
+ <ApplicationAnalytics />
<RegisterFlow program={program} />
</RegisterProvider>
);
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.tsx
index ca7352501f..212412403c 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
@@ -9,7 +9,10 @@ import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { PartnerEarningsResponse, PartnerPayoutResponse } from "@/lib/types";
import { CustomerAvatar } from "@/ui/customers/customer-avatar";
import { CommissionTypeIcon } from "@/ui/partners/comission-type-icon";
-import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
+import {
+ CommissionTypeBadge,
+ getCommissionTypeLabel,
+} from "@/ui/partners/commission-type-badge";
import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
import { ConditionalLink } from "@/ui/shared/conditional-link";
import { X } from "@/ui/shared/icons";
@@ -36,7 +39,6 @@ import {
formatDateTime,
formatDateTimeSmart,
OG_AVATAR_URL,
- pluralize,
} from "@dub/utils";
import { formatPeriod } from "@dub/utils/src/functions/datetime";
import { addBusinessDays, addMinutes } from "date-fns";
@@ -285,11 +287,7 @@ function PayoutDetailsSheetContent({ payout }: PayoutDetailsSheetProps) {
<div className="flex flex-col">
<span className="text-sm text-neutral-700">
- {row.original.type === "click"
- ? `${row.original.quantity} ${pluralize("click", row.original.quantity)}`
- : row.original.customer
- ? row.original.customer.email || row.original.customer.name
- : "Custom commission"}
+ {getCommissionTypeLabel(row.original)}
</span>
<span className="text-xs text-neutral-500">
{formatDateTime(row.original.createdAt)}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
index 4946b35869..384594e547 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
@@ -4,13 +4,11 @@ import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions
import { mutatePrefix } from "@/lib/swr/mutate";
import usePartnerPayoutsCount from "@/lib/swr/use-partner-payouts-count";
import { PartnerProps } from "@/lib/types";
-import { useConfirmModal } from "@/ui/modals/confirm-modal";
import { CountryCombobox } from "@/ui/partners/country-combobox";
import {
PartnerPlatformsForm,
usePartnerPlatformsForm,
} from "@/ui/partners/partner-platforms-form";
-import { useCountryChangeWarningModal } from "@/ui/partners/use-country-change-warning-modal";
import { CustomToast } from "@/ui/shared/custom-toast";
import { AlertCircleFill } from "@/ui/shared/icons";
import { PartnerProfileType } from "@dub/prisma/client";
@@ -25,14 +23,7 @@ import {
import { OG_AVATAR_URL, cn } from "@dub/utils";
import { AnimatePresence, LayoutGroup, motion } from "motion/react";
import { useAction } from "next-safe-action/hooks";
-import {
- Dispatch,
- RefObject,
- SetStateAction,
- useEffect,
- useRef,
- useState,
-} from "react";
+import { Dispatch, RefObject, SetStateAction, useEffect, useRef } from "react";
import {
Controller,
FormProvider,
@@ -79,27 +70,12 @@ export function ProfileDetailsForm({
});
const partnerPlatformsForm = usePartnerPlatformsForm({ partner });
- const {
- setShowConfirmModal: setShowStripeConfirmModal,
- confirmModal: stripeConfirmModal,
- } = useConfirmModal({
- title: "Confirm profile update",
- description:
- "Updating your country or profile type will reset your Stripe account, which will require you to restart the payout connection process. Are you sure you want to continue?",
- confirmText: "Continue",
- onConfirm: () => {
- basicInfoFormRef.current?.requestSubmit();
- partnerPlatformsFormRef.current?.requestSubmit();
- },
- });
-
const { payoutsCount } = usePartnerPayoutsCount({
status: "completed",
});
return (
<div className="border-border-subtle divide-border-subtle flex flex-col divide-y rounded-lg border">
- {stripeConfirmModal}
<div className="px-6 py-8">
<h3 className="text-content-emphasis text-lg font-semibold leading-7">
Profile details
@@ -119,11 +95,22 @@ export function ProfileDetailsForm({
partner={partner}
formRef={basicInfoFormRef}
disabled={disabled}
+ onSubmitAction={() => basicInfoFormRef.current?.requestSubmit()}
/>
</FormProvider>
</SettingsRow>
- {(payoutsCount?.[0]?.amount ?? 0) > 10000 && (
+ <div className="flex items-center justify-end bg-neutral-50 px-6 py-4">
+ <Button
+ text="Save changes"
+ className="h-8 w-fit px-2.5"
+ disabled={disabled}
+ loading={basicInfoForm.formState.isSubmitting}
+ onClick={() => basicInfoFormRef.current?.requestSubmit()}
+ />
+ </div>
+
+ {["approved", "trusted"].includes(partner?.networkStatus ?? "") && (
<SettingsRow
id="identity-verification"
heading="Identity verification"
@@ -149,29 +136,15 @@ export function ProfileDetailsForm({
/>
</SettingsRow>
- <div className="flex items-center justify-end rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-6 py-4">
+ <div className="flex items-center justify-end rounded-b-lg bg-neutral-50 px-6 py-4">
<Button
text="Save changes"
className="h-8 w-fit px-2.5"
disabled={disabled}
- loading={
- basicInfoForm.formState.isSubmitting ||
- partnerPlatformsForm.formState.isSubmitting
- }
+ loading={partnerPlatformsForm.formState.isSubmitting}
onClick={() => {
if (disabled) return;
-
- if (
- partner?.stripeConnectId &&
- (basicInfoForm.formState.dirtyFields.country ||
- basicInfoForm.formState.dirtyFields.profileType ||
- basicInfoForm.formState.dirtyFields.companyName)
- ) {
- setShowStripeConfirmModal(true);
- } else {
- basicInfoFormRef.current?.requestSubmit();
- partnerPlatformsFormRef.current?.requestSubmit();
- }
+ partnerPlatformsFormRef.current?.requestSubmit();
}}
/>
</div>
@@ -183,10 +156,12 @@ function BasicInfoForm({
partner,
formRef,
disabled,
+ onSubmitAction,
}: {
partner?: PartnerProps;
formRef: RefObject<HTMLFormElement | null>;
disabled: boolean;
+ onSubmitAction: () => void;
}) {
const {
register,
@@ -207,8 +182,6 @@ function BasicInfoForm({
}, [isSubmitSuccessful, reset, getValues]);
const { profileType } = watch();
- const [isCountryComboboxOpen, setIsCountryComboboxOpen] = useState(false);
- const countryChangeWarning = useCountryChangeWarningModal();
const { executeAsync } = useAction(updatePartnerProfileAction, {
onSuccess: async ({ data }) => {
@@ -244,15 +217,18 @@ function BasicInfoForm({
},
});
- const shouldShowCountryChangeWarning =
- !disabled &&
- !partner?.payoutsEnabledAt &&
- !!partner?.country &&
- !countryChangeWarning.isAcknowledged;
-
return (
<form
ref={formRef}
+ onKeyDown={(e) => {
+ if (e.key !== "Enter") return;
+
+ const target = e.target as HTMLElement;
+ if (target.tagName !== "INPUT") return;
+
+ e.preventDefault();
+ onSubmitAction();
+ }}
onSubmit={handleSubmit(async (data) => {
const imageChanged = data.image !== partner?.image;
@@ -263,7 +239,6 @@ function BasicInfoForm({
});
})}
>
- {countryChangeWarning.modal}
<div className="flex flex-col gap-6">
<label>
<div className="flex items-center gap-5">
@@ -342,29 +317,39 @@ function BasicInfoForm({
})}
/>
</label>
- {/* <label className="flex flex-col gap-1.5">
+
+ <label className="flex flex-col gap-1.5">
<span className="text-sm font-medium text-neutral-800">Username</span>
- <input
- type="text"
- disabled={disabled}
- className={cn(
- "block w-full rounded-md focus:outline-none sm:text-sm",
- disabled && "cursor-not-allowed bg-neutral-50 text-neutral-400",
- errors.username
- ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
- : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",
- )}
- placeholder={partner?.email?.split("@")[0] ?? ""}
- autoCapitalize="off"
- autoCorrect="off"
- spellCheck={false}
- {...register("username")}
- />
+ <div className="relative w-full">
+ <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-neutral-400">
+ @
+ </span>
+ <input
+ type="text"
+ disabled={disabled}
+ className={cn(
+ "block w-full rounded-md pl-7 focus:outline-none sm:text-sm",
+ disabled && "cursor-not-allowed bg-neutral-50 text-neutral-400",
+ errors.username
+ ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
+ : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",
+ )}
+ placeholder={partner?.email?.split("@")[0] ?? ""}
+ autoCapitalize="off"
+ autoCorrect="off"
+ spellCheck={false}
+ pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"
+ minLength={3}
+ maxLength={30}
+ {...register("username")}
+ />
+ </div>
<p className="text-xs text-neutral-500">
3–30 characters. Lowercase letters, numbers, hyphens, and
underscores only.
</p>
- </label> */}
+ </label>
+
<label className="flex flex-col">
<span className="text-sm font-medium text-neutral-800">Country</span>
<Controller
@@ -375,34 +360,13 @@ function BasicInfoForm({
<CountryCombobox
value={field.value || ""}
onChange={field.onChange}
- error={errors.country ? true : false}
- open={isCountryComboboxOpen}
- onOpenChange={(open) => {
- if (!open) {
- setIsCountryComboboxOpen(false);
- return;
- }
-
- if (shouldShowCountryChangeWarning) {
- countryChangeWarning.acknowledgeAndContinue(() => {
- setIsCountryComboboxOpen(true);
- });
- return;
- }
-
- setIsCountryComboboxOpen(true);
- }}
disabledTooltip={
- disabled ? (
- "You don't have permission to update this field"
- ) : partner?.payoutsEnabledAt ? (
- <TooltipContent
- title="Since you've already connected your bank account for payouts, you cannot change your profile country."
- cta="Contact support"
- href="https://dub.co/support"
- target="_blank"
- />
- ) : undefined
+ <TooltipContent
+ title="Your profile country is based on your current location and cannot be changed. If you need to update your country, please contact support."
+ cta="Contact support"
+ href="https://dub.co/support"
+ target="_blank"
+ />
}
/>
)}
@@ -415,16 +379,9 @@ function BasicInfoForm({
</span>
<DynamicTooltipWrapper
tooltipProps={{
- content: disabled ? (
- "You don't have permission to update this field"
- ) : partner?.payoutsEnabledAt ? (
- <TooltipContent
- title="Since you've already connected your bank account for payouts, you cannot change your profile type."
- cta="Contact support"
- href="https://dub.co/support"
- target="_blank"
- />
- ) : undefined,
+ content: disabled
+ ? "You don't have permission to update this field"
+ : undefined,
}}
>
<LayoutGroup>
@@ -442,19 +399,17 @@ function BasicInfoForm({
]}
selected={profileType}
selectAction={(option: "individual" | "company") => {
- if (!disabled && !partner?.payoutsEnabledAt) {
+ if (!disabled) {
setValue("profileType", option);
}
}}
className={cn(
"flex w-full items-center gap-0.5 rounded-lg border-neutral-300 bg-neutral-100 p-0.5",
- (disabled || partner?.payoutsEnabledAt) &&
- "cursor-not-allowed",
+ disabled && "cursor-not-allowed",
)}
optionClassName={cn(
"h-9 flex items-center justify-center rounded-lg flex-1",
- (disabled || partner?.payoutsEnabledAt) &&
- "pointer-events-none text-neutral-400",
+ disabled && "pointer-events-none text-neutral-400",
)}
indicatorClassName="bg-white"
/>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-composite-chart.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-composite-chart.tsx
index 697c378a65..d43f65d648 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-composite-chart.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-composite-chart.tsx
@@ -39,6 +39,8 @@ const EVENT_TYPE_LINE_COLORS = {
sale: "text-teal-500",
lead: "text-purple-500",
click: "text-blue-500",
+ referral: "text-orange-500",
+ custom: "text-gray-500",
};
const MAX_LINES = LINE_COLORS.length;
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-table.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-table.tsx
index 441b35c5c2..06199a45d8 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-table.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/earnings/earnings-table.tsx
@@ -175,21 +175,26 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
id: "country",
header: "Country",
accessorKey: "customer.country",
- cell: ({ getValue }) => (
- <div
- className="flex items-center gap-3"
- title={COUNTRIES[getValue()] ?? getValue()}
- >
- {getValue() ? (
- <CountryFlag countryCode={getValue()} />
- ) : (
- <Globe className="size-4 shrink-0" />
- )}
- <span className="truncate">
- {COUNTRIES[getValue()] || getValue() || "-"}
- </span>
- </div>
- ),
+ cell: ({ row }) => {
+ if (!row.original.customer) return "-";
+ const country = row.original.customer.country;
+
+ return (
+ <div
+ className="flex items-center gap-3"
+ title={country ? COUNTRIES[country] ?? country : undefined}
+ >
+ {country ? (
+ <CountryFlag countryCode={country} />
+ ) : (
+ <Globe className="size-4 shrink-0" />
+ )}
+ <span className="truncate">
+ {(country ? COUNTRIES[country] || country : null) ?? "-"}
+ </span>
+ </div>
+ );
+ },
},
]),
{
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx
index dae71f85e7..84c2a77779 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/page-client.tsx
@@ -4,20 +4,28 @@ import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "@/lib/analytics/constants";
import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
import { IntervalOptions } from "@/lib/analytics/types";
import { useSyncedLocalStorage } from "@/lib/hooks/use-synced-local-storage";
+import { constructPartnerReferralLink } from "@/lib/partner-referrals/utils";
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { QueryLinkStructureHelpText } from "@/lib/partners/query-link-structure-help-text";
import usePartnerAnalytics from "@/lib/swr/use-partner-analytics";
import { usePartnerEarningsTimeseries } from "@/lib/swr/use-partner-earnings-timeseries";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
-import { HeroBackground } from "@/ui/partners/hero-background";
+import { formatDiscountDescription } from "@/ui/partners/format-discount-description";
+import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
-import { ProgramRewardList } from "@/ui/partners/program-reward-list";
-import { ProgramRewardTerms } from "@/ui/partners/program-reward-terms";
+import { ProgramRewardModifiersTooltip } from "@/ui/partners/program-reward-modifiers-tooltip";
+import { REWARD_EVENT_ICON } from "@/ui/partners/rewards/reward-event-icon";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
import {
Button,
buttonVariants,
+ CopyText,
+ Gift,
+ Icon,
+ LinkLogo,
StatusBadge,
Tooltip,
useCopyToClipboard,
@@ -39,7 +47,13 @@ import {
ReferredVia,
UserPlus,
} from "@dub/ui/icons";
-import { cn, currencyFormatter, getPrettyUrl, nFormatter } from "@dub/utils";
+import {
+ cn,
+ currencyFormatter,
+ getApexDomain,
+ getPrettyUrl,
+ nFormatter,
+} from "@dub/utils";
import NumberFlow, { NumberFlowGroup } from "@number-flow/react";
import { LinearGradient } from "@visx/gradient";
import { endOfDay, startOfDay } from "date-fns";
@@ -49,6 +63,7 @@ import { useParams } from "next/navigation";
import {
createContext,
CSSProperties,
+ ReactNode,
useContext,
useId,
useMemo,
@@ -77,7 +92,6 @@ export function PartnerProgramOverviewPageClient() {
);
const { programEnrollment, showDetailedAnalytics } = useProgramEnrollment();
- const [copied, copyToClipboard] = useCopyToClipboard();
const {
start,
@@ -90,20 +104,11 @@ export function PartnerProgramOverviewPageClient() {
};
const program = programEnrollment?.program;
- const defaultProgramLink = programEnrollment?.links?.[0];
if (!program) {
return null;
}
- const partnerLink = constructPartnerLink({
- group: programEnrollment.group,
- link: defaultProgramLink,
- });
-
- const hasPartnerLink = Boolean(partnerLink);
- const isDeactivated = programEnrollment?.status === "deactivated";
-
return (
<PageWidthWrapper className="pb-10">
{program && (
@@ -121,118 +126,8 @@ export function PartnerProgramOverviewPageClient() {
}}
className="overflow-hidden"
>
- <div
- className={cn(
- "relative z-0 mb-4 flex flex-col overflow-hidden rounded-xl border border-neutral-200 p-4 sm:mb-5 md:p-6",
- isDeactivated && "opacity-80",
- )}
- >
- {program && (
- <HeroBackground
- logo={programEnrollment.group?.logo}
- color={programEnrollment.group?.brandColor}
- />
- )}
-
- <span className="text-base font-semibold text-neutral-800">
- Referral link
- </span>
- <div className="xs:flex-row xs:items-center relative mt-3 flex flex-col gap-2 md:max-w-[50%]">
- <input
- type="text"
- readOnly
- value={
- hasPartnerLink ? getPrettyUrl(partnerLink) : "No link yet"
- }
- disabled={isDeactivated}
- className={cn(
- "border-border-default focus:border-border-emphasis bg-bg-default h-10 min-w-0 shrink grow rounded-md border px-3 text-sm focus:outline-none focus:ring-neutral-500",
- hasPartnerLink
- ? "text-content-default"
- : "text-content-subtle",
- isDeactivated && "text-content-subtle cursor-default",
- )}
- />
- {isDeactivated ? (
- (() => {
- const deactivatedBadge = PartnerStatusBadges.deactivated;
- return (
- <StatusBadge
- variant={deactivatedBadge.variant}
- icon={deactivatedBadge.icon}
- className="xs:w-fit absolute right-4 top-1/2 -translate-y-1/2 px-1.5 py-0.5"
- >
- {deactivatedBadge.label}
- </StatusBadge>
- );
- })()
- ) : hasPartnerLink ? (
- <Button
- icon={
- <div className="relative size-4">
- <div
- className={cn(
- "absolute inset-0 transition-[transform,opacity]",
- copied && "translate-y-1 opacity-0",
- )}
- >
- <Copy className="size-4" />
- </div>
- <div
- className={cn(
- "absolute inset-0 transition-[transform,opacity]",
- !copied && "translate-y-1 opacity-0",
- )}
- >
- <Check className="size-4" />
- </div>
- </div>
- }
- text={copied ? "Copied link" : "Copy link"}
- className="xs:w-fit"
- onClick={() => {
- copyToClipboard(partnerLink);
- }}
- />
- ) : (
- <Link
- href={`/programs/${programSlug}/links`}
- className={cn(
- buttonVariants({ variant: "primary" }),
- "xs:w-fit inline-flex h-10 items-center justify-center rounded-lg px-4 text-sm font-medium",
- )}
- >
- Create link
- </Link>
- )}
- </div>
-
- {programEnrollment.group?.linkStructure === "query" &&
- defaultProgramLink && (
- <QueryLinkStructureHelpText link={defaultProgramLink} />
- )}
-
- <span className="mt-12 text-base font-semibold text-neutral-800">
- Rewards
- </span>
- <div className="relative mt-2 text-lg text-neutral-900 md:max-w-[50%]">
- {programEnrollment?.rewards ? (
- <>
- <ProgramRewardList
- rewards={programEnrollment.rewards}
- discount={programEnrollment.discount}
- />
- <ProgramRewardTerms
- minPayoutAmount={program.minPayoutAmount}
- holdingPeriodDays={
- programEnrollment.group?.holdingPeriodDays ?? 0
- }
- />
- </>
- ) : (
- <div className="h-7 w-5/6 animate-pulse rounded-md bg-neutral-200" />
- )}
- </div>
+ <div className="mb-10">
+ <RewardList />
</div>
</motion.div>
)}
@@ -679,3 +574,331 @@ function ViewMoreButton({ href }: { href: string }) {
</div>
);
}
+
+function RewardsTermsList() {
+ const { programEnrollment } = useProgramEnrollment();
+
+ if (!programEnrollment) {
+ return null;
+ }
+
+ const minPayoutAmount = programEnrollment.program.minPayoutAmount ?? 0;
+ const holdingPeriodDays = programEnrollment.group?.holdingPeriodDays ?? 0;
+
+ const items = [
+ ...(minPayoutAmount > 0
+ ? [
+ {
+ label: "minimum payout",
+ value: currencyFormatter(minPayoutAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ }),
+ href: "https://dub.co/help/article/commissions-payouts#what-does-minimum-payout-amount-mean",
+ },
+ ]
+ : []),
+ ...(holdingPeriodDays > 0
+ ? [
+ {
+ label: "holding period",
+ value: `${holdingPeriodDays}-day`,
+ href: "https://dub.co/help/article/commissions-payouts#what-does-holding-period-mean",
+ },
+ ]
+ : []),
+ ];
+
+ if (items.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-wrap items-center gap-x-1.5 text-xs">
+ {items.map((item, idx) => (
+ <span key={item.label} className="inline-flex items-center gap-1.5">
+ <span>
+ <span className="font-semibold text-neutral-600">{item.value}</span>{" "}
+ <a
+ href={item.href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-neutral-500 underline decoration-dotted underline-offset-2"
+ >
+ {item.label}
+ </a>
+ </span>
+ {idx < items.length - 1 && (
+ <span className="font-semibold text-neutral-600">•</span>
+ )}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function RewardList() {
+ const { programEnrollment } = useProgramEnrollment();
+ const { partner } = usePartnerProfile();
+
+ if (!programEnrollment) {
+ return null;
+ }
+
+ const eligibleRewards = (programEnrollment.rewards ?? []).filter(
+ (r) => getRewardAmount(r) >= 0,
+ );
+
+ const standardRewards = eligibleRewards.filter(
+ (reward) =>
+ reward.event === "click" ||
+ reward.event === "lead" ||
+ reward.event === "sale",
+ );
+
+ const referralRewards = eligibleRewards.filter(
+ (reward) => reward.event === "referral",
+ );
+
+ const discount = programEnrollment.discount ?? null;
+ const showReferralRewardCard = referralRewards.length > 0;
+
+ const defaultProgramLink = programEnrollment.links?.[0];
+ const partnerLink = constructPartnerLink({
+ group: programEnrollment.group,
+ link: defaultProgramLink,
+ });
+ const hasPartnerLink = Boolean(partnerLink);
+ const isDeactivated = programEnrollment.status === "deactivated";
+
+ const partnerReferralApplyLink = constructPartnerReferralLink({
+ partner,
+ program: programEnrollment.program,
+ });
+
+ return (
+ <div className="flex flex-col gap-2 rounded-xl bg-neutral-100 p-2">
+ <RewardListItem
+ title={showReferralRewardCard ? "Customer referral rewards" : "Rewards"}
+ titleRight={<RewardsTermsList />}
+ isDeactivated={isDeactivated}
+ rewards={[
+ ...standardRewards.map((reward) => ({
+ id: reward.id,
+ icon: REWARD_EVENT_ICON[reward.event],
+ text: (
+ <>
+ {formatRewardDescription(reward, { includeEarnPrefix: false })}
+ {(!!reward.modifiers?.length ||
+ Boolean(reward.tooltipDescription)) && (
+ <>
+ {" "}
+ <ProgramRewardModifiersTooltip reward={reward} />
+ </>
+ )}
+ </>
+ ),
+ })),
+ ...(discount
+ ? [
+ {
+ id: "discount",
+ icon: Gift,
+ text: formatDiscountDescription(discount),
+ },
+ ]
+ : []),
+ ]}
+ link={{
+ displayText: hasPartnerLink
+ ? getPrettyUrl(partnerLink)
+ : "No link yet",
+ copyValue: partnerLink,
+ apexDomain: defaultProgramLink
+ ? getApexDomain(defaultProgramLink.url)
+ : null,
+ }}
+ queryLinkHelpTextLink={
+ hasPartnerLink && programEnrollment.group?.linkStructure === "query"
+ ? defaultProgramLink
+ : undefined
+ }
+ />
+
+ {showReferralRewardCard && (
+ <RewardListItem
+ title="Partner referral rewards"
+ isDeactivated={isDeactivated}
+ rewards={referralRewards.map((reward) => ({
+ id: reward.id,
+ icon: REWARD_EVENT_ICON.referral,
+ text: formatRewardDescription(reward),
+ badge: (
+ <span className="inline-flex h-4 shrink-0 items-center justify-center rounded-md bg-blue-100 px-1 text-xs font-semibold leading-4 tracking-tight text-blue-600">
+ New
+ </span>
+ ),
+ }))}
+ link={{
+ displayText: getPrettyUrl(partnerReferralApplyLink),
+ copyValue: partnerReferralApplyLink,
+ apexDomain: "dub.co",
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function RewardListItem({
+ title,
+ titleRight,
+ rewards,
+ link,
+ queryLinkHelpTextLink,
+ isDeactivated,
+}: {
+ title: string;
+ titleRight?: ReactNode;
+ rewards: {
+ id: string;
+ text: ReactNode;
+ icon: Icon;
+ badge?: ReactNode;
+ }[];
+ link: {
+ displayText: string;
+ copyValue: string;
+ apexDomain?: string | null;
+ };
+ queryLinkHelpTextLink?: {
+ key: string;
+ url: string;
+ shortLink: string;
+ };
+ isDeactivated?: boolean;
+}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const [copied, copyToClipboard] = useCopyToClipboard();
+ const copyDisabled =
+ isDeactivated || !link.copyValue || link.copyValue.length === 0;
+
+ return (
+ <div
+ className={cn(
+ "flex flex-col gap-3 rounded-xl border border-neutral-200 bg-white p-4",
+ isDeactivated && "opacity-80",
+ )}
+ >
+ <div className="flex items-center justify-between">
+ <h3 className="text-base font-semibold tracking-tight text-neutral-800">
+ {title}
+ </h3>
+ {titleRight}
+ </div>
+
+ <div className="overflow-hidden rounded-xl border border-neutral-200 bg-neutral-50">
+ <div className="bg-neutral-50 px-3 py-2.5">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-2.5">
+ <div className="shrink-0 rounded-full border border-neutral-200 bg-white p-1">
+ <LinkLogo
+ apexDomain={link.apexDomain}
+ className="size-4.5 sm:size-4.5 shrink-0 rounded-full"
+ imageProps={{ width: 18, height: 18 }}
+ />
+ </div>
+
+ <CopyText
+ value={link.copyValue}
+ className="min-w-0 truncate text-sm font-medium -tracking-wider text-neutral-600"
+ >
+ {link.displayText}
+ </CopyText>
+ {queryLinkHelpTextLink && (
+ <>
+ <span className="hidden text-sm text-neutral-500 sm:block">
+ →
+ </span>
+ <QueryLinkStructureHelpText
+ link={queryLinkHelpTextLink}
+ className="hidden sm:block"
+ />
+ </>
+ )}
+ </div>
+ {isDeactivated ? (
+ <StatusBadge variant={PartnerStatusBadges.deactivated.variant}>
+ {PartnerStatusBadges.deactivated.label}
+ </StatusBadge>
+ ) : (
+ <Button
+ variant="primary"
+ disabled={copyDisabled}
+ onClick={() => {
+ copyToClipboard(link.copyValue);
+ }}
+ className={cn(
+ "h-8 w-auto shrink-0 px-3 transition-opacity",
+ !copyDisabled && "hover:opacity-90",
+ )}
+ icon={
+ <span className="relative size-4">
+ <Copy
+ className={cn(
+ "absolute inset-0 size-4 transition-[transform,opacity]",
+ copied && "translate-y-1 opacity-0",
+ )}
+ />
+ <Check
+ className={cn(
+ "absolute inset-0 size-4 transition-[transform,opacity]",
+ !copied && "translate-y-1 opacity-0",
+ )}
+ />
+ </span>
+ }
+ text={copied ? "Copied" : "Copy"}
+ />
+ )}
+ </div>
+ </div>
+
+ {rewards.length > 0 ? (
+ <div className="space-y-2 rounded-t-xl border-t border-neutral-200 bg-white p-3">
+ {rewards.map((reward) => {
+ const RewardIcon = reward.icon;
+
+ return (
+ <div key={reward.id} className="flex items-center gap-2.5">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <RewardIcon className="size-4 text-neutral-800" />
+ </div>
+ <div className="text-content-default flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-0 text-sm font-semibold leading-5 tracking-tight">
+ {reward.text}
+ {reward.badge}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="flex items-center justify-between rounded-t-xl border-t border-neutral-200 bg-white px-4 py-3">
+ <p className="text-content-subtle text-sm">
+ You are not eligible for any rewards at this time.
+ </p>
+
+ {programSlug && (
+ <Link href={`/messages/${programSlug}`}>
+ <Button
+ variant="secondary"
+ text="Contact program"
+ className="h-8 rounded-lg px-3"
+ />
+ </Link>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/referrals/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/referrals/page-client.tsx
new file mode 100644
index 0000000000..e3a5992362
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/referrals/page-client.tsx
@@ -0,0 +1,252 @@
+"use client";
+
+import { useReferredPartnerFilters } from "@/lib/partner-referrals/hooks/use-referred-partner-filters";
+import { useReferredPartners } from "@/lib/partner-referrals/hooks/use-referred-partners";
+import { useReferredPartnersCount } from "@/lib/partner-referrals/hooks/use-referred-partners-count";
+import { ReferredPartnerProps } from "@/lib/partner-referrals/types";
+import { constructPartnerReferralLink } from "@/lib/partner-referrals/utils";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { PartnerRowItem } from "@/ui/partners/partner-row-item";
+import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { CountryFlag } from "@/ui/shared/country-flag";
+import {
+ AnimatedSizeContainer,
+ Button,
+ Copy,
+ Filter,
+ StatusBadge,
+ Table,
+ TimestampTooltip,
+ useCopyToClipboard,
+ usePagination,
+ useTable,
+} from "@dub/ui";
+import { Users6 } from "@dub/ui/icons";
+import { COUNTRIES, currencyFormatter, formatDate } from "@dub/utils";
+import { Row } from "@tanstack/react-table";
+import { notFound } from "next/navigation";
+import { useMemo } from "react";
+import { toast } from "sonner";
+
+export function PartnerReferralsPageClient() {
+ const { programEnrollment } = useProgramEnrollment();
+ const { partner } = usePartnerProfile();
+
+ if (programEnrollment && !programEnrollment.referralRewardId) {
+ notFound();
+ }
+
+ const { data: referredPartners, isLoading, error } = useReferredPartners();
+
+ const { data: referredPartnersCount, error: countError } =
+ useReferredPartnersCount();
+
+ const { pagination, setPagination } = usePagination(100);
+
+ const {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ isFiltered,
+ setSelectedFilter,
+ } = useReferredPartnerFilters();
+
+ const referralLink = constructPartnerReferralLink({
+ partner,
+ program: programEnrollment?.program,
+ });
+
+ const [, copyToClipboard] = useCopyToClipboard();
+
+ const copyReferralLink = () => {
+ if (!referralLink) return;
+ toast.promise(copyToClipboard(referralLink), {
+ success: "Copied referral link to clipboard!",
+ });
+ };
+
+ const columns = useMemo(
+ () => [
+ {
+ id: "partner",
+ header: "Partner",
+ enableHiding: false,
+ minSize: 250,
+ cell: ({ row }: { row: Row<ReferredPartnerProps> }) => {
+ return (
+ <PartnerRowItem
+ partner={{
+ ...row.original,
+ name: row.original.email ?? "",
+ image: null,
+ }}
+ showPermalink={false}
+ />
+ );
+ },
+ },
+ {
+ id: "status",
+ header: "Status",
+ minSize: 120,
+ cell: ({ row }: { row: Row<ReferredPartnerProps> }) => {
+ const badge =
+ PartnerStatusBadges[row.original.programEnrollment.status];
+ return (
+ <StatusBadge icon={null} variant={badge.variant}>
+ {badge.label}
+ </StatusBadge>
+ );
+ },
+ },
+ {
+ id: "createdAt",
+ header: "Enrolled",
+ cell: ({ row }: { row: Row<ReferredPartnerProps> }) => (
+ <TimestampTooltip
+ timestamp={row.original.programEnrollment.createdAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.programEnrollment.createdAt, {
+ month: "short",
+ })}
+ </span>
+ </TimestampTooltip>
+ ),
+ },
+ {
+ id: "country",
+ header: "Country",
+ minSize: 150,
+ cell: ({ row }: { row: Row<ReferredPartnerProps> }) => {
+ const country = row.original.country;
+ return (
+ <div className="flex items-center gap-2">
+ {country && <CountryFlag countryCode={country} />}
+ <span className="min-w-0 truncate">
+ {(country ? COUNTRIES[country] : null) ?? "-"}
+ </span>
+ </div>
+ );
+ },
+ },
+ {
+ id: "earnings",
+ header: "Earnings",
+ minSize: 120,
+ meta: {
+ headerTooltip: "Total commission earned from this partner.",
+ },
+ cell: ({ row }: { row: Row<ReferredPartnerProps> }) =>
+ currencyFormatter(row.original.programEnrollment.earnings, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }),
+ },
+ ],
+ [],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: referredPartners || [],
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName: (p) => `partner${p ? "s" : ""}`,
+ rowCount: referredPartnersCount || 0,
+ loading: isLoading,
+ error:
+ error instanceof Error
+ ? error.message
+ : countError
+ ? "Failed to load referred partners"
+ : undefined,
+ });
+
+ return (
+ <PageContent title="Referred partners">
+ <PageWidthWrapper className="flex flex-col gap-3 pb-10">
+ <div className="flex flex-col gap-4">
+ <div>
+ <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
+ <Filter.Select
+ className="w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onSelectedFilterChange={setSelectedFilter}
+ />
+ {referralLink && (
+ <Button
+ variant="primary"
+ text="Copy link"
+ icon={<Copy className="size-4" />}
+ className="h-9 w-fit"
+ onClick={copyReferralLink}
+ />
+ )}
+ </div>
+ <AnimatedSizeContainer height>
+ <div>
+ {activeFilters.length > 0 && (
+ <div className="pt-3">
+ <Filter.List
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onRemoveAll={onRemoveAll}
+ />
+ </div>
+ )}
+ </div>
+ </AnimatedSizeContainer>
+ </div>
+
+ {referredPartners?.length !== 0 ? (
+ <Table {...tableProps} table={table} />
+ ) : (
+ <AnimatedEmptyState
+ title={
+ isFiltered
+ ? "No referred partners found"
+ : "No referred partners yet"
+ }
+ description={
+ isFiltered
+ ? "No referred partners found for the selected filters. Adjust your filters to refine your search results."
+ : "Share your referral link to invite other partners to join this program. When they sign up through your link, they'll appear here."
+ }
+ cardContent={() => (
+ <>
+ <Users6 className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ addButton={
+ referralLink ? (
+ <Button
+ text="Copy referral link"
+ onClick={copyReferralLink}
+ />
+ ) : undefined
+ }
+ />
+ )}
+ </div>
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/referrals/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/referrals/page.tsx
new file mode 100644
index 0000000000..a61d882c95
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/referrals/page.tsx
@@ -0,0 +1,5 @@
+import { PartnerReferralsPageClient } from "./page-client";
+
+export default function PartnerReferralsPage() {
+ return <PartnerReferralsPageClient />;
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/apply/program-sidebar.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/apply/program-sidebar.tsx
index 9d1a991600..581864b2b8 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/apply/program-sidebar.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/apply/program-sidebar.tsx
@@ -103,81 +103,73 @@ export function ProgramSidebar({
const [justApplied, setJustApplied] = useState(false);
- const applyDisabledTooltip: ReactNode = justApplied
- ? undefined
- : programEnrollment?.status === "pending"
- ? "Your application is under review"
- : programEnrollment?.status &&
- ["banned", "rejected", "deactivated"].includes(
- programEnrollment.status,
- )
- ? `You were ${programEnrollment.status} from this program`
- : programEnrollment
- ? undefined
- : !isComplete
- ? (
- <div className="max-w-xs p-3 text-center">
- <div className="text-content-default text-pretty text-sm leading-5">
- Complete your profile to join the Dub Partner Network. Once
- approved, you can then apply to this program.
- </div>
- <Link
- href="/profile"
- className="bg-bg-subtle mt-3 flex items-center justify-center gap-2 rounded-lg px-2.5 py-1.5"
- >
- <ProgressCircle
- progress={completedCount / totalCount}
- className="text-green-500"
- />
- <span className="text-content-default text-sm font-medium">
- {completedCount} of {totalCount} tasks completed
- </span>
- </Link>
- </div>
- )
- : partner && !["approved", "trusted"].includes(partner.networkStatus)
- ? (() => {
- const networkStatusBadge =
- NetworkStatusBadges[partner.networkStatus];
- if (!("partnerTooltip" in networkStatusBadge)) {
- return null;
- }
- const {
- partnerTooltip,
- icon: Icon,
- className,
- } = networkStatusBadge;
- const { content, cta } = partnerTooltip;
+ const applyDisabledTooltip: ReactNode =
+ justApplied ? undefined : programEnrollment?.status === "pending" ? (
+ "Your application is under review"
+ ) : programEnrollment?.status &&
+ ["banned", "rejected", "deactivated"].includes(
+ programEnrollment.status,
+ ) ? (
+ `You were ${programEnrollment.status} from this program`
+ ) : programEnrollment ? undefined : !isComplete ? (
+ <div className="max-w-xs p-3 text-center">
+ <div className="text-content-default text-pretty text-sm leading-5">
+ Complete your profile to join the Dub Partner Network. Once approved,
+ you can then apply to this program.
+ </div>
+ <Link
+ href="/profile"
+ className="bg-bg-subtle mt-3 flex items-center justify-center gap-2 rounded-lg px-2.5 py-1.5"
+ >
+ <ProgressCircle
+ progress={completedCount / totalCount}
+ className="text-green-500"
+ />
+ <span className="text-content-default text-sm font-medium">
+ {completedCount} of {totalCount} tasks completed
+ </span>
+ </Link>
+ </div>
+ ) : partner && !["approved", "trusted"].includes(partner.networkStatus) ? (
+ (() => {
+ const networkStatusBadge = NetworkStatusBadges[partner.networkStatus];
+ if (!("partnerTooltip" in networkStatusBadge)) {
+ return null;
+ }
+ const { partnerTooltip, icon: Icon, className } = networkStatusBadge;
+ const { content, cta } = partnerTooltip;
- return (
- <div className="max-w-xs space-y-2 p-4 text-center">
- <div className="text-content-default text-pretty text-sm leading-5">
- {content}
- </div>
- {partner.networkStatus === "draft" ? (
- <Button
- className="p-2"
- text={cta}
- onClick={() => setShowConfirmModal(true)}
- />
- ) : (
- <Link
- href="/profile"
- className={cn(
- "flex items-center justify-center gap-2 rounded-lg p-2",
- "ctaClassName" in partnerTooltip
- ? partnerTooltip.ctaClassName
- : className,
- )}
- >
- <Icon className="size-4 shrink-0" />
- <span className="text-sm font-medium">{cta}</span>
- </Link>
- )}
- </div>
- );
- })()
- : requirementsNotMet;
+ return (
+ <div className="max-w-xs space-y-2 p-4 text-center">
+ <div className="text-content-default text-pretty text-sm leading-5">
+ {content}
+ </div>
+ {partner.networkStatus === "draft" ? (
+ <Button
+ className="p-2"
+ text={cta}
+ onClick={() => setShowConfirmModal(true)}
+ />
+ ) : (
+ <Link
+ href="/profile"
+ className={cn(
+ "flex items-center justify-center gap-2 rounded-lg p-2",
+ "ctaClassName" in partnerTooltip
+ ? partnerTooltip.ctaClassName
+ : className,
+ )}
+ >
+ <Icon className="size-4 shrink-0" />
+ <span className="text-sm font-medium">{cta}</span>
+ </Link>
+ )}
+ </div>
+ );
+ })()
+ ) : (
+ requirementsNotMet
+ );
const statusBadge = programEnrollment
? {
@@ -278,8 +270,7 @@ export function ProgramSidebar({
text={buttonText}
icon={justApplied ? <CircleCheck className="size-4" /> : undefined}
disabled={
- !applyDisabledTooltip &&
- (!!programEnrollment || justApplied)
+ !applyDisabledTooltip && (!!programEnrollment || justApplied)
? true
: undefined
}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx
index 2cb92c8819..5acd41cb34 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/invite/page.tsx
@@ -37,9 +37,10 @@ export default async function ProgramInvitePage(props: {
},
include: {
partnerGroup: true,
- saleReward: true,
- leadReward: true,
clickReward: true,
+ leadReward: true,
+ saleReward: true,
+ referralReward: true,
discount: true,
},
},
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx
index a4229c0a73..9111483d1e 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/use-program-network-filters.tsx
@@ -1,6 +1,6 @@
import { PROGRAM_CATEGORIES_MAP } from "@/lib/network/program-categories";
import useNetworkProgramsCount from "@/lib/swr/use-network-programs-count";
-import { REWARD_EVENTS } from "@/ui/partners/constants";
+import { REWARD_EVENT_ICON } from "@/ui/partners/rewards/reward-event-icon";
import { useRouterStuff } from "@dub/ui";
import { CircleDotted, Gift, Suitcase } from "@dub/ui/icons";
import { capitalize, cn, nFormatter } from "@dub/utils";
@@ -9,15 +9,15 @@ import { ProgramNetworkStatusBadges } from "./program-status-badge";
const REWARD_TYPES = {
sale: {
- icon: REWARD_EVENTS.sale.icon,
+ icon: REWARD_EVENT_ICON.sale,
label: "Sale reward (CPS)",
},
lead: {
- icon: REWARD_EVENTS.lead.icon,
+ icon: REWARD_EVENT_ICON.lead,
label: "Lead reward (CPL)",
},
click: {
- icon: REWARD_EVENTS.click.icon,
+ icon: REWARD_EVENT_ICON.click,
label: "Click reward (CPC)",
},
discount: {
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/referrals/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/referrals/page-client.tsx
new file mode 100644
index 0000000000..c0b9cbd07c
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/referrals/page-client.tsx
@@ -0,0 +1,639 @@
+"use client";
+
+import {
+ NETWORK_REFERRAL_REWARD,
+ NETWORK_REFERRAL_SWAG_THRESHOLD_CENTS,
+} from "@/lib/partner-referrals/constants";
+import { useNetworkReferrals } from "@/lib/partner-referrals/hooks/use-network-referrals";
+import { useNetworkReferralsStats } from "@/lib/partner-referrals/hooks/use-network-referrals-stats";
+import { useNetworkReferralsTimeseries } from "@/lib/partner-referrals/hooks/use-network-referrals-timeseries";
+import { NetworkReferralProps } from "@/lib/partner-referrals/types";
+import { constructPartnerReferralLink } from "@/lib/partner-referrals/utils";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { PartnerRowItem } from "@/ui/partners/partner-row-item";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { CountryFlag } from "@/ui/shared/country-flag";
+import {
+ Button,
+ Copy,
+ CopyText,
+ MiniAreaChart,
+ Table,
+ TimestampTooltip,
+ Tooltip,
+ useCopyToClipboard,
+ useMediaQuery,
+ usePagination,
+ useTable,
+} from "@dub/ui";
+import { Gift, UserArrowRight } from "@dub/ui/icons";
+import {
+ COUNTRIES,
+ currencyFormatter,
+ DUB_LOGO,
+ formatDate,
+ getPrettyUrl,
+} from "@dub/utils";
+import { Row } from "@tanstack/react-table";
+import { Check, HelpCircle, Lock } from "lucide-react";
+import Image from "next/image";
+import Link from "next/link";
+import { ComponentType, ReactNode, useMemo } from "react";
+import { toast } from "sonner";
+
+function useNetworkReferralAccess() {
+ const { partner, loading } = usePartnerProfile();
+
+ const profileReady = !loading && !!partner;
+ const isEligible =
+ partner?.networkStatus === "approved" ||
+ partner?.networkStatus === "trusted";
+
+ const referralLink = constructPartnerReferralLink({
+ partner,
+ });
+
+ return {
+ partner,
+ loading,
+ profileReady,
+ isEligible,
+ referralLink,
+ };
+}
+
+const REFERRALS_EMPTY_STATE_CARD_PARTNERS = [
+ {
+ name: "Derek Forbes",
+ index: 0,
+ earningsCents: 124_500,
+ },
+ {
+ name: "Lauren Anderson",
+ index: 1,
+ earningsCents: 89_200,
+ },
+ {
+ name: "Elias Weber",
+ index: 4,
+ earningsCents: 210_000,
+ },
+] as const;
+
+function ReferralsEmptyState({
+ title,
+ description,
+ button,
+}: {
+ title: string;
+ description: ReactNode;
+ button?: ReactNode;
+}) {
+ return (
+ <AnimatedEmptyState
+ title={title}
+ description={description}
+ cardContent={(idx) => {
+ const partner =
+ REFERRALS_EMPTY_STATE_CARD_PARTNERS[
+ idx % REFERRALS_EMPTY_STATE_CARD_PARTNERS.length
+ ];
+
+ return (
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <div
+ className="size-7 shrink-0 rounded-full border border-neutral-300 bg-neutral-300"
+ style={{
+ backgroundImage:
+ "url(https://assets.dub.co/partners/partner-images.jpg)",
+ backgroundSize: "1400%",
+ backgroundPositionX: (14 - (partner.index % 14)) * 100 + "%",
+ }}
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-0">
+ <span className="text-content-default block truncate text-xs font-semibold leading-tight">
+ {partner.name}
+ </span>
+ <span className="text-content-subtle block truncate text-[11px] font-medium leading-none">
+ Your earnings:{" "}
+ {currencyFormatter(partner.earningsCents, {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 0,
+ })}
+ </span>
+ </div>
+ </div>
+ );
+ }}
+ cardClassName="p-3 opacity-70"
+ addButton={button}
+ />
+ );
+}
+
+function ReferralsStatItem({
+ label,
+ tooltipContent,
+ children,
+ isLoading,
+ chartData,
+}: {
+ label: ReactNode;
+ tooltipContent: string;
+ children: ReactNode;
+ isLoading: boolean;
+ chartData?: { date: Date; value: number }[] | null;
+}) {
+ return (
+ <div className="flex flex-col gap-1 p-4 pr-0">
+ <div className="flex items-center gap-1">
+ <span className="text-content-default text-sm font-medium">
+ {label}
+ </span>
+ <Tooltip content={tooltipContent} side="top">
+ <HelpCircle className="size-3.5 text-neutral-500" />
+ </Tooltip>
+ </div>
+
+ <div className="flex items-end gap-4">
+ <span className="text-content-emphasis whitespace-nowrap text-3xl font-medium tabular-nums">
+ {isLoading ? (
+ <span
+ aria-hidden="true"
+ className="mt-0.5 block h-8 w-[4.75rem] animate-pulse rounded-md bg-neutral-200"
+ />
+ ) : (
+ children
+ )}
+ </span>
+ {chartData && chartData.length > 0 && (
+ <div className="relative h-10 flex-1">
+ <MiniAreaChart data={chartData} padding={{ top: 8, bottom: 8 }} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function ReferralsStats() {
+ const {
+ loading: partnerLoading,
+ profileReady,
+ isEligible,
+ } = useNetworkReferralAccess();
+
+ const { data: stats, isLoading: statsLoading } = useNetworkReferralsStats({
+ enabled: profileReady && isEligible,
+ });
+
+ const { data: timeseries } = useNetworkReferralsTimeseries({
+ enabled: profileReady && isEligible,
+ });
+
+ const partnersChartData = (timeseries || [])?.map((d) => ({
+ date: new Date(d.start),
+ value: d.partners,
+ }));
+
+ const earningsChartData = (timeseries || [])?.map((d) => ({
+ date: new Date(d.start),
+ value: d.earnings,
+ }));
+
+ return (
+ <div className="grid grid-cols-2 divide-x divide-neutral-200 rounded-xl border border-neutral-200 bg-white">
+ <ReferralsStatItem
+ label="Referred partners"
+ tooltipContent="Partners who joined Dub Partners using your referral link."
+ isLoading={partnerLoading || statsLoading}
+ chartData={partnersChartData}
+ >
+ {stats?.count ?? 0}
+ </ReferralsStatItem>
+
+ <ReferralsStatItem
+ label="Your earnings"
+ tooltipContent="Total commission earned from your referrals."
+ isLoading={partnerLoading || statsLoading}
+ chartData={earningsChartData}
+ >
+ {currencyFormatter(stats?.totalEarnings ?? 0, {
+ trailingZeroDisplay: "stripIfInteger",
+ })}
+ </ReferralsStatItem>
+ </div>
+ );
+}
+
+function ReferralLinkLocked() {
+ return (
+ <div className="rounded-xl border border-neutral-200 bg-white p-4">
+ <p className="text-content-default mb-2 text-sm font-semibold">
+ Referral link
+ </p>
+ <div className="rounded-xl border border-neutral-200 p-2">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <span
+ className="flex size-9 shrink-0 items-center justify-center rounded-full border border-neutral-200 bg-white sm:size-10"
+ aria-hidden
+ >
+ <Lock className="size-4 text-neutral-900" strokeWidth={2} />
+ </span>
+ <span className="text-content-default min-w-0 text-sm font-medium leading-snug">
+ Get accepted to the Dub Network to unlock
+ </span>
+ </div>
+ <Link href="/profile" className="shrink-0">
+ <Button text="Apply" variant="primary" className="h-9 w-fit px-4" />
+ </Link>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ReferralLink() {
+ const { profileReady, isEligible, referralLink } = useNetworkReferralAccess();
+ const [copied, copyToClipboard] = useCopyToClipboard();
+ const { isMobile } = useMediaQuery();
+
+ const copyReferralLink = () => {
+ if (!referralLink) return;
+ toast.promise(copyToClipboard(referralLink), {
+ success: "Copied referral link to clipboard!",
+ });
+ };
+
+ if (!profileReady) {
+ return null;
+ }
+
+ if (!isEligible) {
+ return <ReferralLinkLocked />;
+ }
+
+ if (!referralLink) {
+ return null;
+ }
+
+ return (
+ <div className="rounded-xl border border-neutral-200 bg-white p-4">
+ <p className="text-content-default mb-2 text-sm font-semibold">
+ Referral link
+ </p>
+ <div className="rounded-xl border border-neutral-200 p-2">
+ <div className="flex min-w-0 items-center justify-between gap-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <div className="relative flex size-9 shrink-0 items-center justify-center sm:size-10">
+ <div className="absolute inset-0 rounded-full border border-neutral-200">
+ <div className="h-full w-full rounded-full border border-white bg-gradient-to-t from-neutral-100" />
+ </div>
+ <img
+ src={DUB_LOGO}
+ alt="Dub Partners"
+ className="relative z-10 size-6 shrink-0 rounded-full"
+ />
+ </div>
+ <CopyText
+ className="text-content-default min-w-0 truncate text-sm font-semibold"
+ value={referralLink}
+ >
+ {getPrettyUrl(referralLink)}
+ </CopyText>
+ </div>
+ <Button
+ text={isMobile ? undefined : "Copy link"}
+ variant="primary"
+ icon={
+ copied ? (
+ <Check className="size-4" />
+ ) : (
+ <Copy className="size-4" />
+ )
+ }
+ className="h-9 w-fit shrink-0"
+ onClick={copyReferralLink}
+ aria-label="Copy referral link"
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ReferralRewardListItem(props: {
+ icon: ComponentType<{ className?: string }>;
+ children: ReactNode;
+}) {
+ const Icon = props.icon;
+
+ return (
+ <li className="flex gap-2.5">
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <Icon className="size-4 text-neutral-800" />
+ </span>
+ <span className="text-content-default text-sm font-medium">
+ {props.children}
+ </span>
+ </li>
+ );
+}
+
+function ReferralRewards() {
+ return (
+ <div className="rounded-xl border border-neutral-200 bg-white p-4">
+ <p className="text-content-default mb-2 text-sm font-semibold">
+ Referral Rewards
+ </p>
+ <ul className="flex flex-col gap-2">
+ <ReferralRewardListItem icon={UserArrowRight}>
+ You get {NETWORK_REFERRAL_REWARD.amountInPercentage}% of your
+ referees&apos; payout fees for the first{" "}
+ {NETWORK_REFERRAL_REWARD.maxDuration} months.
+ </ReferralRewardListItem>
+
+ <ReferralRewardListItem icon={Gift}>
+ Unlock premium Dub swag once you cross{" "}
+ {currencyFormatter(NETWORK_REFERRAL_SWAG_THRESHOLD_CENTS, {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 0,
+ })}{" "}
+ in referral bonus earnings.
+ </ReferralRewardListItem>
+ </ul>
+ </div>
+ );
+}
+
+function ReferredPartners() {
+ const {
+ loading: partnerLoading,
+ profileReady,
+ isEligible,
+ referralLink,
+ } = useNetworkReferralAccess();
+
+ const {
+ data: referredPartners,
+ isLoading,
+ error,
+ } = useNetworkReferrals({
+ enabled: profileReady && isEligible,
+ });
+
+ const [copied, copyToClipboard] = useCopyToClipboard();
+
+ const copyReferralLink = () => {
+ if (!referralLink) return;
+ toast.promise(copyToClipboard(referralLink), {
+ success: "Copied referral link to clipboard!",
+ });
+ };
+
+ const { data: stats } = useNetworkReferralsStats({
+ enabled: profileReady && isEligible,
+ });
+
+ const { pagination, setPagination } = usePagination(100);
+
+ const columns = useMemo(
+ () => [
+ {
+ id: "partner",
+ header: "Partner",
+ enableHiding: false,
+ minSize: 250,
+ cell: ({ row }: { row: Row<NetworkReferralProps> }) => (
+ <PartnerRowItem
+ partner={{
+ ...row.original,
+ name: row.original.email ?? "",
+ image: null,
+ }}
+ showPermalink={false}
+ />
+ ),
+ },
+ {
+ id: "createdAt",
+ header: "Joined",
+ cell: ({ row }: { row: Row<NetworkReferralProps> }) => (
+ <TimestampTooltip
+ timestamp={row.original.createdAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.createdAt, {
+ month: "short",
+ })}
+ </span>
+ </TimestampTooltip>
+ ),
+ },
+ {
+ id: "country",
+ header: "Country",
+ minSize: 150,
+ cell: ({ row }: { row: Row<NetworkReferralProps> }) => {
+ const country = row.original.country;
+
+ return (
+ <div className="flex items-center gap-2">
+ {country && <CountryFlag countryCode={country} />}
+ <span className="min-w-0 truncate">
+ {(country ? COUNTRIES[country] : null) ?? "-"}
+ </span>
+ </div>
+ );
+ },
+ },
+ {
+ id: "activeProgramsCount",
+ header: "Active programs",
+ minSize: 150,
+ cell: ({ row }: { row: Row<NetworkReferralProps> }) => {
+ return row.original.activeProgramsCount;
+ },
+ },
+ {
+ id: "totalEarnings",
+ header: "Your earnings",
+ minSize: 120,
+ meta: {
+ headerTooltip: "Total commission earned from this partner.",
+ },
+ cell: ({ row }: { row: Row<NetworkReferralProps> }) =>
+ currencyFormatter(row.original.totalEarnings, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }),
+ },
+ ],
+ [],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: referredPartners || [],
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName: (p) => `partner${p ? "s" : ""}`,
+ rowCount: stats?.count ?? 0,
+ loading: isLoading || partnerLoading,
+ error: error instanceof Error ? error.message : undefined,
+ });
+
+ const hasRows = (referredPartners?.length ?? 0) > 0;
+
+ if (profileReady && !isEligible) {
+ return (
+ <div className="flex flex-col gap-4">
+ <ReferralsEmptyState
+ title="No referred partners"
+ description="Get accepted to the Dub Network to start earning from referred partners."
+ button={
+ <Link href="/profile">
+ <Button
+ text="Apply to the network"
+ variant="primary"
+ className="h-9"
+ />
+ </Link>
+ }
+ />
+ </div>
+ );
+ }
+
+ if (isLoading || hasRows || error) {
+ return (
+ <div className="flex flex-col gap-4">
+ <Table {...tableProps} table={table} />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <ReferralsEmptyState
+ title="No referred partners"
+ description="Share your referral link to start earning from partners joining the Dub Network."
+ button={
+ <Button
+ text="Copy link"
+ icon={
+ copied ? (
+ <Check className="size-4" />
+ ) : (
+ <Copy className="size-4" />
+ )
+ }
+ onClick={copyReferralLink}
+ className="h-9"
+ />
+ }
+ />
+ </div>
+ );
+}
+
+function ReferralsPromoCard() {
+ const cards = [
+ {
+ containerClassName:
+ "absolute left-[calc(50%-122px)] top-[-36px] flex h-[156px] w-[236px] items-center justify-center sm:left-[8px] sm:translate-x-0 lg:left-[8px]",
+ transform: "rotate(-14deg) scaleY(0.99) skewX(7deg)",
+ },
+ {
+ containerClassName:
+ "absolute left-[calc(50%-60px)] top-[-20px] flex h-[125px] w-[220px] items-center justify-center sm:left-[68px] sm:translate-x-0 lg:left-[68px]",
+ transform: "rotate(-3.38deg) scaleY(0.99) skewX(7deg)",
+ },
+ {
+ containerClassName:
+ "absolute left-[calc(50%+12px)] top-[-30px] flex h-[161px] w-[207px] items-center justify-center sm:left-[151px] sm:translate-x-0 lg:left-[151px]",
+ transform: "rotate(13.59deg) scaleY(0.99) skewX(7deg)",
+ },
+ ] as const;
+
+ const cardShadow =
+ "-53px 97px 31px rgba(0,0,0,0.01), -34px 62px 28px rgba(0,0,0,0.06), -19px 35px 24px rgba(0,0,0,0.19), -8px 16px 18px rgba(0,0,0,0.32), -2px 4px 10px rgba(0,0,0,0.37)";
+
+ return (
+ <div className="relative isolate flex min-h-[280px] w-full flex-col justify-end overflow-hidden rounded-xl bg-neutral-800 p-5 lg:h-full lg:min-h-0">
+ <div
+ className="pointer-events-none absolute inset-0 overflow-visible"
+ aria-hidden
+ >
+ {cards.map(({ containerClassName, transform }, idx) => (
+ <div key={idx} className={containerClassName}>
+ <div className="flex-none origin-center" style={{ transform }}>
+ <div
+ className="relative h-[115px] w-[199px] overflow-hidden rounded-[6px]"
+ style={{ boxShadow: cardShadow }}
+ >
+ <Image
+ src="https://assets.dub.co/misc/network-referral-card.png"
+ alt=""
+ width={398}
+ height={230}
+ className="size-full object-cover"
+ loading="lazy"
+ />
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ <div className="relative z-[1] mt-auto space-y-2 pt-[88px] sm:pt-[84px]">
+ <p className="text-base font-semibold text-white">
+ Dub Network Referrals
+ </p>
+ <p className="text-sm font-normal text-neutral-200">
+ Bring on other partners to the Dub network, and earn from their
+ activity for up to {NETWORK_REFERRAL_REWARD.maxDuration} months.{" "}
+ <Link
+ href="https://dub.co/docs/partners/quickstart"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-neutral-200 underline decoration-neutral-400 underline-offset-2 hover:decoration-neutral-300"
+ >
+ Learn more
+ </Link>
+ </p>
+ </div>
+ </div>
+ );
+}
+
+export function NetworkReferralsPageClient() {
+ return (
+ <PageContent title="Referrals">
+ <PageWidthWrapper className="flex flex-col gap-6 pb-10">
+ <div className="rounded-xl bg-neutral-100 p-4">
+ <div className="flex flex-col gap-4">
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(268px,22rem)] lg:items-stretch">
+ <div className="order-2 flex min-h-0 flex-col gap-4 lg:order-1">
+ <ReferralsStats />
+ <ReferralLink />
+ </div>
+ <div className="order-1 lg:order-2">
+ <ReferralsPromoCard />
+ </div>
+ </div>
+ <ReferralRewards />
+ </div>
+ </div>
+ <ReferredPartners />
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/referrals/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/referrals/page.tsx
new file mode 100644
index 0000000000..5cb000a89c
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/referrals/page.tsx
@@ -0,0 +1,5 @@
+import { NetworkReferralsPageClient } from "./page-client";
+
+export default function NetworkReferralsPage() {
+ return <NetworkReferralsPageClient />;
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/onboarding-form.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/onboarding-form.tsx
index 019a14185c..73d2ebf426 100644
--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/onboarding-form.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/onboarding-form.tsx
@@ -7,15 +7,12 @@ import {
MAX_PARTNER_DESCRIPTION_LENGTH,
onboardPartnerSchema,
} from "@/lib/zod/schemas/partners";
-import { CountryCombobox } from "@/ui/partners/country-combobox";
-import { useCountryChangeWarningModal } from "@/ui/partners/use-country-change-warning-modal";
import { MaxCharactersCounter } from "@/ui/shared/max-characters-counter";
import { Partner } from "@dub/prisma/client";
import {
Button,
FileUpload,
ToggleGroup,
- TooltipContent,
useEnterSubmit,
useMediaQuery,
} from "@dub/ui";
@@ -40,7 +37,6 @@ export function OnboardingForm({
Partner,
| "name"
| "description"
- | "country"
| "image"
| "profileType"
| "companyName"
@@ -52,9 +48,7 @@ export function OnboardingForm({
const searchParams = useSearchParams();
const { isMobile } = useMediaQuery();
const [accountCreated, setAccountCreated] = useState(false);
- const [isCountryComboboxOpen, setIsCountryComboboxOpen] = useState(false);
const { data: session, update: refreshSession } = useSession();
- const countryChangeWarning = useCountryChangeWarningModal();
const {
register,
@@ -68,7 +62,6 @@ export function OnboardingForm({
defaultValues: {
name: partner?.name ?? undefined,
description: partner?.description ?? undefined,
- country: partner?.country ?? undefined,
image: partner?.image ?? undefined,
profileType: partner?.profileType ?? "individual",
companyName: partner?.companyName ?? undefined,
@@ -116,10 +109,10 @@ export function OnboardingForm({
return (
<form
ref={formRef}
+ method="post"
onSubmit={handleSubmit(async (data) => await executeAsync(data))}
className="flex w-full flex-col gap-6 text-left"
>
- {countryChangeWarning.modal}
<label>
<span className="text-sm font-medium text-neutral-800">Name</span>
<input
@@ -170,50 +163,6 @@ export function OnboardingForm({
</div>
</label>
- <label>
- <span className="text-sm font-medium text-neutral-800">Country</span>
- <Controller
- control={control}
- name="country"
- rules={{ required: true }}
- render={({ field }) => (
- <CountryCombobox
- {...field}
- error={errors.country ? true : false}
- open={isCountryComboboxOpen}
- onOpenChange={(open) => {
- if (!open) {
- setIsCountryComboboxOpen(false);
- return;
- }
-
- const shouldShowCountryChangeWarning =
- !partner?.payoutsEnabledAt;
-
- if (shouldShowCountryChangeWarning) {
- countryChangeWarning.acknowledgeAndContinue(() => {
- setIsCountryComboboxOpen(true);
- });
- return;
- }
-
- setIsCountryComboboxOpen(true);
- }}
- disabledTooltip={
- partner?.payoutsEnabledAt ? (
- <TooltipContent
- title="Since you've already connected your bank account for payouts, you cannot change your profile country."
- cta="Contact support"
- href="https://dub.co/support"
- target="_blank"
- />
- ) : undefined
- }
- />
- )}
- />
- </label>
-
<label>
<span className="text-sm font-medium text-neutral-800">
About you
diff --git a/apps/web/app/api/og/program/route.tsx b/apps/web/app/api/og/program/route.tsx
index bef58fa8e3..4cf9e6337a 100644
--- a/apps/web/app/api/og/program/route.tsx
+++ b/apps/web/app/api/og/program/route.tsx
@@ -39,6 +39,7 @@ export async function GET(req: NextRequest) {
clickReward: true,
saleReward: true,
leadReward: true,
+ referralReward: true,
},
},
},
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/commissions-analytics-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/commissions-analytics-chart.tsx
index 4ff81f9060..140e14dc3b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/commissions-analytics-chart.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/commissions-analytics-chart.tsx
@@ -2,6 +2,7 @@
import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
import useCommissionAnalytics from "@/lib/swr/use-commission-analytics";
+import { LoadingSpinner, useRouterStuff } from "@dub/ui";
import {
Areas,
ChartContext,
@@ -9,7 +10,6 @@ import {
XAxis,
YAxis,
} from "@dub/ui/charts";
-import { LoadingSpinner, useRouterStuff } from "@dub/ui";
import { currencyFormatter, nFormatter } from "@dub/utils";
import { LinearGradient } from "@visx/gradient";
import { useId } from "react";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
index 85259fe615..4173b04b05 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
@@ -549,7 +549,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
<TooltipContent
title="[Social metrics bounties](https://dub.co/help/article/program-bounties#social-metrics-bounties) are only available on the Advanced plan and above."
cta="Upgrade to Advanced"
- href={`/${workspaceSlug}/upgrade?showPartnersUpgradeModal=true`}
+ href={`/${workspaceSlug}/upgrade?plan=advanced&showPartnersUpgradeModal=true`}
target="_blank"
/>
) : (
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
index 283f25b512..9d3d28251b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
@@ -177,7 +177,7 @@ function ConfirmCreateBountyModal({
<TooltipContent
title="New bounty notifications are only available on Advanced plans and above."
cta="Upgrade to Advanced"
- href={`/${workspaceSlug}/upgrade?showPartnersUpgradeModal=true`}
+ href={`/${workspaceSlug}/upgrade?plan=advanced&showPartnersUpgradeModal=true`}
target="_blank"
/>
),
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page.tsx
index 8403f9a507..a64188b803 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/[commissionId]/page.tsx
@@ -11,7 +11,10 @@ import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { CommissionTypeIcon } from "@/ui/partners/comission-type-icon";
import { CommissionRowMenu } from "@/ui/partners/commission-row-menu";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
-import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
+import {
+ CommissionTypeBadge,
+ getCommissionTypeLabel,
+} from "@/ui/partners/commission-type-badge";
import { useEditCommissionModal } from "@/ui/partners/edit-commission-modal";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
@@ -151,11 +154,7 @@ function CommissionDetailsContent({
</Link>
) : (
<span className="min-w-0 max-w-[13rem] truncate text-xs font-medium text-neutral-700">
- {row.original.type === "click"
- ? `${row.original.quantity} ${pluralize("click", row.original.quantity)}`
- : customer
- ? customer.email || customer.name
- : "Custom commission"}
+ {getCommissionTypeLabel(row.original)}
</span>
)}
<span className="text-xs text-neutral-500">
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
index eca6c6c57c..6e21a31a05 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
@@ -1,17 +1,25 @@
"use client";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useGroup from "@/lib/swr/use-group";
+import useWorkspace from "@/lib/swr/use-workspace";
import type { GroupProps, RewardProps } from "@/lib/types";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import { useRewardHistorySheet } from "@/ui/activity-logs/reward-history-sheet";
-import { REWARD_EVENTS } from "@/ui/partners/constants";
+import { usePartnersUpgradeModal } from "@/ui/partners/partners-upgrade-modal";
import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";
import {
RewardSheet,
useRewardSheet,
} from "@/ui/partners/rewards/add-edit-reward-sheet";
+import { REWARD_EVENT_ICON } from "@/ui/partners/rewards/reward-event-icon";
import { EventType } from "@dub/prisma/client";
-import { Button, TimestampTooltip, useRouterStuff } from "@dub/ui";
+import {
+ Button,
+ TimestampTooltip,
+ TooltipContent,
+ useRouterStuff,
+} from "@dub/ui";
import { cn, formatDate } from "@dub/utils";
import Link from "next/link";
import { useParams } from "next/navigation";
@@ -33,6 +41,10 @@ const REWARD_EVENT_DESCRIPTIONS: Record<
title: "Click reward",
description: "Reward for traffic and reach",
},
+ referral: {
+ title: "Partner referral reward",
+ description: "Reward when partners refer more partners",
+ },
};
export function GroupRewards() {
@@ -54,9 +66,12 @@ export function GroupRewards() {
}, [searchParams]);
const rewards =
- [group?.clickReward, group?.leadReward, group?.saleReward].filter(
- Boolean,
- ) ?? [];
+ [
+ group?.clickReward,
+ group?.leadReward,
+ group?.saleReward,
+ group?.referralReward,
+ ].filter(Boolean) ?? [];
const currentReward = rewardSheetState.rewardId
? rewards.find((r) => r?.id === rewardSheetState.rewardId)
@@ -82,9 +97,9 @@ export function GroupRewards() {
<div className="flex flex-col gap-6">
{loading || !group ? (
<>
- <RewardSkeleton />
- <RewardSkeleton />
- <RewardSkeleton />
+ {Array.from({ length: 4 }).map((_, index) => (
+ <RewardSkeleton key={index} />
+ ))}
</>
) : (
<>
@@ -95,6 +110,14 @@ export function GroupRewards() {
event="click"
group={group}
/>
+
+ <hr className="border-neutral-200" />
+
+ <RewardItem
+ reward={group.referralReward}
+ event="referral"
+ group={group}
+ />
</>
)}
</div>
@@ -133,7 +156,11 @@ const RewardItem = ({
group: GroupProps;
}) => {
const { slug } = useParams();
+ const { plan } = useWorkspace();
const { queryParams } = useRouterStuff();
+ const { canCreateReferralReward } = getPlanCapabilities(plan);
+ const { partnersUpgradeModal, setShowPartnersUpgradeModal } =
+ usePartnersUpgradeModal();
const { RewardSheet, setIsOpen } = useRewardSheet({
event,
@@ -149,18 +176,21 @@ const RewardItem = ({
reward: reward ?? null,
});
- const Icon = REWARD_EVENTS[event].icon;
+ const Icon = REWARD_EVENT_ICON[event];
const As = reward ? Link : "div";
+ const lastUpdatedDate = finalActivityLogDate ?? reward?.updatedAt;
+
return (
<>
+ {partnersUpgradeModal}
{RewardSheet}
{rewardHistorySheet}
<As
href={
reward
? `/${slug}/program/groups/${group.slug}/rewards?rewardId=${reward.id}`
- : ""
+ : "#"
}
scroll={false}
className={cn(
@@ -186,16 +216,16 @@ const RewardItem = ({
<div className="flex items-center gap-1 text-xs font-medium text-neutral-500">
<span>Last updated </span>
- {!finalActivityLogDate ? (
+ {!lastUpdatedDate ? (
<div className="h-3 w-16 animate-pulse rounded bg-neutral-100" />
) : (
<TimestampTooltip
- timestamp={finalActivityLogDate ?? reward.updatedAt}
+ timestamp={lastUpdatedDate}
side="left"
rows={["local", "utc", "unix"]}
>
<span>
- {formatDate(finalActivityLogDate, {
+ {formatDate(lastUpdatedDate, {
month: "short",
day: "numeric",
year: "numeric",
@@ -256,13 +286,23 @@ const RewardItem = ({
/>
) : (
<div className="flex flex-col-reverse items-center gap-2 md:flex-row">
- {group.slug !== DEFAULT_PARTNER_GROUP.slug && (
- <CopyDefaultRewardButton event={event} />
- )}
+ {group.slug !== DEFAULT_PARTNER_GROUP.slug &&
+ (event !== "referral" || canCreateReferralReward) && (
+ <CopyDefaultRewardButton event={event} />
+ )}
<Button
text="Create"
variant="primary"
className="h-9 w-full rounded-lg md:w-fit"
+ disabledTooltip={
+ event === "referral" && !canCreateReferralReward ? (
+ <TooltipContent
+ title="Referral rewards are only available on the Advanced plan and above."
+ cta="Upgrade to Advanced"
+ onClick={() => setShowPartnersUpgradeModal(true)}
+ />
+ ) : undefined
+ }
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx
index 78da748cb3..90c36a9a46 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx
@@ -1,9 +1,12 @@
"use client";
+import { usePartnerReferral } from "@/lib/partner-referrals/hooks/use-partner-referral";
+import { constructPartnerReferralLink } from "@/lib/partner-referrals/utils";
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import useDiscountCodes from "@/lib/swr/use-discount-codes";
import useGroup from "@/lib/swr/use-group";
import usePartner from "@/lib/swr/use-partner";
+import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import {
DiscountCodeProps,
@@ -38,6 +41,7 @@ export default function ProgramPartnerLinksPage() {
<div className="grid gap-4">
<PartnerLinks partner={partner} />
<PartnerDiscountCodes partner={partner} />
+ <PartnerReferralLink partner={partner} />
</div>
) : (
<div className="flex justify-center py-16">
@@ -179,6 +183,108 @@ const PartnerLinks = ({ partner }: { partner: EnrolledPartnerProps }) => {
);
};
+const PartnerReferralLink = ({
+ partner,
+}: {
+ partner: EnrolledPartnerProps;
+}) => {
+ const {
+ program,
+ loading: loadingProgram,
+ error: errorProgram,
+ } = useProgram();
+ const {
+ referral,
+ loading: loadingReferral,
+ error: referralError,
+ } = usePartnerReferral({
+ partnerId: partner.id,
+ });
+
+ const referralLink = constructPartnerReferralLink({
+ partner,
+ program,
+ });
+
+ const data = useMemo(() => {
+ if (!referralLink || !referral?.stats) {
+ return [];
+ }
+
+ return [
+ {
+ link: referralLink,
+ totalPartners: referral.stats.totalPartners,
+ totalConversions: referral.stats.totalConversions,
+ totalSaleAmount: referral.stats.totalSaleAmount,
+ },
+ ];
+ }, [referralLink, referral]);
+
+ const table = useTable({
+ data,
+ columns: [
+ {
+ id: "link",
+ header: "Link",
+ cell: ({ row }) => (
+ <div className="flex items-center gap-3">
+ <span className="font-medium text-black">
+ {getPrettyUrl(row.original.link)}
+ </span>
+ <CopyButton value={row.original.link} className="p-0.5" />
+ </div>
+ ),
+ },
+ {
+ header: "Partners",
+ size: 1,
+ minSize: 1,
+ cell: ({ row }) => nFormatter(row.original.totalPartners),
+ },
+ {
+ header: "Conversions",
+ size: 1,
+ minSize: 1,
+ cell: ({ row }) => nFormatter(row.original.totalConversions),
+ },
+ {
+ header: "Revenue",
+ size: 1,
+ minSize: 1,
+ cell: ({ row }) =>
+ currencyFormatter(row.original.totalSaleAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ }),
+ },
+ ],
+ resourceName: (p) => `link${p ? "s" : ""}`,
+ thClassName: (id) =>
+ cn(id === "total" && "[&>div]:justify-end", "border-l-0"),
+ tdClassName: (id) => cn(id === "total" && "text-right", "border-l-0"),
+ className: "[&_tr:last-child>td]:border-b-transparent",
+ scrollWrapperClassName: "min-h-[40px]",
+ loading: loadingReferral || loadingProgram,
+ error:
+ referralError || errorProgram
+ ? "Failed to load partner referral data"
+ : undefined,
+ });
+
+ if (!partner?.referralRewardId) {
+ return null;
+ }
+
+ return (
+ <>
+ <h2 className="text-content-emphasis text-lg font-semibold">
+ Partner referral link
+ </h2>
+ <Table {...table} />
+ </>
+ );
+};
+
const PartnerDiscountCodes = ({
partner,
}: {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/use-partner-filters.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/use-partner-filters.tsx
index e3538b4f1b..bea99d3231 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/use-partner-filters.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/use-partner-filters.tsx
@@ -1,9 +1,10 @@
import useGroups from "@/lib/swr/use-groups";
import { usePartnerTags } from "@/lib/swr/use-partner-tags";
import { usePartnerTagsCount } from "@/lib/swr/use-partner-tags-count";
+import usePartners from "@/lib/swr/use-partners";
import usePartnersCount from "@/lib/swr/use-partners-count";
import useWorkspace from "@/lib/swr/use-workspace";
-import { PartnerTagProps } from "@/lib/types";
+import { EnrolledPartnerProps, PartnerTagProps } from "@/lib/types";
import { PARTNER_TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/partner-tags";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
@@ -18,6 +19,7 @@ import {
MarketingTarget,
MoneyBills2,
Tag,
+ UserArrowLeft,
UserPlus,
Users6,
} from "@dub/ui/icons";
@@ -27,6 +29,7 @@ import {
COUNTRIES,
currencyFormatter,
nFormatter,
+ OG_AVATAR_URL,
parseFilterValue,
type FilterOperator,
type ParsedFilter,
@@ -34,7 +37,7 @@ import {
import { useCallback, useMemo, useState } from "react";
import { useDebounce } from "use-debounce";
-const SINGLE_VALUE_FILTER_KEYS = ["status"] as const;
+const SINGLE_VALUE_FILTER_KEYS = ["status", "referredByPartnerId"] as const;
const MULTI_VALUE_FILTER_KEYS = ["partnerTagId", "groupId", "country"] as const;
function buildMultiValueParam(
@@ -144,6 +147,7 @@ export type PartnerFilterKey =
| "partnerTagId"
| "status"
| "country"
+ | "referredByPartnerId"
| (typeof PARTNER_METRIC_RANGE)[number]["filterKey"];
export function usePartnerFilters(
@@ -153,6 +157,7 @@ export function usePartnerFilters(
"partnerTagId",
"status",
"country",
+ "referredByPartnerId",
"totalClicks",
"totalLeads",
"totalConversions",
@@ -227,6 +232,32 @@ export function usePartnerFilters(
enabled: enabledFilters.includes("groupId"),
});
+ const { partnersCount: referredByCount } = usePartnersCount<
+ | {
+ referredByPartnerId: string;
+ _count: number;
+ }[]
+ | undefined
+ >({
+ groupBy: "referredByPartnerId",
+ status,
+ ...cohortParams,
+ enabled: enabledFilters.includes("referredByPartnerId"),
+ });
+
+ const { referredByPartners } = useReferredByPartnerFilterOptions({
+ search: selectedFilter === "referredByPartnerId" ? debouncedSearch : "",
+ enabled: enabledFilters.includes("referredByPartnerId"),
+ });
+
+ const referredByCountMap = useMemo(
+ () =>
+ new Map(
+ referredByCount?.map((r) => [r.referredByPartnerId, r._count]) ?? [],
+ ),
+ [referredByCount],
+ );
+
const filters = useMemo(
() => [
...(enabledFilters.includes("groupId")
@@ -315,13 +346,6 @@ export function usePartnerFilters(
key: "country",
icon: FlagWavy,
label: "Location",
- separatorAfter: PARTNER_METRIC_RANGE.some((m) =>
- enabledFilters.includes(m.filterKey),
- ),
- getOptionIcon: (value: string) => (
- <CountryFlag countryCode={value} />
- ),
- getOptionLabel: (value: string) => COUNTRIES[value],
options:
countriesCount
?.filter(({ country }) => COUNTRIES[country])
@@ -330,6 +354,41 @@ export function usePartnerFilters(
label: COUNTRIES[country],
right: nFormatter(_count, { full: true }),
})) ?? [],
+ getOptionIcon: (value: string) => (
+ <CountryFlag countryCode={value} />
+ ),
+ getOptionLabel: (value: string) => COUNTRIES[value],
+ },
+ ]
+ : []),
+ ...(enabledFilters.includes("referredByPartnerId")
+ ? [
+ {
+ key: "referredByPartnerId",
+ icon: UserArrowLeft,
+ label: "Referred by",
+ shouldFilter: false,
+ separatorAfter: PARTNER_METRIC_RANGE.some((m) =>
+ enabledFilters.includes(m.filterKey),
+ ),
+ options:
+ referredByPartners?.map(({ id, name, image }) => {
+ const count = referredByCountMap.get(id);
+ return {
+ value: id,
+ label: name,
+ icon: (
+ <img
+ src={image || `${OG_AVATAR_URL}${id}`}
+ alt={`${name} avatar`}
+ className="size-4 rounded-full"
+ />
+ ),
+ ...(count !== undefined && {
+ right: nFormatter(count, { full: true }),
+ }),
+ };
+ }) ?? null,
},
]
: []),
@@ -386,6 +445,8 @@ export function usePartnerFilters(
partnerTagsAsync,
statusCount,
countriesCount,
+ referredByPartners,
+ referredByCountMap,
],
);
@@ -554,6 +615,7 @@ export function usePartnerFilters(
"country",
"groupId",
"partnerTagId",
+ "referredByPartnerId",
"search",
"totalClicksMin",
"totalClicksMax",
@@ -697,3 +759,53 @@ function usePartnerTagFilterOptions({
return { partnerTags: tagsResult, partnerTagsAsync: useAsync };
}
+
+function useReferredByPartnerFilterOptions({
+ search,
+ enabled = true,
+}: {
+ search: string;
+ enabled?: boolean;
+}) {
+ const { searchParamsObj } = useRouterStuff();
+
+ const { partners, loading: partnersLoading } = usePartners({
+ query: { search },
+ enabled,
+ });
+
+ const { partners: selectedPartners } = usePartners({
+ query: {
+ partnerIds: searchParamsObj.referredByPartnerId
+ ? [searchParamsObj.referredByPartnerId]
+ : undefined,
+ },
+ enabled: enabled && !!searchParamsObj.referredByPartnerId,
+ });
+
+ const result = useMemo(() => {
+ if (
+ partnersLoading ||
+ (searchParamsObj.referredByPartnerId &&
+ ![...(selectedPartners ?? []), ...(partners ?? [])].some(
+ (p) => p.id === searchParamsObj.referredByPartnerId,
+ ))
+ ) {
+ return null;
+ }
+
+ return [
+ ...(partners ?? []),
+ ...(selectedPartners
+ ?.filter((sp) => !partners?.some((p) => p.id === sp.id))
+ ?.map((sp) => ({ ...sp, hideDuringSearch: true })) ?? []),
+ ] as (EnrolledPartnerProps & { hideDuringSearch?: boolean })[];
+ }, [
+ partnersLoading,
+ partners,
+ selectedPartners,
+ searchParamsObj.referredByPartnerId,
+ ]);
+
+ return { referredByPartners: result };
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx
index bcecd41071..7c1807bfc3 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx
@@ -16,7 +16,10 @@ import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { ActivityEvent } from "@/ui/partners/activity-event";
import { CommissionTypeIcon } from "@/ui/partners/comission-type-icon";
import { CommissionRowMenu } from "@/ui/partners/commission-row-menu";
-import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
+import {
+ CommissionTypeBadge,
+ getCommissionTypeLabel,
+} from "@/ui/partners/commission-type-badge";
import { PartnerAvatar } from "@/ui/partners/partner-avatar";
import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
import { ConditionalLink } from "@/ui/shared/conditional-link";
@@ -43,7 +46,6 @@ import {
fetcher,
formatDateTime,
formatDateTimeSmart,
- pluralize,
} from "@dub/utils";
import { formatPeriod } from "@dub/utils/src/functions/datetime";
import Link from "next/link";
@@ -334,9 +336,7 @@ function PayoutDetailsContent({
</Link>
) : (
<span className="max-w-xs truncate text-sm text-neutral-700">
- {row.original.type === "click"
- ? `${row.original.quantity} ${pluralize("click", row.original.quantity)}`
- : "Custom commission"}
+ {getCommissionTypeLabel(row.original)}
</span>
)}
<span className="text-xs text-neutral-500">
diff --git a/apps/web/lib/actions/partners/ban-partner.ts b/apps/web/lib/actions/partners/ban-partner.ts
index 308d95cd65..8bee70b202 100644
--- a/apps/web/lib/actions/partners/ban-partner.ts
+++ b/apps/web/lib/actions/partners/ban-partner.ts
@@ -102,6 +102,7 @@ export const banPartner = async ({
clickRewardId: null,
leadRewardId: null,
saleRewardId: null,
+ referralRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/actions/partners/bulk-approve-partners.ts b/apps/web/lib/actions/partners/bulk-approve-partners.ts
index 58d563d23d..e52dafae35 100644
--- a/apps/web/lib/actions/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-approve-partners.ts
@@ -66,6 +66,7 @@ export const bulkApprovePartnersAction = authActionClient
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/lib/actions/partners/bulk-ban-partners.ts b/apps/web/lib/actions/partners/bulk-ban-partners.ts
index e8a41b51b9..2ba8c12331 100644
--- a/apps/web/lib/actions/partners/bulk-ban-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-ban-partners.ts
@@ -71,6 +71,7 @@ export const bulkBanPartnersAction = authActionClient
clickRewardId: null,
leadRewardId: null,
saleRewardId: null,
+ referralRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/actions/partners/bulk-invite-partners.ts b/apps/web/lib/actions/partners/bulk-invite-partners.ts
index a1b4e8d632..5998e75744 100644
--- a/apps/web/lib/actions/partners/bulk-invite-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-invite-partners.ts
@@ -134,6 +134,7 @@ export const bulkInvitePartnersAction = authActionClient
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
})),
skipDuplicates: true,
diff --git a/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts b/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts
index 27f4700c88..d0ef854b40 100644
--- a/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts
+++ b/apps/web/lib/actions/partners/bulk-reject-partner-applications.ts
@@ -64,6 +64,7 @@ export const bulkRejectPartnerApplicationsAction = authActionClient
clickRewardId: null,
leadRewardId: null,
saleRewardId: null,
+ referralRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.ts
index a331cf5e3e..a8a938c23b 100644
--- a/apps/web/lib/actions/partners/create-program-application.ts
+++ b/apps/web/lib/actions/partners/create-program-application.ts
@@ -321,6 +321,7 @@ async function createApplicationAndEnrollment({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
}),
diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.ts
index 1647779213..6cecfa9873 100644
--- a/apps/web/lib/actions/partners/create-reward.ts
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -31,6 +31,7 @@ export const createRewardAction = authActionClient
description,
tooltipDescription,
modifiers,
+ config,
groupId,
} = parsedInput;
@@ -40,7 +41,14 @@ export const createRewardAction = authActionClient
});
const programId = getDefaultProgramIdOrThrow(workspace);
- const { canUseAdvancedRewardLogic } = getPlanCapabilities(workspace.plan);
+ const { canUseAdvancedRewardLogic, canCreateReferralReward } =
+ getPlanCapabilities(workspace.plan);
+
+ if (event === "referral" && !canCreateReferralReward) {
+ throw new Error(
+ "Referral rewards are only available on the Advanced plan and above.",
+ );
+ }
if (modifiers && !canUseAdvancedRewardLogic) {
throw new Error(
@@ -74,6 +82,7 @@ export const createRewardAction = authActionClient
description: description || null,
tooltipDescription: tooltipDescription || null,
modifiers: modifiers || Prisma.DbNull,
+ config: config ?? Prisma.DbNull,
...(type === "flat"
? {
amountInCents,
diff --git a/apps/web/lib/actions/partners/generate-lander.ts b/apps/web/lib/actions/partners/generate-lander.ts
index 2de53f4157..7f30c5097d 100644
--- a/apps/web/lib/actions/partners/generate-lander.ts
+++ b/apps/web/lib/actions/partners/generate-lander.ts
@@ -51,8 +51,9 @@ export const generateLanderAction = authActionClient
},
include: {
clickReward: true,
- saleReward: true,
leadReward: true,
+ saleReward: true,
+ referralReward: true,
discount: true,
},
},
diff --git a/apps/web/lib/actions/partners/onboard-partner.ts b/apps/web/lib/actions/partners/onboard-partner.ts
index b507f9d5d6..44264c5709 100644
--- a/apps/web/lib/actions/partners/onboard-partner.ts
+++ b/apps/web/lib/actions/partners/onboard-partner.ts
@@ -1,6 +1,9 @@
"use server";
import { createId } from "@/lib/api/create-id";
+import { isCI, isLocalDev } from "@/lib/api/environment";
+import { generatePartnerUsername } from "@/lib/api/partners/generate-partner-username";
+import { markApplicationEventSubmittedNetwork } from "@/lib/application-events/mark-application-event-submitted-network";
import { completeProgramApplications } from "@/lib/partners/complete-program-applications";
import { storage } from "@/lib/storage";
import { onboardPartnerSchema } from "@/lib/zod/schemas/partners";
@@ -8,6 +11,7 @@ import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { headers } from "next/headers";
import { authUserActionClient } from "../safe-action";
// Onboard a new partner:
@@ -17,7 +21,7 @@ export const onboardPartnerAction = authUserActionClient
.inputSchema(onboardPartnerSchema)
.action(async ({ ctx, parsedInput }) => {
const { user } = ctx;
- const { name, image, country, description, profileType } = parsedInput;
+ const { name, image, description, profileType, companyName } = parsedInput;
const existingPartner = await prisma.partner.findUnique({
where: {
@@ -25,8 +29,10 @@ export const onboardPartnerAction = authUserActionClient
},
select: {
id: true,
+ username: true,
country: true,
profileType: true,
+ companyName: true,
},
});
@@ -43,13 +49,26 @@ export const onboardPartnerAction = authUserActionClient
.then(({ url }) => url)
: undefined;
- // country, profileType, and companyName cannot be changed once set
+ const username = existingPartner?.username
+ ? undefined
+ : await generatePartnerUsername({
+ name,
+ email: user.email,
+ });
+
+ const headerList = await headers();
+ const country =
+ headerList.get("x-vercel-ip-country") ??
+ (isLocalDev || isCI ? "US" : undefined);
+
const payload: Prisma.PartnerCreateInput = {
name: name || user.email,
email: user.email,
+ ...(username && { username }),
// can only update these fields if it's not already set (else you need to update under profile settings)
...(existingPartner?.country ? {} : { country }),
...(existingPartner?.profileType ? {} : { profileType }),
+ ...(existingPartner?.companyName ? {} : { companyName }),
...(description && { description }),
image: imageUrl,
users: {
@@ -71,7 +90,7 @@ export const onboardPartnerAction = authUserActionClient
},
};
- await Promise.all([
+ const [updatedPartner] = await Promise.all([
existingPartner
? prisma.partner.update({
where: {
@@ -98,8 +117,15 @@ export const onboardPartnerAction = authUserActionClient
}),
]);
- // Complete any outstanding program application
- waitUntil(completeProgramApplications(user.email));
+ waitUntil(
+ Promise.allSettled([
+ // Complete any outstanding program application
+ completeProgramApplications(user.email),
+
+ // Mark the application event as submitted for the `network` program
+ markApplicationEventSubmittedNetwork(updatedPartner),
+ ]),
+ );
// if the user doesn't have an image, set the uploaded image as the user's image
if (!user.image && image) {
diff --git a/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts b/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
index 22e56a5d84..222ffd5855 100644
--- a/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
+++ b/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
@@ -8,6 +8,7 @@ export async function triggerAggregateDueCommissionsCronJob(programId: string) {
programId,
},
});
+
console.log(
`Triggered aggregate due commissions cron job for program ${programId}: ${prettyPrint(qstashResponse)}`,
);
diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.ts
index 7de5a02147..47bf3fd520 100644
--- a/apps/web/lib/actions/partners/update-partner-profile.ts
+++ b/apps/web/lib/actions/partners/update-partner-profile.ts
@@ -1,11 +1,12 @@
"use server";
+import { DubApiError } from "@/lib/api/errors";
import { confirmEmailChange } from "@/lib/auth/confirm-email-change";
import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";
import { qstash } from "@/lib/cron";
import { isReservedUsername } from "@/lib/edge-config";
import { storage } from "@/lib/storage";
-import { stripe } from "@/lib/stripe";
+import { ratelimit } from "@/lib/upstash";
import { partnerProfileChangeHistoryLogSchema } from "@/lib/zod/schemas/partner-profile";
import {
MAX_PARTNER_DESCRIPTION_LENGTH,
@@ -15,7 +16,6 @@ import { prisma } from "@dub/prisma";
import { Partner, PartnerProfileType } from "@dub/prisma/client";
import {
APP_DOMAIN_WITH_NGROK,
- COUNTRIES,
deepEqual,
nanoid,
PARTNERS_DOMAIN,
@@ -34,7 +34,6 @@ const updatePartnerProfileSchema = z
username: z.string().trim().toLowerCase().min(3).max(100).optional(),
image: uploadedImageSchema.nullish(),
description: z.string().max(MAX_PARTNER_DESCRIPTION_LENGTH).nullish(),
- country: z.enum(Object.keys(COUNTRIES) as [string, ...string[]]).nullish(),
profileType: z.enum(PartnerProfileType).optional(),
companyName: z.string().nullish(),
})
@@ -73,7 +72,6 @@ export const updatePartnerProfileAction = authPartnerActionClient
email: newEmail,
image,
description,
- country,
profileType,
companyName,
monthlyTraffic,
@@ -102,12 +100,26 @@ export const updatePartnerProfileAction = authPartnerActionClient
}
if (username && username !== partner.username) {
+ const { success } = await ratelimit(5, "1 h").limit(
+ `partner-profile:username-update:${partner.id}`,
+ );
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message:
+ "You've updated your username too many times. Please try again later.",
+ });
+ }
+
if (!validSlugRegex.test(username) || RESERVED_SLUGS.includes(username)) {
throw new Error("Invalid username");
}
+
if (await isReservedUsername(username)) {
throw new Error("Invalid username");
}
+
const existingPartner = await prisma.partner.findUnique({
where: {
username,
@@ -132,7 +144,6 @@ export const updatePartnerProfileAction = authPartnerActionClient
description,
...(imageUrl && { image: imageUrl }),
username,
- country,
profileType,
companyName,
monthlyTraffic,
@@ -235,49 +246,18 @@ const updatedComplianceFieldsChecks = async ({
partner: Partner;
input: z.infer<typeof updatePartnerProfileSchema>;
}) => {
- const countryChanged =
- input.country !== undefined &&
- partner.country?.toLowerCase() !== input.country?.toLowerCase();
-
const profileTypeChanged =
input.profileType !== undefined &&
partner.profileType.toLowerCase() !== input.profileType.toLowerCase();
- if (!countryChanged && !profileTypeChanged) {
+ if (!profileTypeChanged) {
return;
}
- if (partner.payoutsEnabledAt) {
- throw new Error(
- "Since you've already connected your bank account for payouts, you cannot change your country or profile type. Please contact support to update those fields.",
- );
- }
-
const partnerChangeHistoryLog = partner.changeHistoryLog
? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)
: [];
- if (countryChanged) {
- partnerChangeHistoryLog.push({
- field: "country",
- from: partner.country as string,
- to: input.country as string,
- changedAt: new Date(),
- });
-
- // if there was an existing veriff session, trigger a country change verification
- if (partner.veriffSessionId) {
- waitUntil(
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/verify-country-change`,
- body: {
- partnerId: partner.id,
- },
- }),
- );
- }
- }
-
if (profileTypeChanged) {
partnerChangeHistoryLog.push({
field: "profileType",
@@ -287,16 +267,11 @@ const updatedComplianceFieldsChecks = async ({
});
}
- if (partner.stripeConnectId) {
- await stripe.accounts.del(partner.stripeConnectId);
- }
-
await prisma.partner.update({
where: {
id: partner.id,
},
data: {
- stripeConnectId: null,
changeHistoryLog: partnerChangeHistoryLog,
},
});
diff --git a/apps/web/lib/actions/partners/update-reward.ts b/apps/web/lib/actions/partners/update-reward.ts
index 6027aa92bc..28fdbea2e1 100644
--- a/apps/web/lib/actions/partners/update-reward.ts
+++ b/apps/web/lib/actions/partners/update-reward.ts
@@ -27,6 +27,7 @@ export const updateRewardAction = authActionClient
description,
tooltipDescription,
modifiers,
+ config,
rewardId,
} = parsedInput;
@@ -42,7 +43,14 @@ export const updateRewardAction = authActionClient
programId,
});
- const { canUseAdvancedRewardLogic } = getPlanCapabilities(workspace.plan);
+ const { canUseAdvancedRewardLogic, canCreateReferralReward } =
+ getPlanCapabilities(workspace.plan);
+
+ if (reward.event === "referral" && !canCreateReferralReward) {
+ throw new Error(
+ "Referral rewards are only available on the Advanced plan and above.",
+ );
+ }
if (modifiers && !canUseAdvancedRewardLogic) {
throw new Error(
@@ -65,6 +73,7 @@ export const updateRewardAction = authActionClient
description: description || null,
tooltipDescription: tooltipDescription || null,
modifiers: modifiers === null ? Prisma.DbNull : modifiers,
+ config: config === null ? Prisma.DbNull : config,
...(type === "flat"
? {
amountInCents,
@@ -80,6 +89,7 @@ export const updateRewardAction = authActionClient
clickPartnerGroup: true,
leadPartnerGroup: true,
salePartnerGroup: true,
+ referralPartnerGroup: true,
},
});
@@ -88,6 +98,7 @@ export const updateRewardAction = authActionClient
clickPartnerGroup,
leadPartnerGroup,
salePartnerGroup,
+ referralPartnerGroup,
...rewardMetadata
} = updatedReward;
@@ -95,11 +106,15 @@ export const updateRewardAction = authActionClient
clickPartnerGroup,
leadPartnerGroup,
salePartnerGroup,
+ referralPartnerGroup,
].some((group) => group?.slug === "default");
// Determine the groupId from the partner group relation
const partnerGroup =
- clickPartnerGroup || leadPartnerGroup || salePartnerGroup;
+ clickPartnerGroup ||
+ leadPartnerGroup ||
+ salePartnerGroup ||
+ referralPartnerGroup;
waitUntil(
Promise.allSettled([
diff --git a/apps/web/lib/api/activity-log/get-resource-diff.ts b/apps/web/lib/api/activity-log/get-resource-diff.ts
index 3ab4251791..9ce6f1f08e 100644
--- a/apps/web/lib/api/activity-log/get-resource-diff.ts
+++ b/apps/web/lib/api/activity-log/get-resource-diff.ts
@@ -30,13 +30,15 @@ export const getResourceDiff = (
): ResourceDiff | null => {
const { fields } = options ?? {};
- const diffpatcher = jsondiffpatch.create({
- propertyFilter: fields
- ? (name: string) => fields.includes(name)
- : undefined,
- });
+ const filteredOld = fields
+ ? Object.fromEntries(fields.map((f) => [f, oldResource[f]]))
+ : oldResource;
- const delta = diffpatcher.diff(oldResource, newResource);
+ const filteredNew = fields
+ ? Object.fromEntries(fields.map((f) => [f, newResource[f]]))
+ : newResource;
+
+ const delta = jsondiffpatch.diff(filteredOld, filteredNew);
if (!delta) {
return null;
@@ -48,8 +50,8 @@ export const getResourceDiff = (
if (!Array.isArray(value)) {
// Nested object change - store as-is
result[key] = {
- old: oldResource[key],
- new: newResource[key],
+ old: filteredOld[key],
+ new: filteredNew[key],
};
} else if (value.length === 2) {
// Modified: [oldValue, newValue]
diff --git a/apps/web/lib/api/activity-log/track-reward-activity-log.ts b/apps/web/lib/api/activity-log/track-reward-activity-log.ts
index 7ec069c752..10afc900ba 100644
--- a/apps/web/lib/api/activity-log/track-reward-activity-log.ts
+++ b/apps/web/lib/api/activity-log/track-reward-activity-log.ts
@@ -25,6 +25,7 @@ function toRewardActivitySnapshot(reward: RewardProps) {
description: reward.description ?? null,
tooltipDescription: reward.tooltipDescription ?? null,
modifiers: reward.modifiers ?? null,
+ config: reward.config ?? null,
};
}
@@ -175,6 +176,7 @@ export function trackRewardActivityLog({
"maxDuration",
"description",
"tooltipDescription",
+ "config",
],
});
diff --git a/apps/web/lib/api/groups/get-group-or-throw.ts b/apps/web/lib/api/groups/get-group-or-throw.ts
index 34027f060e..794ae9f397 100644
--- a/apps/web/lib/api/groups/get-group-or-throw.ts
+++ b/apps/web/lib/api/groups/get-group-or-throw.ts
@@ -30,6 +30,7 @@ export const getGroupOrThrow = async ({
clickReward: includeExpandedFields,
leadReward: includeExpandedFields,
saleReward: includeExpandedFields,
+ referralReward: includeExpandedFields,
discount: includeExpandedFields,
utmTemplate: includeExpandedFields,
partnerGroupDefaultLinks: includeExpandedFields,
diff --git a/apps/web/lib/api/groups/move-partners-to-group.ts b/apps/web/lib/api/groups/move-partners-to-group.ts
index 9adb02be23..f2c080cdc3 100644
--- a/apps/web/lib/api/groups/move-partners-to-group.ts
+++ b/apps/web/lib/api/groups/move-partners-to-group.ts
@@ -27,6 +27,7 @@ interface MovePartnersToGroupParams {
| "clickRewardId"
| "leadRewardId"
| "saleRewardId"
+ | "referralRewardId"
| "discountId"
>;
isGroupDeleted?: boolean;
@@ -84,6 +85,7 @@ export async function movePartnersToGroup({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
...(groupMoveDisabledAt !== undefined && { groupMoveDisabledAt }),
},
diff --git a/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts b/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts
index 88b4b3c8ac..3cae672afa 100644
--- a/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts
+++ b/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts
@@ -83,16 +83,23 @@ export async function getEarningsForPartner(
// fallback to a random name if the customer doesn't have an email
const customerEmail =
e.customer?.email || e.customer?.name || generateRandomName();
+
+ // For referral commissions, the customer belongs to the referred partner,
+ // not the partner fetching their earnings — so hide the customer details.
+ const belongsToSamePartner = e.customer?.partnerId === partnerId;
+
return {
...e,
- customer: e.customer
- ? {
- ...e.customer,
- email: customerDataSharingEnabledAt
- ? customerEmail
- : obfuscateCustomerEmail(customerEmail),
- country: e.customer?.country,
- }
+ customer: belongsToSamePartner
+ ? e.customer
+ ? {
+ ...e.customer,
+ email: customerDataSharingEnabledAt
+ ? customerEmail
+ : obfuscateCustomerEmail(customerEmail),
+ country: e.customer?.country,
+ }
+ : null
: null,
};
}),
diff --git a/apps/web/lib/api/partners/applications/approve-partner.ts b/apps/web/lib/api/partners/applications/approve-partner.ts
index 57bc300461..a22d30ccf6 100644
--- a/apps/web/lib/api/partners/applications/approve-partner.ts
+++ b/apps/web/lib/api/partners/applications/approve-partner.ts
@@ -96,6 +96,7 @@ export async function approvePartner({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/lib/api/partners/applications/reject-partner.ts b/apps/web/lib/api/partners/applications/reject-partner.ts
index 1d2721280e..e0dba2ddf8 100644
--- a/apps/web/lib/api/partners/applications/reject-partner.ts
+++ b/apps/web/lib/api/partners/applications/reject-partner.ts
@@ -125,6 +125,7 @@ export async function rejectPartner({
clickRewardId: null,
leadRewardId: null,
saleRewardId: null,
+ referralRewardId: null,
discountId: null,
},
});
diff --git a/apps/web/lib/api/partners/bulk-reactivate-partners.ts b/apps/web/lib/api/partners/bulk-reactivate-partners.ts
index 11e69c22ed..db435f3a14 100644
--- a/apps/web/lib/api/partners/bulk-reactivate-partners.ts
+++ b/apps/web/lib/api/partners/bulk-reactivate-partners.ts
@@ -48,6 +48,7 @@ export async function bulkReactivatePartners({
clickRewardId: true,
leadRewardId: true,
saleRewardId: true,
+ referralRewardId: true,
discountId: true,
},
});
@@ -120,6 +121,7 @@ export async function bulkReactivatePartners({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/lib/api/partners/create-and-enroll-partner.ts b/apps/web/lib/api/partners/create-and-enroll-partner.ts
index 7f222c2a4f..9573884940 100644
--- a/apps/web/lib/api/partners/create-and-enroll-partner.ts
+++ b/apps/web/lib/api/partners/create-and-enroll-partner.ts
@@ -13,6 +13,7 @@ import { waitUntil } from "@vercel/functions";
import { DubApiError } from "../errors";
import { getGroupOrThrow } from "../groups/get-group-or-throw";
import { createPartnerDefaultLinks } from "./create-partner-default-links";
+import { generatePartnerUsername } from "./generate-partner-username";
import { throwIfExistingTenantEnrollmentExists } from "./throw-if-existing-tenant-id-exists";
interface CreateAndEnrollPartnerInput {
@@ -152,6 +153,7 @@ export const createAndEnrollPartner = async ({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
...(enrolledAt && {
createdAt: enrolledAt,
@@ -170,6 +172,10 @@ export const createAndEnrollPartner = async ({
id: createId({ prefix: "pn_" }),
name: partner.name || partner.email,
email: partner.email,
+ username: await generatePartnerUsername({
+ email: partner.email,
+ name: partner.name,
+ }),
image: partner.image && !isStored(partner.image) ? null : partner.image,
country: partner.country,
description: partner.description,
diff --git a/apps/web/lib/api/partners/generate-partner-username.ts b/apps/web/lib/api/partners/generate-partner-username.ts
new file mode 100644
index 0000000000..dec644c442
--- /dev/null
+++ b/apps/web/lib/api/partners/generate-partner-username.ts
@@ -0,0 +1,38 @@
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import slugify from "@sindresorhus/slugify";
+
+export async function generatePartnerUsername({
+ email,
+ name,
+}: {
+ email: string;
+ name?: string | null;
+}) {
+ const slugifiedBase = name ? slugify(name) : slugify(email.split("@")[0]);
+ let username = `${slugifiedBase}-${nanoid(4).toLowerCase()}`;
+ const maxRetries = 3;
+ let retries = 0;
+
+ while (retries <= maxRetries) {
+ const existingPartner = await prisma.partner.findUnique({
+ where: {
+ username,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!existingPartner) {
+ return username;
+ }
+
+ if (retries === maxRetries) {
+ return null;
+ }
+
+ username = `${slugifiedBase}-${nanoid(4).toLowerCase()}`;
+ retries++;
+ }
+}
diff --git a/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts b/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts
index ad6972a41f..bdc4178633 100644
--- a/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts
+++ b/apps/web/lib/api/partners/get-group-rewards-and-bounties.ts
@@ -8,6 +8,7 @@ const REWARD_ICONS: Record<EventType, string> = {
click: "https://assets.dub.co/email-assets/icons/cursor-rays.png",
lead: "https://assets.dub.co/email-assets/icons/user-plus.png",
sale: "https://assets.dub.co/email-assets/icons/invoice-dollar.png",
+ referral: "https://assets.dub.co/email-assets/icons/users.png",
};
const BOUNTY_ICONS: Record<BountyType, string> = {
@@ -31,7 +32,12 @@ export async function getGroupRewardsAndBounties({
return {
rewards: [
- ...[group.clickReward, group.leadReward, group.saleReward]
+ ...[
+ group.clickReward,
+ group.leadReward,
+ group.saleReward,
+ group.referralReward,
+ ]
.filter((r): r is Reward => r !== null)
.map((reward) => ({
label: formatRewardDescription(serializeReward(reward)),
diff --git a/apps/web/lib/api/partners/get-partners-count.ts b/apps/web/lib/api/partners/get-partners-count.ts
index 512afd56cf..27d81ab2d9 100644
--- a/apps/web/lib/api/partners/get-partners-count.ts
+++ b/apps/web/lib/api/partners/get-partners-count.ts
@@ -20,8 +20,6 @@ type PartnersCountFilters = z.infer<typeof partnersCountQuerySchema> & {
export async function getPartnersCount<T>(
filters: PartnersCountFilters,
): Promise<T> {
- // const {
-
const { groupBy, programId, ...enrollmentFilters } = filters;
const enrollmentBase = { ...enrollmentFilters, programId };
@@ -206,6 +204,41 @@ export async function getPartnersCount<T>(
return partners as T;
}
+ if (groupBy === "referredByPartnerId") {
+ const results = await prisma.programApplicationEvent.groupBy({
+ by: ["referredByPartnerId"],
+ where: {
+ programId,
+ referredByPartnerId: {
+ not: null,
+ },
+ programEnrollment: {
+ ...enrollmentScope,
+ ...(groupIdWhere ?? {}),
+ status:
+ status === "approved_invited"
+ ? {
+ in: ["approved", "invited"],
+ }
+ : status,
+ partner: partnerWhereWithCountry,
+ ...enrollmentMetricWhere,
+ },
+ },
+ _count: true,
+ orderBy: {
+ _count: {
+ referredByPartnerId: "desc",
+ },
+ },
+ });
+
+ return results.map((row) => ({
+ referredByPartnerId: row.referredByPartnerId,
+ _count: row._count,
+ })) as T;
+ }
+
// Get absolute count of partners
const count = await prisma.programEnrollment.count({
where: buildProgramEnrollmentWhereForList(enrollmentBase),
diff --git a/apps/web/lib/api/partners/notify-partner-commission.ts b/apps/web/lib/api/partners/notify-partner-commission.ts
index 7d5364b0ca..f3b08a1ae8 100644
--- a/apps/web/lib/api/partners/notify-partner-commission.ts
+++ b/apps/web/lib/api/partners/notify-partner-commission.ts
@@ -30,7 +30,7 @@ export async function notifyPartnerCommission({
Commission,
"type" | "amount" | "earnings" | "partnerId" | "linkId"
>;
- isFirstCommission: boolean;
+ isFirstCommission?: boolean;
}) {
// Workspace owner emails are sent:
// - only for sale commissions
diff --git a/apps/web/lib/api/partners/process-partner-deactivation.ts b/apps/web/lib/api/partners/process-partner-deactivation.ts
index 72ed3f4566..fae016e1fb 100644
--- a/apps/web/lib/api/partners/process-partner-deactivation.ts
+++ b/apps/web/lib/api/partners/process-partner-deactivation.ts
@@ -72,6 +72,7 @@ export async function processPartnerDeactivation({
clickRewardId: null,
leadRewardId: null,
saleRewardId: null,
+ referralRewardId: null,
discountId: null,
},
}),
diff --git a/apps/web/lib/api/partners/program-enrollment-query.ts b/apps/web/lib/api/partners/program-enrollment-query.ts
index ec5e71ebc2..7063af691a 100644
--- a/apps/web/lib/api/partners/program-enrollment-query.ts
+++ b/apps/web/lib/api/partners/program-enrollment-query.ts
@@ -211,6 +211,7 @@ export function buildProgramEnrollmentWhereForList(
search,
email,
partnerTagId,
+ referredByPartnerId,
partnerTagIdOperator = "IN",
groupIdOperator = "IN",
countryOperator = "IN",
@@ -275,6 +276,11 @@ export function buildProgramEnrollmentWhereForList(
: status,
...(groupIdWhere ?? {}),
...(hasPartnerWhere ? { partner: partnerWhere } : {}),
+ ...(referredByPartnerId && {
+ applicationEvent: {
+ referredByPartnerId,
+ },
+ }),
...metricWhere,
};
}
diff --git a/apps/web/lib/api/rewards/validate-reward.ts b/apps/web/lib/api/rewards/validate-reward.ts
index 71aed24d33..e700283519 100644
--- a/apps/web/lib/api/rewards/validate-reward.ts
+++ b/apps/web/lib/api/rewards/validate-reward.ts
@@ -1,5 +1,10 @@
+import {
+ PARTNER_REFERRAL_FLAT_TRIGGERS,
+ PARTNER_REFERRAL_PERCENTAGE_TRIGGERS,
+} from "@/lib/partner-referrals/constants";
import {
createOrUpdateRewardSchema,
+ referralRewardConfigSchema,
rewardConditionsArraySchema,
} from "@/lib/zod/schemas/rewards";
import * as z from "zod/v4";
@@ -64,6 +69,83 @@ export function validateReward(
}
}
+ if (reward.event === "referral") {
+ if (reward.modifiers != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Reward modifiers are not allowed for referral rewards.",
+ });
+ }
+
+ const parsedConfig = referralRewardConfigSchema.safeParse(reward.config);
+
+ if (!parsedConfig.success) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "config must be provided for referral rewards.",
+ });
+ }
+
+ if (reward.type === "percentage") {
+ if (reward.amountInPercentage == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "amountInPercentage must be provided when type is 'percentage'.",
+ });
+ }
+
+ if (reward.amountInCents != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInCents is not allowed when type is 'percentage'.",
+ });
+ }
+
+ if (
+ !PARTNER_REFERRAL_PERCENTAGE_TRIGGERS.includes(
+ parsedConfig.data.trigger as any,
+ )
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `config.trigger must be one of: ${PARTNER_REFERRAL_PERCENTAGE_TRIGGERS.join(
+ ", ",
+ )} for percentage rewards.`,
+ });
+ }
+ }
+
+ if (reward.type === "flat") {
+ if (reward.amountInCents == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInCents must be provided when type is 'flat'.",
+ });
+ }
+
+ if (reward.amountInPercentage != null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "amountInPercentage is not allowed when type is 'flat'.",
+ });
+ }
+
+ if (
+ !PARTNER_REFERRAL_FLAT_TRIGGERS.includes(
+ parsedConfig.data.trigger as any,
+ )
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `config.trigger must be one of: ${PARTNER_REFERRAL_FLAT_TRIGGERS.join(
+ ", ",
+ )} for flat rewards.`,
+ });
+ }
+ }
+ }
+
if (reward.modifiers != null) {
const parsedModifiers = rewardConditionsArraySchema.safeParse(
reward.modifiers,
diff --git a/apps/web/lib/api/workflows/execute-move-group-workflow.ts b/apps/web/lib/api/workflows/execute-move-group-workflow.ts
index b3c2dc7921..6ae323e465 100644
--- a/apps/web/lib/api/workflows/execute-move-group-workflow.ts
+++ b/apps/web/lib/api/workflows/execute-move-group-workflow.ts
@@ -96,6 +96,7 @@ export const executeMoveGroupWorkflow = async ({
clickRewardId: true,
leadRewardId: true,
saleRewardId: true,
+ referralRewardId: true,
discountId: true,
},
});
diff --git a/apps/web/lib/application-events/mark-application-event-submitted-network.ts b/apps/web/lib/application-events/mark-application-event-submitted-network.ts
new file mode 100644
index 0000000000..69bdb36980
--- /dev/null
+++ b/apps/web/lib/application-events/mark-application-event-submitted-network.ts
@@ -0,0 +1,164 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import { Partner } from "@dub/prisma/client";
+import { nanoid, NETWORK_PROGRAM_ID, NETWORK_WORKSPACE_ID } from "@dub/utils";
+import { randomInt } from "crypto";
+import { addSeconds } from "date-fns";
+import { cookies } from "next/headers";
+import { syncPartnerLinksStats } from "../api/partners/sync-partner-links-stats";
+import { recordLead } from "../tinybird";
+import { recordClickZodSchema } from "../tinybird/record-click-zod";
+import { getApplicationEventCookieName } from "./utils";
+
+export async function markApplicationEventSubmittedNetwork(
+ partner: Pick<Partner, "id" | "name" | "email" | "image" | "country">,
+) {
+ try {
+ const cookieStore = await cookies();
+ const cookieName = getApplicationEventCookieName(NETWORK_PROGRAM_ID);
+ const applicationEventId = cookieStore.get(cookieName)?.value;
+
+ if (!applicationEventId) {
+ console.log(
+ `No application event ID found for network program + new partner ${partner.id}, skipping...`,
+ );
+ return;
+ }
+
+ const applicationEvent = await prisma.programApplicationEvent.findUnique({
+ where: {
+ id: applicationEventId,
+ programId: NETWORK_PROGRAM_ID,
+ },
+ });
+
+ if (!applicationEvent) {
+ console.log(
+ `No application event found for new partner ${partner.id}, skipping...`,
+ );
+ return;
+ }
+
+ if (applicationEvent.submittedAt) {
+ console.log(
+ `Application event already submitted for new partner ${partner.id}, skipping...`,
+ );
+ return;
+ }
+
+ await prisma.$transaction(async (tx) => {
+ await tx.programApplicationEvent.update({
+ where: {
+ id: applicationEventId,
+ },
+ data: {
+ // assuming application starts after 15-45 seconds of visiting the page
+ startedAt: addSeconds(applicationEvent.visitedAt, randomInt(15, 45)),
+ submittedAt: new Date(),
+ partnerId: partner.id,
+ },
+ });
+
+ if (applicationEvent.referredByPartnerId) {
+ await tx.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ referredByPartnerId: applicationEvent.referredByPartnerId,
+ },
+ });
+ }
+ });
+
+ if (!applicationEvent.referredByPartnerId) {
+ console.log(
+ `No referredByPartnerId found for new partner ${partner.id}, skipping...`,
+ );
+ return;
+ }
+
+ if (!applicationEvent.metadata) {
+ console.log(
+ `No application event metadata found for new partner ${partner.id}, skipping...`,
+ );
+ return;
+ }
+
+ const networkPartnerLink = await prisma.link.findFirst({
+ where: {
+ programId: NETWORK_PROGRAM_ID,
+ partnerId: applicationEvent.referredByPartnerId,
+ partnerGroupDefaultLinkId: {
+ not: null,
+ },
+ },
+ });
+ if (!networkPartnerLink) {
+ console.log(
+ `No network partner link found for partner ${applicationEvent.referredByPartnerId}, skipping...`,
+ );
+ return;
+ }
+
+ const metadata = recordClickZodSchema.parse(applicationEvent.metadata);
+
+ const customer = await prisma.customer.create({
+ data: {
+ id: createId({ prefix: "cus_" }),
+ name: partner.name,
+ email: partner.email,
+ avatar: partner.image,
+ externalId: partner.id,
+ country: partner.country,
+ projectId: NETWORK_WORKSPACE_ID,
+ linkId: networkPartnerLink.id,
+ programId: NETWORK_PROGRAM_ID,
+ partnerId: applicationEvent.referredByPartnerId,
+ clickId: metadata.click_id,
+ clickedAt: applicationEvent.visitedAt,
+ },
+ });
+ console.log(`Tracked customer with id: ${customer.id}`);
+
+ await recordLead({
+ ...metadata,
+ workspace_id: NETWORK_WORKSPACE_ID,
+ link_id: networkPartnerLink.id,
+ domain: networkPartnerLink.domain,
+ key: networkPartnerLink.key,
+ event_id: nanoid(16),
+ event_name: "New partner signup",
+ customer_id: customer.id,
+ });
+ console.log(`Tracked lead event with event_id: ${nanoid(16)}`);
+
+ await prisma.link.update({
+ where: {
+ id: networkPartnerLink.id,
+ },
+ data: {
+ clicks: {
+ increment: 1,
+ },
+ lastClicked: applicationEvent.visitedAt,
+ leads: {
+ increment: 1,
+ },
+ lastLeadAt: new Date(),
+ },
+ });
+ console.log(`Updated stats for link ${networkPartnerLink.id}`);
+
+ await syncPartnerLinksStats({
+ partnerId: networkPartnerLink.partnerId!,
+ programId: networkPartnerLink.programId!,
+ eventType: "lead",
+ });
+ } catch (error) {
+ console.error(
+ `Error marking application event submitted for new partner ${partner.id}:`,
+ error,
+ );
+ }
+}
diff --git a/apps/web/lib/auth/partner.ts b/apps/web/lib/auth/partner.ts
index d9a5053f3a..15ea0f9914 100644
--- a/apps/web/lib/auth/partner.ts
+++ b/apps/web/lib/auth/partner.ts
@@ -4,7 +4,12 @@ import { PartnerBetaFeatures, PartnerProps } from "@/lib/types";
import { flattenVeriffMetadata } from "@/lib/veriff/veriff-metadata";
import { prisma } from "@dub/prisma";
import { PartnerUser } from "@dub/prisma/client";
-import { getSearchParams, PARTNERS_DOMAIN } from "@dub/utils";
+import {
+ getSearchParams,
+ NETWORK_PROGRAM_ID,
+ NETWORK_PROGRAM_SLUG,
+ PARTNERS_DOMAIN,
+} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { headers } from "next/headers";
import { getPartnerFeatureFlags } from "../edge-config";
@@ -70,6 +75,22 @@ export const withPartnerProfile = (
let responseHeaders = new Headers();
try {
+ // Restrict access to the network program
+ const programIdParam = params.programId?.toLowerCase();
+
+ if (
+ programIdParam &&
+ [
+ NETWORK_PROGRAM_ID.toLowerCase(),
+ NETWORK_PROGRAM_SLUG.toLowerCase(),
+ ].includes(programIdParam)
+ ) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Program not found.",
+ });
+ }
+
const authorizationHeader = requestHeaders.get("Authorization");
if (authorizationHeader) {
if (!authorizationHeader.startsWith("Bearer ")) {
diff --git a/apps/web/lib/cron/enqueue-batch-jobs.ts b/apps/web/lib/cron/enqueue-batch-jobs.ts
index ca8016ff94..789b7e378e 100644
--- a/apps/web/lib/cron/enqueue-batch-jobs.ts
+++ b/apps/web/lib/cron/enqueue-batch-jobs.ts
@@ -9,7 +9,8 @@ type EnqueueBatchJobsProps = PublishBatchRequest<unknown> & {
| "create-discount-code"
| "sync-bounty-social-metrics"
| "process-hubspot-webhook"
- | "delete-discount-code";
+ | "delete-discount-code"
+ | "create-referral-commissions";
};
// Generic helper to enqueue a batch of QStash jobs.
@@ -17,14 +18,13 @@ export async function enqueueBatchJobs(jobs: EnqueueBatchJobsProps[]) {
try {
const result = await qstash.batchJSON(jobs);
- if (process.env.NODE_ENV === "development") {
- console.info(
- `[enqueueBatchJobs] ${result.length} batch jobs enqueued successfully.`,
- {
- jobs,
- },
- );
- }
+ console.log(
+ `[enqueueBatchJobs] ${result.length} batch jobs enqueued successfully.`,
+ {
+ result,
+ jobs,
+ },
+ );
return result;
} catch (error) {
diff --git a/apps/web/lib/fetchers/get-network-program.ts b/apps/web/lib/fetchers/get-network-program.ts
index e6d6cb0d5a..1f4b7ea779 100644
--- a/apps/web/lib/fetchers/get-network-program.ts
+++ b/apps/web/lib/fetchers/get-network-program.ts
@@ -22,6 +22,7 @@ export const getNetworkProgram = cache(async ({ slug }: { slug: string }) => {
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
},
},
diff --git a/apps/web/lib/fetchers/get-program.ts b/apps/web/lib/fetchers/get-program.ts
index 3220c33bd9..632a72d4bf 100644
--- a/apps/web/lib/fetchers/get-program.ts
+++ b/apps/web/lib/fetchers/get-program.ts
@@ -25,6 +25,7 @@ export const getProgram = cache(
clickReward: true,
leadReward: true,
saleReward: true,
+ referralReward: true,
discount: true,
},
},
diff --git a/apps/web/lib/firstpromoter/import-partners.ts b/apps/web/lib/firstpromoter/import-partners.ts
index fc68a69b74..396052a0d8 100644
--- a/apps/web/lib/firstpromoter/import-partners.ts
+++ b/apps/web/lib/firstpromoter/import-partners.ts
@@ -186,6 +186,7 @@ async function createPartnerAndLinks({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
update: {
diff --git a/apps/web/lib/middleware/utils/app-redirect.ts b/apps/web/lib/middleware/utils/app-redirect.ts
index 9a579086a3..c3ee18772e 100644
--- a/apps/web/lib/middleware/utils/app-redirect.ts
+++ b/apps/web/lib/middleware/utils/app-redirect.ts
@@ -8,7 +8,6 @@ const APP_REDIRECTS = {
"/welcome": "/onboarding/welcome",
"/campaigns": "/program/campaigns",
"/messages": "/program/messages",
- "/network": "/program/network",
"/marketplace": "/program/network",
"/fraud": "/program/fraud",
};
diff --git a/apps/web/lib/partner-referrals/constants.ts b/apps/web/lib/partner-referrals/constants.ts
new file mode 100644
index 0000000000..4d9c0eda4e
--- /dev/null
+++ b/apps/web/lib/partner-referrals/constants.ts
@@ -0,0 +1,75 @@
+const PARTNER_REFERRAL_TRIGGER_CONFIG = {
+ percentage: {
+ saleRecorded: {
+ verb: "makes a sale",
+ basis: "original sale amount",
+ },
+ commissionEarned: {
+ verb: "earns a commission",
+ basis: "referred partner's commission",
+ },
+ },
+ flat: {
+ partnerApproved: {
+ verb: "is approved",
+ },
+ commissionThreshold: {
+ verb: "earns at least",
+ },
+ },
+} as const;
+
+export type PartnerReferralPercentageTrigger =
+ keyof typeof PARTNER_REFERRAL_TRIGGER_CONFIG.percentage;
+
+type PartnerReferralFlatTrigger =
+ keyof typeof PARTNER_REFERRAL_TRIGGER_CONFIG.flat;
+
+type PartnerReferralTrigger =
+ | PartnerReferralPercentageTrigger
+ | PartnerReferralFlatTrigger;
+
+export const PARTNER_REFERRAL_PERCENTAGE_TRIGGERS = Object.keys(
+ PARTNER_REFERRAL_TRIGGER_CONFIG.percentage,
+) as readonly PartnerReferralPercentageTrigger[];
+
+export const PARTNER_REFERRAL_FLAT_TRIGGERS = Object.keys(
+ PARTNER_REFERRAL_TRIGGER_CONFIG.flat,
+) as readonly PartnerReferralFlatTrigger[];
+
+export const PARTNER_REFERRAL_TRIGGER = [
+ ...PARTNER_REFERRAL_PERCENTAGE_TRIGGERS,
+ ...PARTNER_REFERRAL_FLAT_TRIGGERS,
+] as readonly PartnerReferralTrigger[];
+
+export const PARTNER_REFERRAL_TRIGGER_LABELS: Record<
+ PartnerReferralTrigger,
+ string
+> = {
+ ...Object.fromEntries(
+ Object.entries(PARTNER_REFERRAL_TRIGGER_CONFIG.percentage).map(
+ ([key, { verb }]) => [key, verb],
+ ),
+ ),
+ ...Object.fromEntries(
+ Object.entries(PARTNER_REFERRAL_TRIGGER_CONFIG.flat).map(
+ ([key, { verb }]) => [key, verb],
+ ),
+ ),
+} as Record<PartnerReferralTrigger, string>;
+
+export const PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS = Object.fromEntries(
+ Object.entries(PARTNER_REFERRAL_TRIGGER_CONFIG.percentage).map(
+ ([key, { basis }]) => [key, basis],
+ ),
+) as {
+ readonly [K in PartnerReferralPercentageTrigger]: string;
+};
+
+// TODO: refactor to pull from programEnrollment.saleReward
+export const NETWORK_REFERRAL_REWARD = {
+ amountInPercentage: 50,
+ maxDuration: 6,
+} as const;
+
+export const NETWORK_REFERRAL_SWAG_THRESHOLD_CENTS = 1000_000;
diff --git a/apps/web/lib/partner-referrals/create-network-referral-commission.ts b/apps/web/lib/partner-referrals/create-network-referral-commission.ts
new file mode 100644
index 0000000000..217c6f00b0
--- /dev/null
+++ b/apps/web/lib/partner-referrals/create-network-referral-commission.ts
@@ -0,0 +1,259 @@
+import { prisma } from "@dub/prisma";
+import {
+ Commission,
+ CommissionType,
+ Partner,
+ Payout,
+ Prisma,
+} from "@dub/prisma/client";
+import {
+ currencyFormatter,
+ log,
+ nanoid,
+ NETWORK_PROGRAM_ID,
+ NETWORK_WORKSPACE_ID,
+} from "@dub/utils";
+import { differenceInMonths } from "date-fns";
+import { isFirstConversion } from "../analytics/is-first-conversion";
+import { createId } from "../api/create-id";
+import { syncPartnerLinksStats } from "../api/partners/sync-partner-links-stats";
+import { calculateSaleEarnings } from "../api/sales/calculate-sale-earnings";
+import { determinePartnerReward } from "../partners/determine-partner-reward";
+import { getLeadEvent, recordSale } from "../tinybird";
+import { LeadEventTB } from "../types";
+import { NETWORK_REFERRAL_REWARD } from "./constants";
+
+type CreateNetworkReferralCommissionProps = {
+ partner: Pick<Partner, "id" | "referredByPartnerId">;
+ payout: Pick<Payout, "id" | "amount" | "programId">;
+};
+
+export const createNetworkReferralCommission = async ({
+ partner,
+ payout,
+}: CreateNetworkReferralCommissionProps) => {
+ if (!partner.referredByPartnerId) {
+ console.error(
+ `Partner ${partner.id} has no referredByPartnerId, skipping...`,
+ );
+ return null;
+ }
+
+ if (payout.programId === NETWORK_PROGRAM_ID) {
+ console.error(`Payout ${payout.id} is from Network program, skipping...`);
+ return null;
+ }
+
+ const payoutFeeEarned = Math.floor(payout.amount * 0.03); // assumes 3% average payout fee for all payouts
+
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId: partner.referredByPartnerId,
+ programId: NETWORK_PROGRAM_ID,
+ },
+ },
+ include: {
+ partner: true,
+ links: true,
+ saleReward: true,
+ },
+ });
+
+ if (!programEnrollment) {
+ console.log(
+ `Referrer partner ${partner.referredByPartnerId} is not enrolled in network program.`,
+ );
+ return null;
+ }
+
+ const customer = await prisma.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: NETWORK_WORKSPACE_ID,
+ externalId: partner.id,
+ },
+ },
+ include: {
+ link: true,
+ },
+ });
+
+ const invoiceId = `referral:network:${payout.id}`;
+
+ if (customer?.link) {
+ const leadEventData = (await getLeadEvent({
+ customerId: customer.id,
+ })) as LeadEventTB | null;
+
+ if (leadEventData) {
+ const saleData = {
+ ...leadEventData,
+ event_id: nanoid(16),
+ event_name: "Partner payout fee",
+ customer_id: customer.id,
+ payment_processor: "dub",
+ amount: payoutFeeEarned,
+ currency: "usd",
+ invoice_id: invoiceId,
+ };
+
+ const firstConversionFlag = isFirstConversion({
+ customer,
+ linkId: saleData.link_id,
+ });
+
+ await Promise.allSettled([
+ recordSale({
+ ...saleData,
+ timestamp: undefined,
+ }),
+
+ // Update link conversions, sales, and saleAmount
+ prisma.link.update({
+ where: {
+ id: saleData.link_id,
+ },
+ data: {
+ ...(firstConversionFlag && {
+ conversions: {
+ increment: 1,
+ },
+ lastConversionAt: new Date(),
+ }),
+ sales: {
+ increment: 1,
+ },
+ saleAmount: {
+ increment: payoutFeeEarned,
+ },
+ },
+ }),
+
+ prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ sales: {
+ increment: 1,
+ },
+ saleAmount: {
+ increment: payoutFeeEarned,
+ },
+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
+ },
+ }),
+ ]);
+ await syncPartnerLinksStats({
+ partnerId: partner.referredByPartnerId,
+ programId: NETWORK_PROGRAM_ID,
+ eventType: "sale",
+ });
+ } else {
+ // should never happen, but just in case
+ console.error(`No lead event data found for customer ${customer.id}.`);
+ }
+ } else {
+ // should never happen, but just in case
+ console.error(`No customer found for partner ${partner.id}.`);
+ }
+
+ const reward = determinePartnerReward({
+ event: "sale",
+ programEnrollment,
+ });
+
+ if (!reward) {
+ console.log(
+ `Referrer partner ${partner.referredByPartnerId} has no eligible reward for the network program.`,
+ );
+ return null;
+ }
+
+ const firstCommission = await prisma.commission.findFirst({
+ where: {
+ programId: NETWORK_PROGRAM_ID,
+ partnerId: partner.referredByPartnerId,
+ sourcePartnerId: partner.id,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ select: {
+ createdAt: true,
+ },
+ });
+
+ if (firstCommission) {
+ const durationMonths = differenceInMonths(
+ new Date(),
+ firstCommission.createdAt,
+ );
+
+ if (durationMonths >= NETWORK_REFERRAL_REWARD.maxDuration) {
+ console.log(
+ `Referrer partner ${partner.referredByPartnerId} has reached max duration for network bonus.`,
+ );
+ return null;
+ }
+ }
+
+ const earnings = calculateSaleEarnings({
+ reward,
+ sale: {
+ amount: payoutFeeEarned,
+ quantity: 1,
+ },
+ });
+
+ const commissionData: Prisma.CommissionUncheckedCreateInput = {
+ id: createId({ prefix: "cm_" }),
+ programId: NETWORK_PROGRAM_ID,
+ partnerId: partner.referredByPartnerId,
+ sourcePartnerId: partner.id,
+ type: CommissionType.referral,
+ amount: 0,
+ quantity: 1,
+ earnings,
+ customerId: customer?.id,
+ linkId: customer?.link?.id,
+ invoiceId,
+ description: `Earned ${reward.amountInPercentage}% commission on the referred partner's ${currencyFormatter(payoutFeeEarned)} payout fee.`,
+ };
+
+ let commission: Commission | null = null;
+
+ try {
+ commission = await prisma.commission.create({
+ data: commissionData,
+ });
+
+ console.log("Network referral commission created", commission);
+ } catch (error) {
+ // Don't retry on unique constraint violation – the commission already exists
+ // (likely a race between the dedup check and the create)
+ if (error.code === "P2002") {
+ console.log(
+ `Referral commission already exists for invoiceId ${commissionData.invoiceId}, skipping creation.`,
+ );
+ return null;
+ }
+
+ console.error(
+ "Error creating network referral commission",
+ error,
+ commissionData,
+ );
+
+ await log({
+ message: `[createNetworkReferralCommission] Error creating referral commission - ${error.message}`,
+ type: "errors",
+ mention: true,
+ });
+
+ throw error;
+ }
+
+ return commission;
+};
diff --git a/apps/web/lib/partner-referrals/create-referral-commission.ts b/apps/web/lib/partner-referrals/create-referral-commission.ts
new file mode 100644
index 0000000000..eed1b42b06
--- /dev/null
+++ b/apps/web/lib/partner-referrals/create-referral-commission.ts
@@ -0,0 +1,466 @@
+import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { prisma } from "@dub/prisma";
+import { Commission, CommissionType, Prisma, Reward } from "@dub/prisma/client";
+import { currencyFormatter, log, NETWORK_PROGRAM_ID } from "@dub/utils";
+import { differenceInMonths } from "date-fns";
+import { createId } from "../api/create-id";
+import { notifyPartnerCommission } from "../api/partners/notify-partner-commission";
+import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
+import { constructWebhookPartner } from "../partners/constuct-webhook-partner";
+import { sendPartnerPostback } from "../postback/send-partner-postback";
+import { sendWorkspaceWebhook } from "../webhook/publish";
+import { CommissionWebhookSchema } from "../zod/schemas/commissions";
+
+type CreateReferralCommissionProps =
+ | { sourceCommissionId: string; partnerId?: never; programId?: never } // Based on a source commission
+ | { sourceCommissionId?: never; partnerId: string; programId: string }; // Based on partner approval and commission threshold
+
+export const createReferralCommission = async (
+ props: CreateReferralCommissionProps,
+) => {
+ const context = await resolveReferralContext(props);
+
+ if (!context) {
+ return null;
+ }
+
+ const { sourceCommission, programId, partnerId, referredByPartnerId } =
+ context;
+
+ if (programId === NETWORK_PROGRAM_ID) {
+ return null;
+ }
+
+ const referrerProgramEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId: referredByPartnerId,
+ programId,
+ },
+ },
+ include: {
+ partner: true,
+ links: true,
+ referralReward: true,
+ partnerGroup: true,
+ },
+ });
+
+ if (!referrerProgramEnrollment) {
+ console.log(
+ `Referrer partner ${referredByPartnerId} is not enrolled in the program ${programId}.`,
+ );
+ return null;
+ }
+
+ const { referralReward } = referrerProgramEnrollment;
+
+ if (!referralReward) {
+ console.log(
+ `Referrer partner ${referredByPartnerId} has no referral reward for the group in program ${programId}.`,
+ );
+ return null;
+ }
+
+ const rewardConfig = referralRewardConfigSchema.safeParse(
+ referralReward.config,
+ );
+
+ if (!rewardConfig.success) {
+ console.log(`Referral reward ${referralReward.id} has an invalid config.`);
+ return null;
+ }
+
+ let commissionData: Prisma.CommissionUncheckedCreateInput = {
+ id: createId({ prefix: "cm_" }),
+ type: CommissionType.referral,
+ amount: 0,
+ quantity: 1,
+ earnings: 0,
+ programId,
+ sourcePartnerId: partnerId,
+ partnerId: referredByPartnerId,
+ rewardId: referralReward.id,
+ };
+
+ const { trigger, commissionsThresholdInCents } = rewardConfig.data;
+
+ // When reward is based on commission earned or sale recorded
+ if (
+ sourceCommission &&
+ (trigger === "commissionEarned" || trigger === "saleRecorded")
+ ) {
+ const amountInPercentage = Number(referralReward.amountInPercentage ?? 0);
+
+ if (typeof referralReward.maxDuration === "number") {
+ const firstReferralCommission = await prisma.commission.findFirst({
+ where: {
+ partnerId: referredByPartnerId,
+ customerId: sourceCommission.customerId,
+ type: "referral",
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ select: {
+ createdAt: true,
+ },
+ });
+
+ if (firstReferralCommission) {
+ const subscriptionDurationMonths = differenceInMonths(
+ sourceCommission.createdAt,
+ firstReferralCommission.createdAt,
+ );
+
+ // One-time
+ if (referralReward.maxDuration === 0) {
+ console.log(
+ `Referrer ${referredByPartnerId} reached max duration (first-sale only) for referred partner ${partnerId} for the customer ${sourceCommission.customerId}.`,
+ );
+ return null;
+ }
+
+ // Recurring
+ if (subscriptionDurationMonths >= referralReward.maxDuration) {
+ console.log(
+ `Referrer ${referredByPartnerId} reached max duration (${referralReward.maxDuration} months) for referred partner ${partnerId} for the customer ${sourceCommission.customerId}.`,
+ );
+ return null;
+ }
+ }
+ }
+
+ if (trigger === "commissionEarned") {
+ commissionData.earnings = Math.floor(
+ (sourceCommission.earnings * amountInPercentage) / 100,
+ );
+ } else if (trigger === "saleRecorded") {
+ commissionData.earnings = Math.floor(
+ (sourceCommission.amount * amountInPercentage) / 100,
+ );
+ }
+
+ commissionData = {
+ ...commissionData,
+ customerId: sourceCommission.customerId,
+ currency: sourceCommission.currency,
+ sourceCommissionId: sourceCommission.id,
+ invoiceId: `referral:${trigger}:${sourceCommission.id}`,
+ };
+ }
+
+ // When reward is based on partner approval
+ else if (trigger === "partnerApproved") {
+ commissionData = {
+ ...commissionData,
+ earnings: referralReward.amountInCents ?? 0,
+ invoiceId: `referral:${trigger}:${partnerId}`,
+ };
+ }
+
+ // When reward is based on commission threshold reached
+ else if (trigger === "commissionThreshold") {
+ const {
+ _sum: { earnings: totalCommissionsEarned },
+ } = await prisma.commission.aggregate({
+ where: {
+ partnerId,
+ programId,
+ type: "sale",
+ },
+ _sum: {
+ earnings: true,
+ },
+ });
+
+ if ((totalCommissionsEarned ?? 0) < (commissionsThresholdInCents ?? 0)) {
+ console.log(
+ `Referrer ${referredByPartnerId} has not reached the commission threshold for referred partner ${partnerId}.`,
+ );
+ return null;
+ }
+
+ commissionData = {
+ ...commissionData,
+ earnings: referralReward.amountInCents ?? 0,
+ invoiceId: `referral:${trigger}:${partnerId}`,
+ };
+ }
+
+ // When reward is based on unknown trigger
+ else {
+ console.log(
+ `Invalid trigger ${trigger} for referral reward ${referralReward.id}.`,
+ );
+ return null;
+ }
+
+ if (commissionData.earnings === 0) {
+ return null;
+ }
+
+ // Check if the commission already exists using the invoiceId
+ if (commissionData.invoiceId) {
+ const existingCommission = await prisma.commission.findUnique({
+ where: {
+ invoiceId_programId: {
+ invoiceId: commissionData.invoiceId,
+ programId,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (existingCommission) {
+ console.log(
+ `Referral commission ${existingCommission.id} already exists for the invoiceId ${commissionData.invoiceId}.`,
+ );
+ return null;
+ }
+ }
+
+ commissionData.description = generateCommissionDescription({
+ referralReward,
+ });
+
+ let commission: Commission;
+
+ try {
+ commission = await prisma.commission.create({
+ data: commissionData,
+ });
+
+ console.log("Referral commission created", commission);
+ } catch (error) {
+ // Don't retry on unique constraint violation – the commission already exists
+ // (likely a race between the dedup check and the create)
+ if (error.code === "P2002") {
+ console.log(
+ `Referral commission already exists for invoiceId ${commissionData.invoiceId}, skipping creation.`,
+ );
+ return null;
+ }
+
+ console.error("Error creating referral commission", error, commissionData);
+
+ await log({
+ message: `[createReferralCommission] Error creating referral commission - ${error.message}`,
+ type: "errors",
+ mention: true,
+ });
+
+ throw error;
+ }
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ supportEmail: true,
+ groups: true,
+ workspace: {
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ webhookEnabled: true,
+ },
+ },
+ },
+ });
+
+ await Promise.allSettled([
+ sendWorkspaceWebhook({
+ workspace: program.workspace,
+ trigger: "commission.created",
+ data: CommissionWebhookSchema.parse({
+ ...commission,
+ partner: constructWebhookPartner(referrerProgramEnrollment),
+ link: null,
+ }),
+ }),
+
+ sendPartnerPostback({
+ partnerId: referredByPartnerId,
+ event: "commission.created",
+ data: commission,
+ }),
+
+ syncTotalCommissions({
+ partnerId: referredByPartnerId,
+ programId,
+ }),
+
+ notifyPartnerCommission({
+ workspace: program.workspace,
+ program,
+ commission,
+ group: referrerProgramEnrollment.partnerGroup ?? program.groups[0],
+ }),
+ ]);
+
+ return commission;
+};
+
+function generateCommissionDescription({
+ referralReward,
+}: {
+ referralReward: Reward;
+}) {
+ const { trigger } = referralRewardConfigSchema.parse(referralReward.config);
+ const amountInPercentage = Number(referralReward.amountInPercentage ?? 0);
+
+ if (trigger === "commissionEarned") {
+ return `Earned ${amountInPercentage}% of referred partner's sale commission.`;
+ }
+
+ if (trigger === "saleRecorded") {
+ return `Earned ${amountInPercentage}% of referred partner's sale amount.`;
+ }
+
+ if (trigger === "partnerApproved") {
+ return "Earned for referring a new partner.";
+ }
+
+ if (trigger === "commissionThreshold") {
+ const { commissionsThresholdInCents } = referralRewardConfigSchema.parse(
+ referralReward.config,
+ );
+
+ const formattedThreshold = currencyFormatter(
+ commissionsThresholdInCents ?? 0,
+ {
+ currency: "usd",
+ trailingZeroDisplay: "stripIfInteger",
+ },
+ );
+
+ return `Earned for referred partner reaching ${formattedThreshold} in commissions.`;
+ }
+
+ return null;
+}
+
+async function resolveReferralContext(props: CreateReferralCommissionProps) {
+ if (props.sourceCommissionId) {
+ const { sourceCommissionId } = props;
+
+ const sourceCommission = await prisma.commission.findUnique({
+ where: {
+ id: sourceCommissionId,
+ },
+ include: {
+ programEnrollment: {
+ select: {
+ programId: true,
+ partnerId: true,
+ applicationEvent: {
+ select: {
+ referredByPartnerId: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!sourceCommission) {
+ console.log(`Source commission ${sourceCommissionId} not found.`);
+ return null;
+ }
+
+ // We only support referral commissions for sale commissions currently
+ if (sourceCommission.type !== CommissionType.sale) {
+ console.log(
+ `Source commission ${sourceCommissionId} is not a sale commission.`,
+ );
+ return null;
+ }
+
+ if (!["processed", "paid"].includes(sourceCommission.status)) {
+ console.log(
+ `Source commission ${sourceCommissionId} is not a processed or paid.`,
+ );
+ return null;
+ }
+
+ const referredByPartnerId =
+ sourceCommission.programEnrollment?.applicationEvent?.referredByPartnerId;
+
+ if (!referredByPartnerId) {
+ console.log(
+ `Source commission ${sourceCommissionId} is not associated with a referred partner.`,
+ );
+ return null;
+ }
+
+ return {
+ sourceCommission,
+ programId: sourceCommission.programId,
+ partnerId: sourceCommission.partnerId,
+ referredByPartnerId,
+ };
+ }
+
+ if (props.partnerId && props.programId) {
+ const { partnerId, programId } = props;
+
+ const programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ select: {
+ programId: true,
+ partnerId: true,
+ status: true,
+ applicationEvent: {
+ select: {
+ referredByPartnerId: true,
+ },
+ },
+ },
+ });
+
+ if (!programEnrollment) {
+ console.log(
+ `Partner ${partnerId} is not enrolled in the program ${programId}.`,
+ );
+ return null;
+ }
+
+ if (programEnrollment.status !== "approved") {
+ console.log(
+ `Partner ${partnerId} is not approved in the program ${programId}.`,
+ );
+ return null;
+ }
+
+ const referredByPartnerId =
+ programEnrollment?.applicationEvent?.referredByPartnerId;
+
+ if (!referredByPartnerId) {
+ console.log(
+ `Referrer partner ${partnerId} is not associated with a referred partner.`,
+ );
+ return null;
+ }
+
+ return {
+ sourceCommission: null,
+ programId,
+ partnerId,
+ referredByPartnerId,
+ };
+ }
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-network-referrals-stats.ts b/apps/web/lib/partner-referrals/hooks/use-network-referrals-stats.ts
new file mode 100644
index 0000000000..0ba897313d
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-network-referrals-stats.ts
@@ -0,0 +1,21 @@
+import { NetworkReferralsStats } from "@/lib/partner-referrals/types";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+
+export function useNetworkReferralsStats({
+ enabled = true,
+}: { enabled?: boolean } = {}) {
+ const { data, error, isLoading } = useSWR<NetworkReferralsStats>(
+ enabled ? `/api/partner-profile/referrals/stats` : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ isLoading,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-network-referrals-timeseries.ts b/apps/web/lib/partner-referrals/hooks/use-network-referrals-timeseries.ts
new file mode 100644
index 0000000000..0f7044bc0c
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-network-referrals-timeseries.ts
@@ -0,0 +1,33 @@
+import { NetworkReferralsTimeseries } from "@/lib/partner-referrals/types";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+
+export function useNetworkReferralsTimeseries({
+ enabled = true,
+ interval = "1y",
+}: {
+ enabled?: boolean;
+ interval?: string;
+} = {}) {
+ const searchParams = new URLSearchParams({
+ interval,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ });
+
+ const { data, error, isLoading } = useSWR<NetworkReferralsTimeseries[]>(
+ enabled
+ ? `/api/partner-profile/referrals/timeseries?${searchParams.toString()}`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ isLoading,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-network-referrals.ts b/apps/web/lib/partner-referrals/hooks/use-network-referrals.ts
new file mode 100644
index 0000000000..5ffb5ae9bd
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-network-referrals.ts
@@ -0,0 +1,24 @@
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import { NetworkReferralProps } from "../types";
+
+export function useNetworkReferrals({
+ enabled = true,
+}: { enabled?: boolean } = {}) {
+ const { getQueryString } = useRouterStuff();
+
+ const { data, isLoading, error } = useSWR<NetworkReferralProps[]>(
+ enabled ? `/api/partner-profile/referrals${getQueryString()}` : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ isLoading,
+ error,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-partner-referral.ts b/apps/web/lib/partner-referrals/hooks/use-partner-referral.ts
new file mode 100644
index 0000000000..439113b43e
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-partner-referral.ts
@@ -0,0 +1,25 @@
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import useWorkspace from "../../swr/use-workspace";
+import { PartnerReferral } from "../types";
+
+export function usePartnerReferral({
+ partnerId,
+}: {
+ partnerId: string | null | undefined;
+}) {
+ const { id: workspaceId } = useWorkspace();
+
+ const { data, isLoading, error } = useSWR<PartnerReferral>(
+ partnerId && workspaceId
+ ? `/api/partners/${partnerId}/referral?workspaceId=${workspaceId}`
+ : null,
+ fetcher,
+ );
+
+ return {
+ referral: data,
+ loading: isLoading,
+ error,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-referred-partner-filters.tsx b/apps/web/lib/partner-referrals/hooks/use-referred-partner-filters.tsx
new file mode 100644
index 0000000000..12fc6a867f
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-referred-partner-filters.tsx
@@ -0,0 +1,127 @@
+import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
+import { CountryFlag } from "@/ui/shared/country-flag";
+import { ProgramEnrollmentStatus } from "@dub/prisma/client";
+import { useRouterStuff } from "@dub/ui";
+import { CircleDotted, Globe } from "@dub/ui/icons";
+import { cn, COUNTRIES, nFormatter } from "@dub/utils";
+import { useCallback, useMemo, useState } from "react";
+import { useReferredPartnersCount } from "./use-referred-partners-count";
+
+export function useReferredPartnerFilters() {
+ const { searchParamsObj, queryParams } = useRouterStuff();
+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+
+ const { data: countriesCount } = useReferredPartnersCount<
+ | {
+ country: string;
+ _count: number;
+ }[]
+ | undefined
+ >({
+ query: {
+ groupBy: "country",
+ },
+ enabled: selectedFilter === "country" || !!searchParamsObj.country,
+ });
+
+ const { data: statusesCount } = useReferredPartnersCount<
+ | {
+ status: ProgramEnrollmentStatus;
+ _count: number;
+ }[]
+ | undefined
+ >({
+ query: {
+ groupBy: "status",
+ },
+ enabled: selectedFilter === "status" || !!searchParamsObj.status,
+ });
+
+ const filters = useMemo(
+ () => [
+ {
+ key: "country",
+ icon: Globe,
+ label: "Country",
+ options:
+ countriesCount?.map(({ country, _count }) => ({
+ value: country,
+ label: COUNTRIES[country] || country,
+ icon: <CountryFlag countryCode={country} />,
+ right: nFormatter(_count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "status",
+ icon: CircleDotted,
+ label: "Status",
+ options:
+ statusesCount?.map(({ status, _count }) => {
+ const {
+ label,
+ icon: Icon,
+ className,
+ } = PartnerStatusBadges[status];
+
+ return {
+ value: status,
+ label,
+ icon: <Icon className={cn(className, "size-4 bg-transparent")} />,
+ right: nFormatter(_count, { full: true }),
+ };
+ }) ?? null,
+ },
+ ],
+ [countriesCount, statusesCount],
+ );
+
+ const activeFilters = useMemo(() => {
+ const { country, status } = searchParamsObj;
+ return [
+ ...(country ? [{ key: "country", value: country }] : []),
+ ...(status ? [{ key: "status", value: status }] : []),
+ ];
+ }, [searchParamsObj]);
+
+ const onSelect = useCallback(
+ (key: string, value: any) =>
+ queryParams({
+ set: {
+ [key]: value,
+ },
+ del: "page",
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const onRemove = useCallback(
+ (key: string) =>
+ queryParams({
+ del: [key, "page"],
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const onRemoveAll = useCallback(
+ () =>
+ queryParams({
+ del: ["country", "status", "page"],
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const isFiltered = useMemo(() => activeFilters.length > 0, [activeFilters]);
+
+ return {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ isFiltered,
+ setSelectedFilter,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-referred-partners-count.ts b/apps/web/lib/partner-referrals/hooks/use-referred-partners-count.ts
new file mode 100644
index 0000000000..9970936ed7
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-referred-partners-count.ts
@@ -0,0 +1,39 @@
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+import * as z from "zod/v4";
+import { getReferredPartnersCountQuerySchema } from "../schemas";
+
+export function useReferredPartnersCount<T = number>({
+ query,
+ includeParams = ["country", "status"],
+ enabled = true,
+}: {
+ query?: z.infer<typeof getReferredPartnersCountQuerySchema>;
+ includeParams?: string[];
+ enabled?: boolean;
+} = {}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { getQueryString } = useRouterStuff();
+
+ const { data, error } = useSWR<T>(
+ enabled &&
+ programSlug &&
+ `/api/partner-profile/programs/${programSlug}/referrals/count${getQueryString(
+ query,
+ {
+ include: includeParams,
+ },
+ )}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/hooks/use-referred-partners.ts b/apps/web/lib/partner-referrals/hooks/use-referred-partners.ts
new file mode 100644
index 0000000000..951d1931bd
--- /dev/null
+++ b/apps/web/lib/partner-referrals/hooks/use-referred-partners.ts
@@ -0,0 +1,25 @@
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+import { ReferredPartnerProps } from "../types";
+
+export function useReferredPartners() {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { getQueryString } = useRouterStuff();
+
+ const { data, isLoading, error } = useSWR<ReferredPartnerProps[]>(
+ programSlug &&
+ `/api/partner-profile/programs/${programSlug}/referrals${getQueryString()}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ isLoading,
+ error,
+ };
+}
diff --git a/apps/web/lib/partner-referrals/schemas.ts b/apps/web/lib/partner-referrals/schemas.ts
new file mode 100644
index 0000000000..4deb5ca72e
--- /dev/null
+++ b/apps/web/lib/partner-referrals/schemas.ts
@@ -0,0 +1,75 @@
+import { ProgramEnrollmentStatus } from "@dub/prisma/client";
+import { COUNTRIES } from "@dub/utils";
+import * as z from "zod/v4";
+import { getPaginationQuerySchema } from "../zod/schemas/misc";
+import { PartnerSchema } from "../zod/schemas/partners";
+import { centsSchemaWithDefault } from "../zod/schemas/utils";
+
+export const partnerReferralSchema = z.object({
+ referredBy: PartnerSchema.pick({
+ id: true,
+ name: true,
+ image: true,
+ }).nullable(),
+ stats: z.object({
+ totalPartners: z.number(),
+ totalConversions: z.number(),
+ totalSaleAmount: z.number(),
+ }),
+});
+
+export const referredPartnerSchema = PartnerSchema.pick({
+ id: true,
+ email: true,
+ country: true,
+}).extend({
+ programEnrollment: z.object({
+ createdAt: z.date(),
+ status: z.enum(ProgramEnrollmentStatus),
+ earnings: centsSchemaWithDefault,
+ }),
+});
+
+export const getReferredPartnersQuerySchema = z
+ .object({
+ country: z.enum(Object.keys(COUNTRIES)).optional(),
+ status: z.enum(ProgramEnrollmentStatus).optional(),
+ })
+ .extend(getPaginationQuerySchema({ pageSize: 100 }));
+
+export const getReferredPartnersCountQuerySchema =
+ getReferredPartnersQuerySchema
+ .omit({
+ page: true,
+ pageSize: true,
+ })
+ .extend({
+ groupBy: z.enum(["country", "status"]).optional(),
+ });
+
+export const networkReferralSchema = PartnerSchema.pick({
+ id: true,
+ email: true,
+ country: true,
+ createdAt: true,
+}).extend({
+ totalEarnings: centsSchemaWithDefault,
+ activeProgramsCount: z.number().int().nonnegative(),
+});
+
+export const getNetworkReferralsQuerySchema = z.object({}).extend(
+ getPaginationQuerySchema({
+ pageSize: 100,
+ }),
+);
+
+export const networkReferralsStatsSchema = z.object({
+ count: z.number().int().nonnegative(),
+ totalEarnings: z.number().int(),
+});
+
+export const networkReferralsTimeseriesSchema = z.object({
+ start: z.string(),
+ partners: z.number().int().nonnegative(),
+ earnings: z.number().int(),
+});
diff --git a/apps/web/lib/partner-referrals/types.ts b/apps/web/lib/partner-referrals/types.ts
new file mode 100644
index 0000000000..1b9d0018e4
--- /dev/null
+++ b/apps/web/lib/partner-referrals/types.ts
@@ -0,0 +1,23 @@
+import * as z from "zod/v4";
+import { referralRewardConfigSchema } from "../zod/schemas/rewards";
+import {
+ networkReferralSchema,
+ networkReferralsStatsSchema,
+ networkReferralsTimeseriesSchema,
+ partnerReferralSchema,
+ referredPartnerSchema,
+} from "./schemas";
+
+export type ReferralRewardConfig = z.infer<typeof referralRewardConfigSchema>;
+
+export type PartnerReferral = z.infer<typeof partnerReferralSchema>;
+
+export type ReferredPartnerProps = z.infer<typeof referredPartnerSchema>;
+
+export type NetworkReferralProps = z.infer<typeof networkReferralSchema>;
+
+export type NetworkReferralsStats = z.infer<typeof networkReferralsStatsSchema>;
+
+export type NetworkReferralsTimeseries = z.infer<
+ typeof networkReferralsTimeseriesSchema
+>;
diff --git a/apps/web/lib/partner-referrals/utils.ts b/apps/web/lib/partner-referrals/utils.ts
new file mode 100644
index 0000000000..ccf217fff0
--- /dev/null
+++ b/apps/web/lib/partner-referrals/utils.ts
@@ -0,0 +1,22 @@
+import { PARTNERS_DOMAIN } from "@dub/utils";
+import { PartnerProps, ProgramProps } from "../types";
+
+// Construct the program or Dub Network referral link
+// Examples are
+// https://partners.dub.co/register?via=johndoe
+// https://partners.dub.co/acme/apply?via=johndoe
+export const constructPartnerReferralLink = ({
+ partner,
+ program,
+}: {
+ partner: Pick<PartnerProps, "username"> | undefined;
+ program?: Pick<ProgramProps, "slug">;
+}) => {
+ const viaQuery = partner?.username
+ ? `?via=${encodeURIComponent(partner.username)}`
+ : "";
+
+ const path = program ? `/${program.slug}/apply` : "/register";
+
+ return `${PARTNERS_DOMAIN}${path}${viaQuery}`;
+};
diff --git a/apps/web/lib/partners/constuct-webhook-partner.ts b/apps/web/lib/partners/constuct-webhook-partner.ts
new file mode 100644
index 0000000000..ff29af4bc5
--- /dev/null
+++ b/apps/web/lib/partners/constuct-webhook-partner.ts
@@ -0,0 +1,19 @@
+import { Link, Partner, ProgramEnrollment } from "@dub/prisma/client";
+import { toCentsNumber } from "@dub/utils";
+import { aggregatePartnerLinksStats } from "./aggregate-partner-links-stats";
+
+export const constructWebhookPartner = (
+ programEnrollment: ProgramEnrollment & { partner: Partner; links: Link[] },
+ {
+ totalCommissions: totalCommissionsParam,
+ }: { totalCommissions?: number } = {},
+) => {
+ const totalCommissions =
+ totalCommissionsParam ?? toCentsNumber(programEnrollment.totalCommissions);
+ return {
+ ...programEnrollment.partner,
+ groupId: programEnrollment.groupId,
+ ...aggregatePartnerLinksStats(programEnrollment.links),
+ totalCommissions,
+ };
+};
diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.ts
index b3daed102d..5036dd96f1 100644
--- a/apps/web/lib/partners/create-partner-commission.ts
+++ b/apps/web/lib/partners/create-partner-commission.ts
@@ -3,9 +3,6 @@ import {
Commission,
CommissionStatus,
CommissionType,
- Link,
- Partner,
- ProgramEnrollment,
} from "@dub/prisma/client";
import { currencyFormatter, log, prettyPrint, toCentsNumber } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
@@ -23,7 +20,7 @@ import { RewardContext, RewardProps } from "../types";
import { sendWorkspaceWebhook } from "../webhook/publish";
import { CommissionWebhookSchema } from "../zod/schemas/commissions";
import { DEFAULT_PARTNER_GROUP } from "../zod/schemas/groups";
-import { aggregatePartnerLinksStats } from "./aggregate-partner-links-stats";
+import { constructWebhookPartner } from "./constuct-webhook-partner";
import { determinePartnerReward } from "./determine-partner-reward";
import { getRewardAmount } from "./get-reward-amount";
@@ -45,22 +42,6 @@ export type CreatePartnerCommissionProps = {
skipWorkflow?: boolean;
};
-const constructWebhookPartner = (
- programEnrollment: ProgramEnrollment & { partner: Partner; links: Link[] },
- {
- totalCommissions: totalCommissionsParam,
- }: { totalCommissions?: number } = {},
-) => {
- const totalCommissions =
- totalCommissionsParam ?? toCentsNumber(programEnrollment.totalCommissions);
- return {
- ...programEnrollment.partner,
- groupId: programEnrollment.groupId,
- ...aggregatePartnerLinksStats(programEnrollment.links),
- totalCommissions,
- };
-};
-
export const createPartnerCommission = async ({
event,
partnerId,
diff --git a/apps/web/lib/partners/create-stablecoin-payout.ts b/apps/web/lib/partners/create-stablecoin-payout.ts
index 96e575d91b..c8d1c2bcd7 100644
--- a/apps/web/lib/partners/create-stablecoin-payout.ts
+++ b/apps/web/lib/partners/create-stablecoin-payout.ts
@@ -4,7 +4,11 @@ import PartnerPayoutForceWithdrawal from "@dub/email/templates/partner-payout-fo
import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
import { prisma } from "@dub/prisma";
import { PartnerPayoutMethod, Prisma } from "@dub/prisma/client";
-import { currencyFormatter, prettyPrint } from "@dub/utils";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ currencyFormatter,
+ prettyPrint,
+} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import {
BELOW_MIN_WITHDRAWAL_FEE_CENTS,
@@ -12,6 +16,7 @@ import {
MIN_WITHDRAWAL_AMOUNT_CENTS,
STABLECOIN_PAYOUT_FEE_RATE,
} from "../constants/payouts";
+import { enqueueBatchJobs } from "../cron/enqueue-batch-jobs";
import { createPayoutsIdempotencyKey } from "../payouts/create-payouts-idempotency-key";
import { markPayoutsAsProcessed } from "../payouts/mark-payouts-as-processed";
import { createStripeOutboundPayment } from "../stripe/create-stripe-outbound-payment";
@@ -276,11 +281,23 @@ export const createStablecoinPayout = async ({
]);
waitUntil(
- trackCommissionStatusUpdatesByProgram({
- commissions,
- payouts: allPayouts,
- newStatus: "paid",
- }),
+ 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) {
diff --git a/apps/web/lib/partners/create-stripe-transfer.ts b/apps/web/lib/partners/create-stripe-transfer.ts
index 52e9452b24..7b94f621db 100644
--- a/apps/web/lib/partners/create-stripe-transfer.ts
+++ b/apps/web/lib/partners/create-stripe-transfer.ts
@@ -10,8 +10,13 @@ import PartnerPayoutForceWithdrawal from "@dub/email/templates/partner-payout-fo
import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
-import { currencyFormatter, pluralize } from "@dub/utils";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ currencyFormatter,
+ pluralize,
+} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { enqueueBatchJobs } from "../cron/enqueue-batch-jobs";
import { createPayoutsIdempotencyKey } from "../payouts/create-payouts-idempotency-key";
import { markPayoutsAsProcessed } from "../payouts/mark-payouts-as-processed";
@@ -243,11 +248,23 @@ export const createStripeTransfer = async ({
]);
waitUntil(
- trackCommissionStatusUpdatesByProgram({
- commissions,
- payouts: allPayouts,
- newStatus: "paid",
- }),
+ 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) {
diff --git a/apps/web/lib/partners/query-link-structure-help-text.tsx b/apps/web/lib/partners/query-link-structure-help-text.tsx
index d5c394f66e..28c0e64af9 100644
--- a/apps/web/lib/partners/query-link-structure-help-text.tsx
+++ b/apps/web/lib/partners/query-link-structure-help-text.tsx
@@ -1,11 +1,13 @@
import { CopyText } from "@dub/ui";
-import { getDomainWithoutWWW } from "@dub/utils";
+import { cn, getDomainWithoutWWW } from "@dub/utils";
import { PartnerProfileLinkProps } from "../types";
export const QueryLinkStructureHelpText = ({
link,
+ className,
}: {
link?: Pick<PartnerProfileLinkProps, "key" | "url" | "shortLink">;
+ className?: string;
}) => {
if (!link) {
return null;
@@ -13,7 +15,7 @@ export const QueryLinkStructureHelpText = ({
const appendValue = `?via=${link.key}`;
return (
- <p className="mt-1.5 text-xs text-neutral-500">
+ <p className={cn("text-xs text-neutral-500", className)}>
Link to any page on{" "}
<a
href={link.url}
diff --git a/apps/web/lib/partners/sort-rewards-by-event-order.ts b/apps/web/lib/partners/sort-rewards-by-event-order.ts
index 7fc78e3904..81af9bb5e0 100644
--- a/apps/web/lib/partners/sort-rewards-by-event-order.ts
+++ b/apps/web/lib/partners/sort-rewards-by-event-order.ts
@@ -4,6 +4,7 @@ const DEFAULT_REWARD_EVENT_ORDER = [
EventType.click,
EventType.lead,
EventType.sale,
+ EventType.referral,
] as const;
export function sortRewardsByEventOrder<T extends Pick<Reward, "event">>(
diff --git a/apps/web/lib/partnerstack/import-partners.ts b/apps/web/lib/partnerstack/import-partners.ts
index 3393f9e433..181eac8b21 100644
--- a/apps/web/lib/partnerstack/import-partners.ts
+++ b/apps/web/lib/partnerstack/import-partners.ts
@@ -185,6 +185,7 @@ async function createPartner({
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
update: {
diff --git a/apps/web/lib/plan-capabilities.ts b/apps/web/lib/plan-capabilities.ts
index 1028e3ee86..0250ff649a 100644
--- a/apps/web/lib/plan-capabilities.ts
+++ b/apps/web/lib/plan-capabilities.ts
@@ -25,5 +25,7 @@ export const getPlanCapabilities = (
!!plan && ["enterprise", "advanced"].includes(plan),
canRequestSlackSupportInvite:
!!plan && ["enterprise", "advanced"].includes(plan),
+ canCreateReferralReward:
+ !!plan && ["enterprise", "advanced"].includes(plan),
};
};
diff --git a/apps/web/lib/rewardful/import-partners.ts b/apps/web/lib/rewardful/import-partners.ts
index acbea09e95..4e7b558e41 100644
--- a/apps/web/lib/rewardful/import-partners.ts
+++ b/apps/web/lib/rewardful/import-partners.ts
@@ -92,9 +92,10 @@ export async function importPartners(payload: RewardfulImportPayload) {
userId,
defaultGroupAttributes: {
groupId: group.id,
- saleRewardId: group.saleRewardId,
- leadRewardId: group.leadRewardId,
clickRewardId: group.clickRewardId,
+ leadRewardId: group.leadRewardId,
+ saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
partnerGroupDefaultLinkId:
@@ -166,6 +167,7 @@ async function createPartnerAndLinks({
saleRewardId: string | null;
leadRewardId: string | null;
clickRewardId: string | null;
+ referralRewardId: string | null;
discountId: string | null;
};
partnerGroupDefaultLinkId?: string | null;
diff --git a/apps/web/lib/stripe/create-connected-account.ts b/apps/web/lib/stripe/create-connected-account.ts
index b81fbfcf44..39aed94227 100644
--- a/apps/web/lib/stripe/create-connected-account.ts
+++ b/apps/web/lib/stripe/create-connected-account.ts
@@ -6,10 +6,9 @@ export const createConnectedAccount = async ({
country,
profileType,
companyName,
-}: Pick<
- z.infer<typeof onboardPartnerSchema>,
- "country" | "profileType" | "companyName"
->) => {
+}: Pick<z.infer<typeof onboardPartnerSchema>, "profileType" | "companyName"> & {
+ country: string;
+}) => {
try {
return await stripe.accounts.create({
type: "express",
diff --git a/apps/web/lib/swr/use-commission-analytics.ts b/apps/web/lib/swr/use-commission-analytics.ts
index c014e799ad..e2bce024db 100644
--- a/apps/web/lib/swr/use-commission-analytics.ts
+++ b/apps/web/lib/swr/use-commission-analytics.ts
@@ -13,9 +13,8 @@ export type CommissionAnalyticsFilterKey = Extract<
"partnerId" | "groupId" | "partnerTagId" | "type"
>;
-interface UseCommissionAnalyticsProps<
- G extends CommissionAnalyticsGroupBy,
-> extends Partial<Omit<CommissionAnalyticsQuery, "groupBy">> {
+interface UseCommissionAnalyticsProps<G extends CommissionAnalyticsGroupBy>
+ extends Partial<Omit<CommissionAnalyticsQuery, "groupBy">> {
groupBy: G;
exclude?: CommissionAnalyticsFilterKey[];
enabled?: boolean;
@@ -34,11 +33,7 @@ function serializeCommissionAnalyticsFilters(
export default function useCommissionAnalytics<
G extends CommissionAnalyticsGroupBy,
->({
- exclude,
- enabled = true,
- ...filters
-}: UseCommissionAnalyticsProps<G>) {
+>({ exclude, enabled = true, ...filters }: UseCommissionAnalyticsProps<G>) {
const { id: workspaceId } = useWorkspace();
const { getQueryString } = useRouterStuff();
@@ -51,8 +46,7 @@ export default function useCommissionAnalytics<
...serialized,
...(workspaceId ? { workspaceId } : {}),
timezone:
- serialized.timezone ??
- Intl.DateTimeFormat().resolvedOptions().timeZone,
+ serialized.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
},
{
exclude: [
@@ -74,9 +68,7 @@ export default function useCommissionAnalytics<
);
const url =
- workspaceId && enabled
- ? `/api/commissions/analytics${querySuffix}`
- : null;
+ workspaceId && enabled ? `/api/commissions/analytics${querySuffix}` : null;
const { data, error, isLoading } = useSWR<CommissionAnalyticsByGroup[G]>(
url,
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index a2acea0cd2..21cac82baf 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -95,6 +95,7 @@ import {
import {
CommissionDetailSchema,
CommissionEnrichedSchema,
+ CommissionSchema,
} from "./zod/schemas/commissions";
import { customerActivityResponseSchema } from "./zod/schemas/customer-activity";
import {
@@ -975,3 +976,5 @@ export type ApplicationAnalyticsByGroup = {
(typeof applicationEventAnalyticsSchema)[K]
>;
};
+
+export type CommissionProps = z.infer<typeof CommissionSchema>;
diff --git a/apps/web/lib/webhook/sample-events/partner-enrolled.json b/apps/web/lib/webhook/sample-events/partner-enrolled.json
index ae55f9f58a..8bb670b818 100644
--- a/apps/web/lib/webhook/sample-events/partner-enrolled.json
+++ b/apps/web/lib/webhook/sample-events/partner-enrolled.json
@@ -1,6 +1,7 @@
{
"id": "pn_1K9BZE1K285BSTX4W6MPKXJFZ",
"name": "Matthew Hayden",
+ "username": "matthew-hayden",
"email": "[email protected]",
"image": null,
"country": "MR",
@@ -30,6 +31,7 @@
"clickRewardId": null,
"leadRewardId": null,
"saleRewardId": "rw_1KEC01MXCW9RK7PQMCTZQCPB3",
+ "referralRewardId": null,
"discountId": "disc_1KEC01MXC5H50XQMSN83VCW65",
"bannedAt": null,
"bannedReason": null,
diff --git a/apps/web/lib/zod/schemas/activity-log.ts b/apps/web/lib/zod/schemas/activity-log.ts
index bb866cb6f7..1ed86e9574 100644
--- a/apps/web/lib/zod/schemas/activity-log.ts
+++ b/apps/web/lib/zod/schemas/activity-log.ts
@@ -7,6 +7,7 @@ export const activityLogResourceTypeSchema = z.enum([
"clickReward",
"saleReward",
"leadReward",
+ "referralReward",
"submittedLead",
]);
@@ -65,4 +66,5 @@ export const REWARD_EVENT_TO_RESOURCE_TYPE = {
click: "clickReward",
sale: "saleReward",
lead: "leadReward",
+ referral: "referralReward",
} as const;
diff --git a/apps/web/lib/zod/schemas/groups.ts b/apps/web/lib/zod/schemas/groups.ts
index 39fd1378d4..dfa2a5142f 100644
--- a/apps/web/lib/zod/schemas/groups.ts
+++ b/apps/web/lib/zod/schemas/groups.ts
@@ -67,6 +67,7 @@ export const GroupSchema = z.object({
clickReward: RewardSchema.nullish(),
leadReward: RewardSchema.nullish(),
saleReward: RewardSchema.nullish(),
+ referralReward: RewardSchema.nullish(),
discount: DiscountSchema.nullish(),
utmTemplate: UTMTemplateSchema.nullish(),
additionalLinks: z.array(additionalPartnerLinkSchema).nullable(),
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 656c9c6354..70460a28c3 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -14,7 +14,6 @@ import {
ProgramEnrollmentStatus,
SalesChannel,
} from "@dub/prisma/client";
-import { COUNTRY_CODES } from "@dub/utils";
import * as z from "zod/v4";
import { analyticsQuerySchema } from "./analytics";
import { analyticsResponse } from "./analytics-response";
@@ -208,6 +207,7 @@ export const getPartnersQuerySchemaExtended = getPartnersQuerySchema.extend({
.optional(),
groupId: z.union([z.string(), z.array(z.string())]).optional(),
country: z.union([z.string(), z.array(z.string())]).optional(),
+ referredByPartnerId: z.string().optional(),
includePartnerPlatforms: booleanQuerySchema.optional(),
// metric range query fields (TODO: Add to public API once we finalize the syntax)
totalClicksMin: z.coerce
@@ -290,7 +290,13 @@ export const partnersCountQuerySchema = getPartnersQuerySchemaExtended
})
.extend({
groupBy: z
- .enum(["status", "country", "groupId", "partnerTagId"])
+ .enum([
+ "status",
+ "country",
+ "groupId",
+ "partnerTagId",
+ "referredByPartnerId",
+ ])
.optional(),
});
@@ -362,7 +368,10 @@ export const PartnerSchema = z
.object({
id: z.string().describe("The partner's unique ID on Dub."),
name: z.string().max(190).describe("The partner's full legal name."),
- username: z.string().nullable().describe("The partner's unique username."),
+ username: z
+ .string()
+ .nullable()
+ .describe("The partner's unique username on Dub."),
email: z
.string()
.max(190)
@@ -476,6 +485,7 @@ export const PartnerRewindSchema = z.object({
export const EnrolledPartnerSchema = PartnerSchema.pick({
id: true,
name: true,
+ username: true,
email: true,
image: true,
description: true,
@@ -735,12 +745,12 @@ export const onboardPartnerSchema = createPartnerSchema
.omit({
username: true,
email: true,
+ country: true,
linkProps: true,
})
.extend({
name: z.string().min(1, "Name is required"),
image: partnerImageSchema,
- country: z.enum(COUNTRY_CODES),
profileType: z.enum(PartnerProfileType).default("individual"),
companyName: z.string().nullish(),
})
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index 3750d254d2..84a023cbf4 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -162,6 +162,7 @@ export const ProgramEnrollmentSchema = z.object({
clickRewardId: z.string().nullish(),
leadRewardId: z.string().nullish(),
saleRewardId: z.string().nullish(),
+ referralRewardId: z.string().nullish(),
discount: DiscountSchema.nullish(),
discountId: z.string().nullish(),
applicationId: z
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 9242b859a4..54f4e43503 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -1,3 +1,4 @@
+import { PARTNER_REFERRAL_TRIGGER } from "@/lib/partner-referrals/constants";
import { EventType, RewardStructure } from "@dub/prisma/client";
import * as z from "zod/v4";
import { getPaginationQuerySchema, maxDurationSchema } from "./misc";
@@ -199,6 +200,11 @@ export const REWARD_CONDITIONS: Record<
},
],
},
+
+ // Partner referral reward
+ referral: {
+ entities: [],
+ },
};
export const REWARD_CONDITION_ENTITIES = [
@@ -325,12 +331,31 @@ export const RewardSchema = z.object({
amountInPercentage: decimalToNumber,
maxDuration: z.number().nullish(),
modifiers: z.any().nullish(), // TODO: Fix this
+ config: z.any().nullish(),
updatedAt: z.coerce.date(),
});
export const REWARD_DESCRIPTION_MAX_LENGTH = 100;
export const REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH = 2000;
+export const referralRewardConfigSchema = z
+ .object({
+ trigger: z.enum(PARTNER_REFERRAL_TRIGGER),
+ commissionsThresholdInCents: z.number().int().min(100).optional(),
+ })
+ .superRefine((data, ctx) => {
+ if (
+ data.trigger === "commissionThreshold" &&
+ data.commissionsThresholdInCents == null
+ ) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["commissionsThresholdInCents"],
+ message: "Please enter a commission threshold amount.",
+ });
+ }
+ });
+
export const createOrUpdateRewardSchema = z.object({
workspaceId: z.string(),
event: z.enum(EventType),
@@ -339,6 +364,7 @@ export const createOrUpdateRewardSchema = z.object({
amountInPercentage: PERCENTAGE_REWARD_AMOUNT_SCHEMA.optional(),
maxDuration: maxDurationSchema,
modifiers: rewardConditionsArraySchema.nullish(),
+ config: referralRewardConfigSchema.nullish(),
description: z.string().max(REWARD_DESCRIPTION_MAX_LENGTH).nullish(),
tooltipDescription: z
.string()
@@ -349,7 +375,7 @@ export const createOrUpdateRewardSchema = z.object({
export const createRewardSchema = createOrUpdateRewardSchema.superRefine(
(data) => {
- if (data.event !== EventType.sale) {
+ if (data.event === EventType.click || data.event === EventType.lead) {
data.maxDuration = 0;
data.type = "flat";
}
@@ -375,6 +401,7 @@ export const REWARD_EVENT_COLUMN_MAPPING = Object.freeze({
click: "clickRewardId",
lead: "leadRewardId",
sale: "saleRewardId",
+ referral: "referralRewardId",
});
export const CUSTOMER_SOURCES = ["tracked", "submitted", "trial"] as const;
diff --git a/apps/web/playwright/partners/onboarding.spec.ts b/apps/web/playwright/partners/onboarding.spec.ts
index ef8dc68922..d888115680 100644
--- a/apps/web/playwright/partners/onboarding.spec.ts
+++ b/apps/web/playwright/partners/onboarding.spec.ts
@@ -13,109 +13,59 @@ test.describe("Partner onboarding", () => {
test("onboarding page renders", async ({ page }) => {
await page.goto("/onboarding");
- await expect(
- page.getByRole("heading", { name: "Create your partner profile" }),
- ).toBeVisible();
+ await expect(page.getByText("Create your partner profile")).toBeVisible();
await expect(page.locator('input[name="name"]').first()).toBeVisible();
- await expect(page.getByText("Profile image")).toBeVisible();
- await expect(page.getByLabel("Country")).toBeVisible();
- await expect(page.getByText("About you")).toBeVisible();
- await expect(page.getByText("Profile Type")).toBeVisible();
+ await expect(page.getByText("Profile image").first()).toBeVisible();
+ await expect(page.getByText("About you").first()).toBeVisible();
+ await expect(page.getByText("Profile Type").first()).toBeVisible();
await expect(page.getByRole("button", { name: "Continue" })).toBeVisible();
});
test("profile submit redirects to platforms", async ({ page }) => {
await page.goto("/onboarding");
+ await page.waitForLoadState("networkidle");
- const nameInput = page.locator('input[name="name"]').first();
- const countryField = page.getByLabel("Country");
- const searchCountriesInput = page.getByPlaceholder("Search countries...");
+ const nameInput = page.locator('input[name="name"]');
const continueButton = page.getByRole("button", { name: "Continue" });
- const acknowledgeButton = page.getByRole("button", {
- name: "I acknowledge",
- });
await nameInput.fill("E2E Onboarding Test");
- await countryField.click();
-
- if (
- await acknowledgeButton.isVisible({ timeout: 2000 }).catch(() => false)
- ) {
- await acknowledgeButton.click();
- }
-
- await expect(searchCountriesInput).toBeVisible({
- timeout: 5000,
- });
- await searchCountriesInput.fill("United States");
- await page.getByText("United States", { exact: true }).first().click();
-
await continueButton.click();
- await page.waitForURL(/\/onboarding\/platforms/);
+ await page.waitForURL("/onboarding/platforms");
await expect(
- page.getByRole("heading", {
- name: "Your social and web platforms",
- }),
+ page.getByText("Your social and web platforms", { exact: true }),
).toBeVisible();
});
- test("platforms step skip link goes to payouts or programs", async ({
- page,
- }) => {
+ test("platforms step skip link goes to payouts", async ({ page }) => {
await page.goto("/onboarding");
+ await page.waitForLoadState("networkidle");
const nameInput = page.locator('input[name="name"]').first();
- const countryField = page.getByLabel("Country");
- const searchCountriesInput = page.getByPlaceholder("Search countries...");
const continueButton = page.getByRole("button", { name: "Continue" });
- const skipLink = page.getByRole("link", {
- name: "I'll complete this later",
- });
- const acknowledgeButton = page.getByRole("button", {
- name: "I acknowledge",
- });
await nameInput.fill("E2E Onboarding Test");
- await countryField.click();
-
- if (
- await acknowledgeButton.isVisible({ timeout: 2000 }).catch(() => false)
- ) {
- await acknowledgeButton.click();
- }
-
- await expect(searchCountriesInput).toBeVisible({
- timeout: 5000,
- });
- await searchCountriesInput.fill("United States");
- await page.getByText("United States", { exact: true }).first().click();
await continueButton.click();
- await page.waitForURL(/\/onboarding\/platforms/);
+ await page.waitForURL("/onboarding/platforms");
+ const skipLink = page.getByRole("link", {
+ name: "I'll complete this later",
+ });
+ await expect(skipLink).toBeVisible();
await skipLink.click();
- await expect(page).toHaveURL(/\/(onboarding\/payouts|programs)/);
- if (page.url().includes("/onboarding/payouts")) {
- await expect(
- page.getByRole("heading", { name: "Connect payouts" }),
- ).toBeVisible();
- }
+ await expect(page).toHaveURL("/onboarding/payouts");
});
test("payouts step skip link goes to programs", async ({ page }) => {
await page.goto("/onboarding/payouts");
- await page.waitForURL(/\/(onboarding\/payouts|programs)/);
-
- if (page.url().includes("/programs")) {
- return;
- }
-
const skipLink = page.getByRole("link", {
name: "I'll complete this later",
});
+ await expect(skipLink).toBeVisible();
await skipLink.click();
- await expect(page).toHaveURL(/\/programs/);
+
+ await expect(page).toHaveURL("/programs");
});
});
diff --git a/apps/web/scripts/dev/data.json b/apps/web/scripts/dev/data.json
index ec2e217563..e8365a9724 100644
--- a/apps/web/scripts/dev/data.json
+++ b/apps/web/scripts/dev/data.json
@@ -15,7 +15,8 @@
"usersLimit": 100,
"aiLimit": 100,
"groupsLimit": 100,
- "defaultProgramId": "prog_1K2J9DRWPPJ2F1RX53N92TSGA",
+ "partnersLimit": 100,
+ "defaultProgramId": "prog_CYCu7IMAapjkRpTnr8F1azjN",
"invoicePrefix": "ACME",
"conversionEnabled": true,
"webhookEnabled": true,
@@ -112,7 +113,7 @@
}
],
"program": {
- "id": "prog_1K2J9DRWPPJ2F1RX53N92TSGA",
+ "id": "prog_CYCu7IMAapjkRpTnr8F1azjN",
"name": "Acme",
"slug": "acme",
"defaultFolderId": "fold_1K2J9DRWPPJ2F1RX53N92TSGB",
diff --git a/apps/web/scripts/dev/seed-application-events.ts b/apps/web/scripts/dev/seed-application-events.ts
index f8a14bd3e4..6c3368a14c 100644
--- a/apps/web/scripts/dev/seed-application-events.ts
+++ b/apps/web/scripts/dev/seed-application-events.ts
@@ -1,4 +1,5 @@
import { prisma } from "@dub/prisma";
+import { ACME_PROGRAM_ID } from "@dub/utils";
import "dotenv-flow/config";
const randomDateBetween = (start: Date, end: Date) => {
@@ -24,11 +25,15 @@ const referralSources = [
] as const;
async function main() {
- const programId = "prog_1K2J9DRWPPJ2F1RX53N92TSGA";
+ const programId = ACME_PROGRAM_ID;
+ const referredByPartnerIds = ["pn_1K2J9DRWPPJ2F1RX53N92TSGH"];
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
programId,
+ partnerId: {
+ notIn: referredByPartnerIds,
+ },
},
orderBy: {
createdAt: "asc",
@@ -41,7 +46,7 @@ async function main() {
},
},
},
- take: 10,
+ take: 1,
});
if (programEnrollments.length === 0) {
@@ -80,7 +85,7 @@ async function main() {
rejectedAt: isApproved ? null : decidedAt,
referralSource: sample(referralSources),
country: programEnrollment.partner.country ?? null,
- // intentionally leaving: referredByPartnerId, programApplicationId
+ referredByPartnerId: sample(referredByPartnerIds),
};
}),
skipDuplicates: true,
diff --git a/apps/web/scripts/dev/seed-commissions.ts b/apps/web/scripts/dev/seed-commissions.ts
new file mode 100644
index 0000000000..9898f15a7c
--- /dev/null
+++ b/apps/web/scripts/dev/seed-commissions.ts
@@ -0,0 +1,41 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import "dotenv-flow/config";
+
+async function main() {
+ const programId = "prog_1K2J9DRWPPJ2F1RX53N92TSGA";
+ const partnerId = "pn_1K2J9DRWPPJ2F1RX53N92TSGG";
+
+ const commissions: Prisma.CommissionCreateManyInput[] = [
+ {
+ id: createId({ prefix: "cm_" }),
+ programId,
+ partnerId,
+ type: "referral",
+ amount: 0,
+ quantity: 1,
+ earnings: 10000,
+ createdAt: new Date(),
+ },
+ {
+ id: createId({ prefix: "cm_" }),
+ programId,
+ partnerId,
+ type: "referral",
+ amount: 0,
+ quantity: 1,
+ earnings: 20000,
+ createdAt: new Date(),
+ },
+ ];
+
+ const response = await prisma.commission.createMany({
+ data: commissions,
+ skipDuplicates: true,
+ });
+
+ console.log(response);
+}
+
+main();
diff --git a/apps/web/scripts/dev/seed-partner-enrollment.ts b/apps/web/scripts/dev/seed-partner-enrollment.ts
new file mode 100644
index 0000000000..2aeca0b629
--- /dev/null
+++ b/apps/web/scripts/dev/seed-partner-enrollment.ts
@@ -0,0 +1,83 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import "dotenv-flow/config";
+
+const programId = "prog_1K2J9DRWPPJ2F1RX53N92TSGA";
+const referredByPartnerId = "pn_1K2J9DRWPPJ2F1RX53N92TSGG";
+
+async function main() {
+ const program = await prisma.program.findUnique({
+ where: {
+ id: programId,
+ },
+ select: {
+ defaultGroupId: true,
+ },
+ });
+
+ if (!program) {
+ console.error(`Program not found: ${programId}`);
+ return;
+ }
+
+ const suffix = nanoid(3);
+ const email = `partner-${suffix}@dub-internal-test.com`;
+ const name = `Partner ${suffix}`;
+
+ const userId = createId({ prefix: "user_" });
+ const partnerId = createId({ prefix: "pn_" });
+
+ await prisma.user.create({
+ data: {
+ id: userId,
+ email,
+ name,
+ emailVerified: new Date(),
+ defaultPartnerId: partnerId,
+ },
+ });
+
+ await prisma.partner.create({
+ data: {
+ id: partnerId,
+ name,
+ email,
+ },
+ });
+
+ await prisma.partnerUser.create({
+ data: {
+ userId,
+ partnerId,
+ role: "owner",
+ },
+ });
+
+ await prisma.programEnrollment.create({
+ data: {
+ id: createId({ prefix: "pge_" }),
+ programId,
+ partnerId,
+ groupId: program.defaultGroupId,
+ status: "pending",
+ },
+ });
+
+ const now = new Date();
+
+ await prisma.programApplicationEvent.create({
+ data: {
+ programId,
+ partnerId,
+ referredByPartnerId,
+ referralSource: "direct",
+ visitedAt: now,
+ startedAt: now,
+ submittedAt: now,
+ approvedAt: now,
+ },
+ });
+}
+
+main();
diff --git a/apps/web/scripts/dev/seed.ts b/apps/web/scripts/dev/seed.ts
index 31735a349d..705517f7c1 100644
--- a/apps/web/scripts/dev/seed.ts
+++ b/apps/web/scripts/dev/seed.ts
@@ -37,6 +37,7 @@ type Workspace = Pick<
| "usersLimit"
| "aiLimit"
| "groupsLimit"
+ | "partnersLimit"
| "defaultProgramId"
| "invoicePrefix"
| "conversionEnabled"
@@ -501,6 +502,8 @@ const truncate = async () => {
"FraudEvent",
"FraudEventGroup",
"FraudRule",
+ "ActivityLog",
+ "ProgramApplicationEvent",
"ProgramApplication",
"ProgramEnrollment",
"PartnerGroup",
diff --git a/apps/web/scripts/dev/test-partner-referrals.ts b/apps/web/scripts/dev/test-partner-referrals.ts
new file mode 100644
index 0000000000..6a1b3f638d
--- /dev/null
+++ b/apps/web/scripts/dev/test-partner-referrals.ts
@@ -0,0 +1,25 @@
+import "dotenv-flow/config";
+
+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+
+async function main() {
+ const payouts = await prisma.payout.findMany({
+ where: {
+ programId: "prog_1K2J9DRWPPJ2F1RX53N92TSGA",
+ },
+ });
+
+ await enqueueBatchJobs(
+ payouts.map(({ id }) => ({
+ queueName: "create-referral-commissions",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/queue`,
+ body: {
+ payoutId: id,
+ },
+ })),
+ );
+}
+
+main();
diff --git a/apps/web/scripts/migrations/backfill-partner-usernames.ts b/apps/web/scripts/migrations/backfill-partner-usernames.ts
new file mode 100644
index 0000000000..45304904e6
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-partner-usernames.ts
@@ -0,0 +1,103 @@
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import slugify from "@sindresorhus/slugify";
+import "dotenv-flow/config";
+
+const BATCH_SIZE = 100;
+
+async function main() {
+ let totalProcessed = 0;
+
+ while (totalProcessed < 200) {
+ const partners = await prisma.partner.findMany({
+ where: {
+ username: null,
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ take: BATCH_SIZE,
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+
+ if (partners.length === 0) {
+ break;
+ }
+
+ // Derive usernames and deduplicate within the batch
+ const usernameEntries: { id: string; username: string }[] = [];
+ const seenInBatch = new Set<string>();
+
+ for (const partner of partners) {
+ let username = partner.name
+ ? slugify(partner.name)
+ : partner.email
+ ? `${slugify(partner.email.split("@")[0])}`
+ : null;
+
+ if (!username) {
+ continue;
+ }
+
+ username = `${username}-${nanoid(4).toLowerCase()}`;
+
+ while (seenInBatch.has(username)) {
+ username = `${username.slice(0, -5)}-${nanoid(4).toLowerCase()}`;
+ }
+
+ seenInBatch.add(username);
+ usernameEntries.push({ id: partner.id, username });
+ }
+
+ // Check conflicts against existing DB usernames
+ const existingPartners = await prisma.partner.findMany({
+ where: {
+ username: {
+ in: usernameEntries.map((e) => e.username),
+ },
+ },
+ select: {
+ username: true,
+ },
+ });
+
+ const existingUsernames = new Set(existingPartners.map((p) => p.username));
+
+ for (const entry of usernameEntries) {
+ if (existingUsernames.has(entry.username)) {
+ entry.username = `${entry.username.slice(0, -5)}-${nanoid(4).toLowerCase()}`;
+ }
+ }
+
+ console.log(usernameEntries);
+
+ // await Promise.allSettled(
+ // usernameEntries.map(({ id, username }) =>
+ // prisma.partner.update({
+ // where: {
+ // id,
+ // },
+ // data: {
+ // username,
+ // },
+ // }),
+ // ),
+ // );
+
+ totalProcessed += partners.length;
+
+ console.log(
+ `Backfilled ${partners.length} partner usernames (processed=${totalProcessed})`,
+ );
+ }
+
+ console.log(
+ `Done backfilling partner usernames (processed=${totalProcessed})`,
+ );
+}
+
+main();
diff --git a/apps/web/scripts/partners/fix-partner-groups.ts b/apps/web/scripts/partners/fix-partner-groups.ts
index 56fc81e4e1..7262899e4b 100644
--- a/apps/web/scripts/partners/fix-partner-groups.ts
+++ b/apps/web/scripts/partners/fix-partner-groups.ts
@@ -48,6 +48,7 @@ async function main() {
clickRewardId: group.clickRewardId,
leadRewardId: group.leadRewardId,
saleRewardId: group.saleRewardId,
+ referralRewardId: group.referralRewardId,
discountId: group.discountId,
},
});
diff --git a/apps/web/scripts/programs/bulk-star-partners.ts b/apps/web/scripts/programs/bulk-star-partners.ts
new file mode 100644
index 0000000000..f130f1c2b2
--- /dev/null
+++ b/apps/web/scripts/programs/bulk-star-partners.ts
@@ -0,0 +1,38 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import "dotenv-flow/config";
+
+const programId = "prog_xxx";
+const emails = ["[email protected]", "[email protected]"];
+
+async function main() {
+ for (const email of emails) {
+ const partner = await prisma.partner.findUniqueOrThrow({
+ where: {
+ email: email,
+ },
+ });
+
+ await prisma.discoveredPartner.upsert({
+ where: {
+ programId_partnerId: {
+ programId,
+ partnerId: partner.id,
+ },
+ },
+ create: {
+ id: createId({ prefix: "dpn_" }),
+ partnerId: partner.id,
+ programId,
+ starredAt: new Date(),
+ },
+ update: {
+ starredAt: new Date(),
+ },
+ });
+
+ console.log(`Starred partner ${partner.name} for program ${programId}`);
+ }
+}
+
+main();
diff --git a/apps/web/tests/partner-groups/index.test.ts b/apps/web/tests/partner-groups/index.test.ts
index 090cf2189c..994ece0428 100644
--- a/apps/web/tests/partner-groups/index.test.ts
+++ b/apps/web/tests/partner-groups/index.test.ts
@@ -28,6 +28,7 @@ const expectedGroup: Partial<GroupProps> = {
clickReward: null,
leadReward: null,
saleReward: null,
+ referralReward: null,
discount: null,
maxPartnerLinks: DEFAULT_ADDITIONAL_PARTNER_LINKS,
linkStructure: "short",
diff --git a/apps/web/ui/activity-logs/activity-feed.tsx b/apps/web/ui/activity-logs/activity-feed.tsx
index 65df8fe36b..44e88eee47 100644
--- a/apps/web/ui/activity-logs/activity-feed.tsx
+++ b/apps/web/ui/activity-logs/activity-feed.tsx
@@ -13,6 +13,7 @@ const ACTIVITY_ITEM_MAP: Record<
clickReward: RewardActivityItem,
leadReward: RewardActivityItem,
saleReward: RewardActivityItem,
+ referralReward: RewardActivityItem,
};
interface ActivityFeedProps {
diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
index 11afe2ae47..29fbb7b64e 100644
--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
@@ -13,9 +13,11 @@ import {
ColorPalette2,
Gauge6,
Gear2,
+ Gift,
GridIcon,
MoneyBills2,
Msgs,
+ Nodes4,
ShieldCheck,
Shop,
SquareUserSparkle2,
@@ -24,6 +26,8 @@ import {
Users2,
Webhook,
} from "@dub/ui/icons";
+import { cn } from "@dub/utils";
+import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import { ReactNode, useMemo } from "react";
import { CursorRays } from "./icons/cursor-rays";
@@ -45,6 +49,7 @@ type SidebarNavData = {
programBountiesCount?: number;
showDetailedAnalytics?: boolean;
postbacksEnabled?: boolean;
+ hasReferralReward?: boolean;
};
const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({
@@ -177,6 +182,7 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
queryString,
programBountiesCount,
showDetailedAnalytics,
+ hasReferralReward,
}) => ({
title: (
<div className="mb-3">
@@ -253,6 +259,16 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
: programBountiesCount || undefined,
locked: isUnapproved,
},
+ ...(hasReferralReward
+ ? [
+ {
+ name: "Partner Referrals",
+ icon: Nodes4 as Icon,
+ href: `/programs/${programSlug}/referrals` as `/${string}`,
+ locked: isUnapproved,
+ },
+ ]
+ : []),
{
name: "Resources",
icon: ColorPalette2,
@@ -351,6 +367,24 @@ export function PartnersSidebarNav({
const { partner } = usePartnerProfile();
+ const referralsActive =
+ pathname === "/referrals" || pathname.startsWith("/referrals/");
+
+ const composedToolContent = (
+ <div className="flex flex-col items-center gap-3">
+ <Link
+ href="/referrals"
+ className={cn(
+ "text-content-default flex size-11 shrink-0 items-center justify-center rounded-lg",
+ referralsActive ? "bg-white" : "hover:bg-bg-inverted/5",
+ )}
+ >
+ <Gift className="size-5" />
+ </Link>
+ {toolContent}
+ </div>
+ );
+
return (
<SidebarNav
groups={NAV_GROUPS}
@@ -366,8 +400,9 @@ export function PartnersSidebarNav({
programBountiesCount: bountiesCount.active,
showDetailedAnalytics,
postbacksEnabled: partner?.featureFlags?.postbacks,
+ hasReferralReward: !!programEnrollment?.referralRewardId,
}}
- toolContent={toolContent}
+ toolContent={composedToolContent}
newsContent={newsContent}
bottom={
isEnrolledProgramPage ? (
diff --git a/apps/web/ui/partners/comission-type-icon.tsx b/apps/web/ui/partners/comission-type-icon.tsx
index a23eb472d9..0d505c6232 100644
--- a/apps/web/ui/partners/comission-type-icon.tsx
+++ b/apps/web/ui/partners/comission-type-icon.tsx
@@ -3,6 +3,7 @@ import {
CursorRays,
InvoiceDollar,
MoneyBills2,
+ Nodes4,
UserCheck,
} from "@dub/ui/icons";
import { cn } from "@dub/utils";
@@ -13,6 +14,7 @@ const ICONS_MAP = {
lead: { icon: UserCheck, className: "text-purple-500" },
sale: { icon: InvoiceDollar, className: "text-teal-500" },
custom: { icon: MoneyBills2, className: "text-gray-500" },
+ referral: { icon: Nodes4, className: "text-gray-500" },
};
export const CommissionTypeIcon = ({
diff --git a/apps/web/ui/partners/commission-type-badge.tsx b/apps/web/ui/partners/commission-type-badge.tsx
index a942d9bd40..e14dd91faa 100644
--- a/apps/web/ui/partners/commission-type-badge.tsx
+++ b/apps/web/ui/partners/commission-type-badge.tsx
@@ -1,5 +1,6 @@
+import { CommissionProps, CustomerProps } from "@/lib/types";
import { PartnerEarningsSchema } from "@/lib/zod/schemas/partner-profile";
-import { capitalize } from "@dub/utils";
+import { capitalize, pluralize } from "@dub/utils";
import * as z from "zod/v4";
import { CommissionTypeIcon } from "./comission-type-icon";
@@ -15,3 +16,34 @@ export const CommissionTypeBadge = ({
</div>
);
};
+
+export function getCommissionTypeLabel(
+ commission: Pick<CommissionProps, "type" | "quantity"> & {
+ customer?: Pick<CustomerProps, "email" | "name"> | null;
+ },
+) {
+ if (commission.type === "click") {
+ return `${commission.quantity} ${pluralize("click", commission.quantity)}`;
+ }
+
+ if (
+ (commission.type === "lead" || commission.type === "sale") &&
+ commission.customer
+ ) {
+ const customerLabel = commission.customer.email ?? commission.customer.name;
+
+ if (customerLabel) {
+ return customerLabel;
+ }
+ }
+
+ if (commission.type === "referral") {
+ return "Partner referral";
+ }
+
+ if (commission.type === "custom") {
+ return "Custom commission";
+ }
+
+ return "-";
+}
diff --git a/apps/web/ui/partners/constants.ts b/apps/web/ui/partners/constants.ts
index 26959045ba..a59782af0d 100644
--- a/apps/web/ui/partners/constants.ts
+++ b/apps/web/ui/partners/constants.ts
@@ -1,29 +1,3 @@
-import { CursorRays, InvoiceDollar, UserPlus } from "@dub/ui/icons";
-
-export const REWARD_EVENTS = {
- click: {
- icon: CursorRays,
- text: "Click reward",
- event: "click",
- shortcut: "C",
- eventName: "click",
- },
- lead: {
- icon: UserPlus,
- text: "Lead reward",
- event: "lead",
- shortcut: "L",
- eventName: "signup",
- },
- sale: {
- icon: InvoiceDollar,
- text: "Sale reward",
- event: "sale",
- shortcut: "S",
- eventName: "sale",
- },
-} as const;
-
export const ERROR_MAP: Record<
string,
{ title: string; ctaLabel: string; ctaUrl: string }
diff --git a/apps/web/ui/partners/format-reward-description.ts b/apps/web/ui/partners/format-reward-description.ts
index b03a16d91d..cb5ca3ce2f 100644
--- a/apps/web/ui/partners/format-reward-description.ts
+++ b/apps/web/ui/partners/format-reward-description.ts
@@ -1,15 +1,32 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import {
+ PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS,
+ PARTNER_REFERRAL_PERCENTAGE_TRIGGERS,
+ PartnerReferralPercentageTrigger,
+} from "@/lib/partner-referrals/constants";
import { RewardProps } from "@/lib/types";
+import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { currencyFormatter } from "@dub/utils";
-export function formatRewardDescription(reward: RewardProps) {
+export function formatRewardDescription(
+ reward: RewardProps,
+ { includeEarnPrefix = true }: { includeEarnPrefix?: boolean } = {},
+) {
if (reward.description) {
return reward.description;
}
+ if (reward.event === "referral") {
+ return formatReferralRewardDescription(reward, { includeEarnPrefix });
+ }
+
const rewardAmount = constructRewardAmount(reward);
+
const parts: string[] = [];
- parts.push("Earn");
+ if (includeEarnPrefix) {
+ parts.push("Earn");
+ }
parts.push(rewardAmount);
if (reward.event === "sale" && reward.maxDuration === 0) {
@@ -30,3 +47,95 @@ export function formatRewardDescription(reward: RewardProps) {
return parts.join(" ");
}
+
+function formatReferralRewardDescription(
+ reward: RewardProps,
+ { includeEarnPrefix }: { includeEarnPrefix: boolean },
+) {
+ const rewardAmount = constructRewardAmount(reward);
+ const parsed = referralRewardConfigSchema.safeParse(reward.config);
+ const config = parsed.success ? parsed.data : undefined;
+
+ if (!config) {
+ const duration = formatReferralDuration(reward.maxDuration);
+ return [
+ includeEarnPrefix ? "Earn" : null,
+ rewardAmount,
+ "per",
+ "referral",
+ duration,
+ ]
+ .filter(Boolean)
+ .join(" ");
+ }
+
+ if (
+ reward.type === "percentage" &&
+ (PARTNER_REFERRAL_PERCENTAGE_TRIGGERS as readonly string[]).includes(
+ config.trigger,
+ )
+ ) {
+ const basis =
+ PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS[
+ config.trigger as PartnerReferralPercentageTrigger
+ ];
+ const duration = formatReferralDuration(reward.maxDuration);
+ return [
+ includeEarnPrefix ? "Earn" : null,
+ rewardAmount,
+ "per",
+ basis,
+ duration,
+ ]
+ .filter(Boolean)
+ .join(" ");
+ }
+
+ if (
+ reward.type === "flat" &&
+ config.trigger === "commissionThreshold" &&
+ config.commissionsThresholdInCents != null
+ ) {
+ const threshold = currencyFormatter(config.commissionsThresholdInCents, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ return `${includeEarnPrefix ? "Earn " : ""}${rewardAmount} when the referred partner earns at least ${threshold} in commissions`;
+ }
+
+ if (reward.type === "flat" && config.trigger === "partnerApproved") {
+ return `${includeEarnPrefix ? "Earn " : ""}${rewardAmount} when the referred partner is approved into the program`;
+ }
+
+ const duration = formatReferralDuration(reward.maxDuration);
+ return [
+ includeEarnPrefix ? "Earn" : null,
+ rewardAmount,
+ "per",
+ "referral",
+ duration,
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+function formatReferralDuration(maxDuration: number | null | undefined) {
+ if (maxDuration === null) {
+ return "for the customer's lifetime";
+ }
+
+ if (maxDuration === 0) {
+ return "one time";
+ }
+
+ if (maxDuration && maxDuration > 1) {
+ if (maxDuration % 12 === 0) {
+ const years = maxDuration / 12;
+ return `for ${years} year${years > 1 ? "s" : ""}`;
+ }
+
+ return `for ${maxDuration} months`;
+ }
+
+ return "";
+}
diff --git a/apps/web/ui/partners/lander/lander-rewards.tsx b/apps/web/ui/partners/lander/lander-rewards.tsx
index f11679af3c..b59457b610 100644
--- a/apps/web/ui/partners/lander/lander-rewards.tsx
+++ b/apps/web/ui/partners/lander/lander-rewards.tsx
@@ -10,9 +10,9 @@ import {
import { Gift, Heart, Icon, Trophy } from "@dub/ui";
import { cn } from "@dub/utils";
import { PropsWithChildren, useState } from "react";
-import { REWARD_EVENTS } from "../constants";
import { formatDiscountDescription } from "../format-discount-description";
import { ProgramRewardModifiersTooltip } from "../program-reward-modifiers-tooltip";
+import { REWARD_EVENT_ICON } from "../rewards/reward-event-icon";
const MAX_VISIBLE_BOUNTIES = 3;
@@ -62,7 +62,7 @@ export function LanderRewards({
</h2>
<ul className="mt-2 flex flex-col gap-2 text-sm font-medium tracking-[-0.02em] text-neutral-600">
{sortedFilteredRewards.map((reward) => (
- <Item key={reward.id} icon={REWARD_EVENTS[reward.event].icon}>
+ <Item key={reward.id} icon={REWARD_EVENT_ICON[reward.event]}>
{reward.description || (
<>
{constructRewardAmount(reward)}{" "}
diff --git a/apps/web/ui/partners/partner-info-cards.tsx b/apps/web/ui/partners/partner-info-cards.tsx
index 6c63fe5a38..948b09a898 100644
--- a/apps/web/ui/partners/partner-info-cards.tsx
+++ b/apps/web/ui/partners/partner-info-cards.tsx
@@ -1,3 +1,4 @@
+import { usePartnerReferral } from "@/lib/partner-referrals/hooks/use-partner-referral";
import useGroup from "@/lib/swr/use-group";
import useWorkspace from "@/lib/swr/use-workspace";
import {
@@ -20,7 +21,12 @@ import {
TimestampTooltip,
Trophy,
} from "@dub/ui";
-import { TriangleWarning, Users, VerifiedBadge } from "@dub/ui/icons";
+import {
+ TriangleWarning,
+ UserArrowRight,
+ Users,
+ VerifiedBadge,
+} from "@dub/ui/icons";
import {
COUNTRIES,
fetcher,
@@ -73,7 +79,7 @@ type PartnerInfoCardsProps = {
type BasicField = {
id: string;
icon: React.ReactElement;
- text: string | null | undefined;
+ text: ReactNode | null | undefined;
/** When set, the row is wrapped in TimestampTooltip (local / UTC / unix). */
timestamp?: Date | string | number;
/** Optional outer wrapper (e.g. ConversionScoreTooltip) around the row content. */
@@ -120,6 +126,10 @@ export function PartnerInfoCards({
fetcher,
);
+ const { referral, loading: loadingReferral } = usePartnerReferral({
+ partnerId: partner?.id,
+ });
+
let basicFields: BasicField[] = [
{
id: "country",
@@ -186,6 +196,31 @@ export function PartnerInfoCards({
},
]
: []),
+
+ // Referred by
+ ...(referral && referral.referredBy
+ ? [
+ {
+ id: "referredBy",
+ icon: <UserArrowRight className="size-3.5 shrink-0" />,
+ text: (
+ <span className="flex min-w-0 items-center gap-1">
+ Referred by
+ <Link
+ href={`/${workspaceSlug}/program/partners/${referral.referredBy.id}`}
+ className="inline-flex min-w-0 max-w-full cursor-alias items-center gap-1 rounded decoration-dotted underline-offset-2 hover:underline"
+ >
+ <PartnerAvatar
+ partner={referral.referredBy}
+ className="size-3.5"
+ />
+ <span className="truncate">{referral.referredBy.name}</span>
+ </Link>
+ </span>
+ ),
+ },
+ ]
+ : []),
]);
}
diff --git a/apps/web/ui/partners/partner-platforms-form.tsx b/apps/web/ui/partners/partner-platforms-form.tsx
index ef7c42f288..cdc1a3353c 100644
--- a/apps/web/ui/partners/partner-platforms-form.tsx
+++ b/apps/web/ui/partners/partner-platforms-form.tsx
@@ -128,11 +128,17 @@ export const PartnerPlatformsForm = forwardRef<
const { executeAsync } = useAction(updatePartnerPlatformsAction, {
onSuccess: async () => {
+ toast.success(
+ "Successfully updated your websites and social accounts.",
+ );
await mutate("/api/partner-profile");
},
onError: ({ error }) => {
toast.error(
- parseActionError(error, "Failed to update partner platforms"),
+ parseActionError(
+ error,
+ "Failed to update your websites and social accounts.",
+ ),
);
reset(form.getValues(), { keepErrors: true });
diff --git a/apps/web/ui/partners/program-marketplace/program-rewards-display.tsx b/apps/web/ui/partners/program-marketplace/program-rewards-display.tsx
index bc79380d20..4232b60462 100644
--- a/apps/web/ui/partners/program-marketplace/program-rewards-display.tsx
+++ b/apps/web/ui/partners/program-marketplace/program-rewards-display.tsx
@@ -1,10 +1,10 @@
import { DiscountProps, RewardProps } from "@/lib/types";
-import { REWARD_EVENTS } from "@/ui/partners/constants";
import { formatDiscountDescription } from "@/ui/partners/format-discount-description";
import { formatRewardDescription } from "@/ui/partners/format-reward-description";
import { Gift, Icon } from "@dub/ui";
import { cn } from "@dub/utils";
import * as HoverCard from "@radix-ui/react-hover-card";
+import { REWARD_EVENT_ICON } from "../rewards/reward-event-icon";
import { ProgramRewardIcon } from "./program-reward-icon";
type RewardItem = {
@@ -43,8 +43,10 @@ export function ProgramRewardsDisplay({
rewards.forEach((reward) => {
items.push({
id: reward.id,
- icon: REWARD_EVENTS[reward.event].icon,
- description: formatRewardDescription(reward),
+ icon: REWARD_EVENT_ICON[reward.event],
+ description: formatRewardDescription(reward, {
+ includeEarnPrefix: false,
+ }),
onClick: onRewardClick ? () => onRewardClick(reward) : undefined,
});
});
diff --git a/apps/web/ui/partners/program-marketplace/programs-promo-banner.tsx b/apps/web/ui/partners/program-marketplace/programs-promo-banner.tsx
index dad7425c6f..577d8bac9a 100644
--- a/apps/web/ui/partners/program-marketplace/programs-promo-banner.tsx
+++ b/apps/web/ui/partners/program-marketplace/programs-promo-banner.tsx
@@ -1,38 +1,23 @@
"use client";
-import usePartnerPayoutsCount from "@/lib/swr/use-partner-payouts-count";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { IdentityVerificationBanner } from "@/ui/partners/identity-verification/identity-verification-banner";
-import { StablecoinPayoutBanner } from "@/ui/partners/payouts/stablecoin-payout-banner";
import { ProgramMarketplaceBanner } from "@/ui/partners/program-marketplace/program-marketplace-banner";
-/**
- * Single promo banner slot for the programs page: identity verification when the
- * partner is not verified yet; then stablecoin payouts when available and not
- * connected; otherwise the program marketplace banner.
- */
+// Single promo banner slot for the programs page
export function ProgramsPromoBanner() {
- const { partner, availablePayoutMethods } = usePartnerProfile();
- const { payoutsCount } = usePartnerPayoutsCount();
+ const { partner } = usePartnerProfile();
- if (!partner || !payoutsCount) {
+ if (!partner) {
return null;
}
if (
!partner.identityVerifiedAt &&
- !["IN", "GE"].includes(partner.country ?? "") &&
- (payoutsCount[0]?.amount ?? 0) > 10000
+ ["approved", "trusted"].includes(partner.networkStatus)
) {
return <IdentityVerificationBanner />;
}
- if (
- availablePayoutMethods.includes("stablecoin") &&
- !partner.stripeRecipientId
- ) {
- return <StablecoinPayoutBanner />;
- }
-
return <ProgramMarketplaceBanner />;
}
diff --git a/apps/web/ui/partners/program-marketplace/programs-promo-card.tsx b/apps/web/ui/partners/program-marketplace/programs-promo-card.tsx
index 86949fa39c..81ddf9f8b5 100644
--- a/apps/web/ui/partners/program-marketplace/programs-promo-card.tsx
+++ b/apps/web/ui/partners/program-marketplace/programs-promo-card.tsx
@@ -1,38 +1,23 @@
"use client";
-import usePartnerPayoutsCount from "@/lib/swr/use-partner-payouts-count";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { IdentityVerificationCard } from "@/ui/partners/identity-verification/identity-verification-card";
-import { StablecoinPayoutCard } from "@/ui/partners/payouts/stablecoin-payout-card";
import { ProgramMarketplaceCard } from "@/ui/partners/program-marketplace/program-marketplace-card";
-/**
- * Single promo card slot for the sidebar: identity verification when the partner
- * is not verified yet; then stablecoin payouts when available and not connected;
- * otherwise the program marketplace card.
- */
+// Single promo card slot for the sidebar
export function ProgramsPromoCard() {
- const { partner, availablePayoutMethods } = usePartnerProfile();
- const { payoutsCount } = usePartnerPayoutsCount();
+ const { partner } = usePartnerProfile();
- if (!partner || !payoutsCount) {
+ if (!partner) {
return null;
}
if (
!partner.identityVerifiedAt &&
- !["IN", "GE"].includes(partner.country ?? "") &&
- (payoutsCount[0]?.amount ?? 0) > 10000
+ ["approved", "trusted"].includes(partner.networkStatus)
) {
return <IdentityVerificationCard />;
}
- if (
- availablePayoutMethods.includes("stablecoin") &&
- !partner.stripeRecipientId
- ) {
- return <StablecoinPayoutCard />;
- }
-
return <ProgramMarketplaceCard />;
}
diff --git a/apps/web/ui/partners/program-reward-description.tsx b/apps/web/ui/partners/program-reward-description.tsx
index 4b2956b4e5..8608ebdfe2 100644
--- a/apps/web/ui/partners/program-reward-description.tsx
+++ b/apps/web/ui/partners/program-reward-description.tsx
@@ -1,7 +1,13 @@
import { constructDiscountAmount } from "@/lib/api/sales/construct-discount-amount";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import {
+ PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS,
+ PARTNER_REFERRAL_PERCENTAGE_TRIGGERS,
+ PartnerReferralPercentageTrigger,
+} from "@/lib/partner-referrals/constants";
import { DiscountProps, RewardProps } from "@/lib/types";
-import { cn } from "@dub/utils";
+import { referralRewardConfigSchema } from "@/lib/zod/schemas/rewards";
+import { cn, currencyFormatter } from "@dub/utils";
import { ProgramRewardModifiersTooltip } from "./program-reward-modifiers-tooltip";
export function ProgramRewardDescription({
@@ -21,6 +27,7 @@ export function ProgramRewardDescription({
| "type"
| "amountInCents"
| "amountInPercentage"
+ | "config"
> | null;
discount?: DiscountProps | null;
amountClassName?: string;
@@ -31,40 +38,47 @@ export function ProgramRewardDescription({
<>
{reward ? (
<>
- {reward.description || (
- <>
- Earn{" "}
- <strong
- className={cn("font-semibold lowercase", amountClassName)}
- >
- {constructRewardAmount(reward)}{" "}
- </strong>
- {reward.event === "sale" && reward.maxDuration === 0 ? (
- <>for the first sale</>
- ) : (
- <>per {reward.event}</>
- )}
- {reward.maxDuration === null ? (
- <>
- {" "}
- for the{" "}
- <strong className={cn("font-semibold", periodClassName)}>
- customer's lifetime
- </strong>
- </>
- ) : reward.maxDuration && reward.maxDuration > 1 ? (
- <>
- {" "}
- for{" "}
- <strong className={cn("font-semibold", periodClassName)}>
- {reward.maxDuration % 12 === 0
- ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
- : `${reward.maxDuration} months`}
- </strong>
- </>
- ) : null}
- </>
- )}
+ {reward.description ||
+ (reward.event === "referral" ? (
+ <ReferralRewardDescription
+ reward={reward}
+ amountClassName={amountClassName}
+ periodClassName={periodClassName}
+ />
+ ) : (
+ <>
+ Earn{" "}
+ <strong
+ className={cn("font-semibold lowercase", amountClassName)}
+ >
+ {constructRewardAmount(reward)}{" "}
+ </strong>
+ {reward.event === "sale" && reward.maxDuration === 0 ? (
+ <>for the first sale</>
+ ) : (
+ <>per {reward.event}</>
+ )}
+ {reward.maxDuration === null ? (
+ <>
+ {" "}
+ for the{" "}
+ <strong className={cn("font-semibold", periodClassName)}>
+ customer's lifetime
+ </strong>
+ </>
+ ) : reward.maxDuration && reward.maxDuration > 1 ? (
+ <>
+ {" "}
+ for{" "}
+ <strong className={cn("font-semibold", periodClassName)}>
+ {reward.maxDuration % 12 === 0
+ ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
+ : `${reward.maxDuration} months`}
+ </strong>
+ </>
+ ) : null}
+ </>
+ ))}
{/* Modifiers */}
{showModifiersTooltip &&
@@ -108,3 +122,127 @@ export function ProgramRewardDescription({
</>
);
}
+
+function ReferralRewardDescription({
+ reward,
+ amountClassName,
+ periodClassName,
+}: {
+ reward: Pick<
+ RewardProps,
+ | "type"
+ | "config"
+ | "maxDuration"
+ | "amountInCents"
+ | "amountInPercentage"
+ | "modifiers"
+ >;
+ amountClassName?: string;
+ periodClassName?: string;
+}) {
+ const parsed = referralRewardConfigSchema.safeParse(reward.config);
+ const config = parsed.success ? parsed.data : undefined;
+
+ const amountFragment = (
+ <>
+ Earn{" "}
+ <strong className={cn("font-semibold lowercase", amountClassName)}>
+ {constructRewardAmount(reward)}{" "}
+ </strong>
+ </>
+ );
+
+ const durationSuffix = () => {
+ if (reward.maxDuration === null) {
+ return (
+ <>
+ {" "}
+ for the{" "}
+ <strong className={cn("font-semibold", periodClassName)}>
+ customer's lifetime
+ </strong>
+ </>
+ );
+ }
+
+ if (reward.maxDuration === 0) {
+ return <> one time</>;
+ }
+
+ if (reward.maxDuration && reward.maxDuration > 1) {
+ return (
+ <>
+ {" "}
+ for{" "}
+ <strong className={cn("font-semibold", periodClassName)}>
+ {reward.maxDuration % 12 === 0
+ ? `${reward.maxDuration / 12} year${reward.maxDuration / 12 > 1 ? "s" : ""}`
+ : `${reward.maxDuration} months`}
+ </strong>
+ </>
+ );
+ }
+
+ return null;
+ };
+
+ const fallbackReferralDescription = (
+ <>
+ {amountFragment}
+ <>per referral</>
+ {durationSuffix()}
+ </>
+ );
+
+ if (!config) {
+ return fallbackReferralDescription;
+ }
+
+ if (
+ reward.type === "percentage" &&
+ (PARTNER_REFERRAL_PERCENTAGE_TRIGGERS as readonly string[]).includes(
+ config.trigger,
+ )
+ ) {
+ const basis =
+ PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS[
+ config.trigger as PartnerReferralPercentageTrigger
+ ];
+
+ return (
+ <>
+ {amountFragment}
+ <>per {basis}</>
+ {durationSuffix()}
+ </>
+ );
+ }
+
+ if (
+ reward.type === "flat" &&
+ config.trigger === "commissionThreshold" &&
+ config.commissionsThresholdInCents != null
+ ) {
+ const threshold = currencyFormatter(config.commissionsThresholdInCents, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ return (
+ <>
+ {amountFragment}
+ <>when the referred partner earns at least {threshold} in commissions</>
+ </>
+ );
+ }
+
+ if (reward.type === "flat" && config.trigger === "partnerApproved") {
+ return (
+ <>
+ {amountFragment}
+ <>when the referred partner is approved</>
+ </>
+ );
+ }
+
+ return fallbackReferralDescription;
+}
diff --git a/apps/web/ui/partners/program-reward-list.tsx b/apps/web/ui/partners/program-reward-list.tsx
index 982e6012fc..82525b416a 100644
--- a/apps/web/ui/partners/program-reward-list.tsx
+++ b/apps/web/ui/partners/program-reward-list.tsx
@@ -8,9 +8,9 @@ import { cn } from "@dub/utils";
import Link from "next/link";
import { useParams } from "next/navigation";
import { PropsWithChildren } from "react";
-import { REWARD_EVENTS } from "./constants";
import { formatDiscountDescription } from "./format-discount-description";
import { ProgramRewardModifiersTooltip } from "./program-reward-modifiers-tooltip";
+import { REWARD_EVENT_ICON } from "./rewards/reward-event-icon";
export function ProgramRewardList({
rewards,
@@ -62,7 +62,7 @@ export function ProgramRewardList({
{sortedFilteredRewards.map((reward) => (
<Item
key={reward.id}
- icon={REWARD_EVENTS[reward.event].icon}
+ icon={REWARD_EVENT_ICON[reward.event]}
iconClassName={iconClassName}
>
{reward.description || (
diff --git a/apps/web/ui/partners/program-rewards-panel.tsx b/apps/web/ui/partners/program-rewards-panel.tsx
index c1c07c8b6b..a8c27bf660 100644
--- a/apps/web/ui/partners/program-rewards-panel.tsx
+++ b/apps/web/ui/partners/program-rewards-panel.tsx
@@ -6,9 +6,9 @@ import { DiscountProps, RewardProps } from "@/lib/types";
import { Gift, Tooltip } from "@dub/ui";
import { HelpCircle } from "lucide-react";
import { memo } from "react";
-import { REWARD_EVENTS } from "./constants";
import { formatDiscountDescription } from "./format-discount-description";
import { ProgramRewardModifiersTooltipContent } from "./program-reward-modifiers-tooltip";
+import { REWARD_EVENT_ICON } from "./rewards/reward-event-icon";
interface ProgramRewardsPanelProps {
rewards: RewardProps[];
@@ -36,7 +36,7 @@ export const ProgramRewardsPanel = memo(
const rewardItems = [
...sortedFilteredRewards.map((reward) => ({
- icon: REWARD_EVENTS[reward.event].icon,
+ icon: REWARD_EVENT_ICON[reward.event],
label: reward.description || (
<>
{constructRewardAmount(reward)}{" "}
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index b2f4e763be..04f4224bab 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -6,6 +6,7 @@ import { deleteRewardAction } from "@/lib/actions/partners/delete-reward";
import { updateRewardAction } from "@/lib/actions/partners/update-reward";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
+import { ReferralRewardConfig } from "@/lib/partner-referrals/types";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useGroup from "@/lib/swr/use-group";
import useProgram from "@/lib/swr/use-program";
@@ -62,6 +63,7 @@ import {
InlineBadgePopoverRichTextArea,
} from "../../shared/inline-badge-popover";
import { RewardDiscountPartnersCard } from "../groups/reward-discount-partners-card";
+import { PartnerReferralRewardBuilder } from "./partner-referral-reward-builder";
import { RewardIconSquare } from "./reward-icon-square";
import { RewardPreviewCard } from "./reward-preview-card";
import { REWARD_TYPES, RewardsLogic } from "./rewards-logic";
@@ -88,8 +90,48 @@ type FormData = z.infer<typeof formSchema>;
export const useAddEditRewardForm = () => useFormContext<FormData>();
+function referralConfigFromApi(
+ config: ReferralRewardConfig | null | undefined,
+): ReferralRewardConfig | null {
+ if (!config) return null;
+
+ if (
+ config.trigger === "commissionThreshold" &&
+ typeof config.commissionsThresholdInCents === "number"
+ ) {
+ return {
+ ...config,
+ commissionsThresholdInCents: config.commissionsThresholdInCents / 100,
+ };
+ }
+
+ return config;
+}
+
+function referralConfigToApi(
+ config: ReferralRewardConfig | null | undefined,
+): ReferralRewardConfig | null {
+ if (!config) return null;
+
+ if (
+ config.trigger === "commissionThreshold" &&
+ typeof config.commissionsThresholdInCents === "number"
+ ) {
+ return {
+ ...config,
+ commissionsThresholdInCents: Math.round(
+ config.commissionsThresholdInCents * 100,
+ ),
+ };
+ }
+
+ return config;
+}
+
export const getRewardPayload = ({ data }: { data: FormData }) => {
let modifiers: RewardConditionsArray | null = null;
+ const config =
+ data.event === "referral" ? referralConfigToApi(data.config) : null;
if (data.modifiers?.length) {
modifiers = rewardConditionsArraySchema.parse(
@@ -144,6 +186,7 @@ export const getRewardPayload = ({ data }: { data: FormData }) => {
maxDuration:
Infinity === Number(data.maxDuration) ? null : data.maxDuration,
modifiers,
+ config,
};
};
@@ -170,12 +213,14 @@ function RewardSheetContent({
defaultValues: {
event,
type:
- defaultValuesSource?.type || (event === "sale" ? "percentage" : "flat"),
+ defaultValuesSource?.type ??
+ (event === "click" || event === "lead" ? "flat" : "percentage"),
maxDuration: defaultValuesSource
? defaultValuesSource.maxDuration === null
? Infinity
: defaultValuesSource.maxDuration
: Infinity,
+ config: referralConfigFromApi(defaultValuesSource?.config),
amountInCents:
defaultValuesSource?.amountInCents != null
? defaultValuesSource.amountInCents / 100
@@ -287,6 +332,8 @@ function RewardSheetContent({
);
const [showAdvancedUpsell, setShowAdvancedUpsell] = useState(false);
+ const showReferralUpsell =
+ event === "referral" && !getPlanCapabilities(plan).canCreateReferralReward;
useEffect(() => {
if (
@@ -300,7 +347,13 @@ function RewardSheetContent({
}, [modifiers, plan]);
const onSubmit = async (data: FormData) => {
- if (!workspaceId || !defaultProgramId || showAdvancedUpsell || !group) {
+ if (
+ !workspaceId ||
+ !defaultProgramId ||
+ showAdvancedUpsell ||
+ showReferralUpsell ||
+ !group
+ ) {
return;
}
@@ -379,86 +432,90 @@ function RewardSheetContent({
<div className="flex min-w-0 items-center justify-between">
<div className="flex min-w-0 items-center gap-2.5">
<RewardIconSquare icon={MoneyBills2} />
- <span className="leading-relaxed">
- Pay{" "}
- {selectedEvent === "sale" && (
- <>
- a{" "}
- <InlineBadgePopover text={capitalize(type)}>
- <InlineBadgePopoverMenu
- selectedValue={type}
- onSelect={(value) =>
- setValue("type", value as RewardStructure, {
- shouldDirty: true,
- })
- }
- items={REWARD_TYPES}
- />
- </InlineBadgePopover>{" "}
- {type === "percentage" && "of "}
- </>
- )}
- <InlineBadgePopover
- text={
- amount != null && !isNaN(amount)
- ? constructRewardAmount({
- type,
- maxDuration,
- amountInCents:
- type === "flat" ? amount * 100 : undefined,
- amountInPercentage:
- type === "percentage" ? amount : undefined,
- })
- : "amount"
- }
- invalid={amount == null || isNaN(amount)}
- >
- <AmountInput />
- </InlineBadgePopover>{" "}
- per {selectedEvent}
- {selectedEvent === "sale" && (
- <>
- {" "}
- <InlineBadgePopover
- text={
- maxDuration === 0
- ? "one time"
- : maxDuration === Infinity
- ? "for the customer's lifetime"
- : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`
- }
- >
- <InlineBadgePopoverMenu
- selectedValue={maxDuration?.toString()}
- onSelect={(value) =>
- setValue("maxDuration", Number(value), {
- shouldDirty: true,
+ {selectedEvent === "referral" ? (
+ <PartnerReferralRewardBuilder />
+ ) : (
+ <span className="leading-relaxed">
+ Pay{" "}
+ {selectedEvent === "sale" && (
+ <>
+ a{" "}
+ <InlineBadgePopover text={capitalize(type)}>
+ <InlineBadgePopoverMenu
+ selectedValue={type}
+ onSelect={(value) =>
+ setValue("type", value as RewardStructure, {
+ shouldDirty: true,
+ })
+ }
+ items={REWARD_TYPES}
+ />
+ </InlineBadgePopover>{" "}
+ {type === "percentage" && "of "}
+ </>
+ )}
+ <InlineBadgePopover
+ text={
+ amount != null && !isNaN(amount)
+ ? constructRewardAmount({
+ type,
+ maxDuration,
+ amountInCents:
+ type === "flat" ? amount * 100 : undefined,
+ amountInPercentage:
+ type === "percentage" ? amount : undefined,
})
+ : "amount"
+ }
+ invalid={amount == null || isNaN(amount)}
+ >
+ <AmountInput />
+ </InlineBadgePopover>{" "}
+ per {selectedEvent}
+ {selectedEvent === "sale" && (
+ <>
+ {" "}
+ <InlineBadgePopover
+ text={
+ maxDuration === 0
+ ? "one time"
+ : maxDuration === Infinity
+ ? "for the customer's lifetime"
+ : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`
}
- items={[
- {
- text: "one time",
- value: "0",
- },
- ...RECURRING_MAX_DURATIONS.filter(
- (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)
- ).map((v) => ({
- text: `for ${v} ${pluralize("month", Number(v))}`,
- value: v.toString(),
- })),
- {
- text: "for the customer's lifetime",
- value: "Infinity",
- },
- ]}
- />
- </InlineBadgePopover>
- </>
- )}
- {modifiers?.length ? (
- <> for all other {selectedEvent}s</>
- ) : null}
- </span>
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={maxDuration?.toString()}
+ onSelect={(value) =>
+ setValue("maxDuration", Number(value), {
+ shouldDirty: true,
+ })
+ }
+ items={[
+ {
+ text: "one time",
+ value: "0",
+ },
+ ...RECURRING_MAX_DURATIONS.filter(
+ (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)
+ ).map((v) => ({
+ text: `for ${v} ${pluralize("month", Number(v))}`,
+ value: v.toString(),
+ })),
+ {
+ text: "for the customer's lifetime",
+ value: "Infinity",
+ },
+ ]}
+ />
+ </InlineBadgePopover>
+ </>
+ )}
+ {modifiers?.length ? (
+ <> for all other {selectedEvent}s</>
+ ) : null}
+ </span>
+ )}
</div>
<Tooltip
content={"Add a custom reward description"}
@@ -551,7 +608,11 @@ function RewardSheetContent({
</motion.div>
</div>
}
- content={<RewardsLogic isDefaultReward={false} />}
+ content={
+ selectedEvent === "referral" ? null : (
+ <RewardsLogic isDefaultReward={false} />
+ )
+ }
/>
<VerticalLine />
@@ -600,11 +661,18 @@ function RewardSheetContent({
amount == null || isDeleting || isCreating || isUpdating
}
disabledTooltip={
- showAdvancedUpsell ? (
+ showReferralUpsell ? (
+ <TooltipContent
+ title="Referral rewards are only available on the Advanced plan and above."
+ cta="Upgrade to Advanced"
+ href={`/${workspaceSlug}/upgrade?plan=advanced&showPartnersUpgradeModal=true`}
+ target="_blank"
+ />
+ ) : showAdvancedUpsell ? (
<TooltipContent
title="[Advanced reward structures](https://dub.co/help/article/partner-rewards#adding-reward-conditions) are only available on the Advanced plan and above."
cta="Upgrade to Advanced"
- href={`/${workspaceSlug}/upgrade?showPartnersUpgradeModal=true`}
+ href={`/${workspaceSlug}/upgrade?plan=advanced&showPartnersUpgradeModal=true`}
target="_blank"
/>
) : undefined
@@ -635,13 +703,19 @@ const REWARD_HELPER_CONTENT: Record<
icon: UserPlus,
title: "Lead rewards",
description:
- "Reward for sign ups or demos. Best for B2B, demos, waitlists, or longer sales cycles.",
+ "Reward for sign ups or demos. Best for B2B, demos, waitlists, or products with longer sales cycles.",
},
click: {
icon: CursorRays,
title: "Click rewards",
description:
- "Reward for traffic and reach. Best for publishers and trusted partners only.",
+ "Reward for traffic and reach. Best for publishers with high DR sites and trusted partners only.",
+ },
+ referral: {
+ icon: UserPlus,
+ title: "Referral rewards",
+ description:
+ "Reward partners for referring other partners. Best for driving partner growth to your program.",
},
};
diff --git a/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx b/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx
new file mode 100644
index 0000000000..5ae621fcdb
--- /dev/null
+++ b/apps/web/ui/partners/rewards/partner-referral-reward-builder.tsx
@@ -0,0 +1,340 @@
+"use client";
+
+import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
+import {
+ PARTNER_REFERRAL_FLAT_TRIGGERS,
+ PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS,
+ PARTNER_REFERRAL_PERCENTAGE_TRIGGERS,
+ PARTNER_REFERRAL_TRIGGER,
+ PARTNER_REFERRAL_TRIGGER_LABELS,
+} from "@/lib/partner-referrals/constants";
+import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
+import { RewardStructure } from "@dub/prisma/client";
+import { capitalize, cn, currencyFormatter, pluralize } from "@dub/utils";
+import { useContext, useEffect, useMemo } from "react";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverContext,
+ InlineBadgePopoverMenu,
+} from "../../shared/inline-badge-popover";
+import { useAddEditRewardForm } from "./add-edit-reward-sheet";
+
+type Trigger = (typeof PARTNER_REFERRAL_TRIGGER)[number];
+
+const PERCENTAGE_TRIGGER_ITEMS = PARTNER_REFERRAL_PERCENTAGE_TRIGGERS.map(
+ (trigger) => ({
+ text: PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS[trigger],
+ value: trigger,
+ }),
+);
+
+const FLAT_TRIGGER_ITEMS = PARTNER_REFERRAL_FLAT_TRIGGERS.map((trigger) => ({
+ text: PARTNER_REFERRAL_TRIGGER_LABELS[trigger],
+ value: trigger,
+}));
+
+const MAX_DURATION_MENU_ITEMS = [
+ {
+ text: "one time",
+ value: "0",
+ },
+ ...RECURRING_MAX_DURATIONS.filter((v) => v !== 0 && v !== 1).map((v) => ({
+ text: `for ${v} ${pluralize("month", Number(v))}`,
+ value: v.toString(),
+ })),
+ {
+ text: "for the customer's lifetime",
+ value: "Infinity",
+ },
+];
+
+export function PartnerReferralRewardBuilder() {
+ const { watch, setValue } = useAddEditRewardForm();
+
+ const [type, amountInCents, amountInPercentage, config, maxDuration] = watch([
+ "type",
+ "amountInCents",
+ "amountInPercentage",
+ "config",
+ "maxDuration",
+ ]);
+
+ const amount = type === "flat" ? amountInCents : amountInPercentage;
+
+ const thresholdDollars =
+ config?.trigger === "commissionThreshold"
+ ? config.commissionsThresholdInCents
+ : undefined;
+
+ // Keep config in sync with the main reward type. If the trigger doesn't
+ // match the current reward type, reset to that type's default trigger.
+ useEffect(() => {
+ const validTriggers =
+ type === "percentage"
+ ? PARTNER_REFERRAL_PERCENTAGE_TRIGGERS
+ : PARTNER_REFERRAL_FLAT_TRIGGERS;
+
+ if (
+ config?.trigger &&
+ (validTriggers as readonly Trigger[]).includes(config?.trigger)
+ ) {
+ return;
+ }
+
+ const nextTrigger: Trigger =
+ type === "percentage" ? "saleRecorded" : "partnerApproved";
+
+ setValue("config", { trigger: nextTrigger }, { shouldDirty: true });
+ }, [setValue, config?.trigger, type]);
+
+ // Flat triggers (partnerApproved, commissionThreshold) don't support
+ // maxDuration, so clear it whenever a flat trigger is active. When switching
+ // back to a percentage trigger, restore maxDuration if it was cleared.
+ useEffect(() => {
+ if (
+ config?.trigger &&
+ (PARTNER_REFERRAL_FLAT_TRIGGERS as readonly Trigger[]).includes(
+ config.trigger,
+ ) &&
+ maxDuration !== null
+ ) {
+ setValue("maxDuration", null, { shouldDirty: true });
+ return;
+ }
+
+ if (
+ config?.trigger &&
+ (PARTNER_REFERRAL_PERCENTAGE_TRIGGERS as readonly Trigger[]).includes(
+ config.trigger,
+ ) &&
+ maxDuration === null
+ ) {
+ setValue("maxDuration", Infinity, { shouldDirty: true });
+ }
+ }, [setValue, config?.trigger, maxDuration]);
+
+ const amountText = useMemo(() => {
+ if (amount == null || Number.isNaN(Number(amount))) return "amount";
+
+ return constructRewardAmount({
+ type,
+ maxDuration: null,
+ amountInCents: type === "flat" ? Number(amount) * 100 : undefined,
+ amountInPercentage: type === "percentage" ? Number(amount) : undefined,
+ });
+ }, [amount, type]);
+
+ const triggerText = useMemo(() => {
+ if (!config?.trigger) return "event";
+
+ if (type === "percentage") {
+ if (
+ config.trigger === "commissionEarned" ||
+ config.trigger === "saleRecorded"
+ ) {
+ return PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS[config.trigger];
+ }
+
+ return PARTNER_REFERRAL_PERCENTAGE_BASIS_LABELS.saleRecorded;
+ }
+
+ return PARTNER_REFERRAL_TRIGGER_LABELS[config.trigger];
+ }, [type, config?.trigger]);
+
+ const thresholdText =
+ thresholdDollars != null && !Number.isNaN(Number(thresholdDollars))
+ ? currencyFormatter(Math.round(Number(thresholdDollars) * 100), {
+ trailingZeroDisplay: "stripIfInteger",
+ })
+ : "$1";
+
+ const maxDurationText = useMemo(() => {
+ if (maxDuration === 0) return "one time";
+ if (maxDuration === Infinity) return "for the customer's lifetime";
+ return `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`;
+ }, [maxDuration]);
+
+ return (
+ <span className="leading-relaxed">
+ Pay a{" "}
+ <InlineBadgePopover text={capitalize(type)}>
+ <InlineBadgePopoverMenu
+ selectedValue={type}
+ onSelect={(value) =>
+ setValue("type", value as RewardStructure, { shouldDirty: true })
+ }
+ items={[
+ { text: "Percentage", value: "percentage" },
+ { text: "Flat fee", value: "flat" },
+ ]}
+ />
+ </InlineBadgePopover>{" "}
+ of{" "}
+ <InlineBadgePopover
+ text={amountText}
+ invalid={amount == null || Number.isNaN(Number(amount))}
+ >
+ <RewardAmountInput />
+ </InlineBadgePopover>{" "}
+ {type === "percentage" ? (
+ <>
+ based on the{" "}
+ <InlineBadgePopover text={triggerText} invalid={!config?.trigger}>
+ <InlineBadgePopoverMenu
+ selectedValue={config?.trigger}
+ onSelect={(value) => {
+ setValue(
+ "config",
+ { trigger: value as Trigger },
+ { shouldDirty: true },
+ );
+ }}
+ items={PERCENTAGE_TRIGGER_ITEMS}
+ />
+ </InlineBadgePopover>{" "}
+ <InlineBadgePopover text={maxDurationText}>
+ <InlineBadgePopoverMenu
+ selectedValue={maxDuration?.toString()}
+ onSelect={(value) =>
+ setValue("maxDuration", Number(value), {
+ shouldDirty: true,
+ })
+ }
+ items={MAX_DURATION_MENU_ITEMS}
+ />
+ </InlineBadgePopover>
+ </>
+ ) : (
+ <>
+ when referred partner{" "}
+ <InlineBadgePopover text={triggerText} invalid={!config?.trigger}>
+ <InlineBadgePopoverMenu
+ selectedValue={config?.trigger}
+ onSelect={(value) => {
+ if (value === "commissionThreshold") {
+ setValue(
+ "config",
+ { trigger: value, commissionsThresholdInCents: 1 },
+ { shouldDirty: true },
+ );
+ return;
+ }
+
+ setValue(
+ "config",
+ { trigger: value as Trigger },
+ { shouldDirty: true },
+ );
+ }}
+ items={FLAT_TRIGGER_ITEMS}
+ />
+ </InlineBadgePopover>
+ {config?.trigger === "commissionThreshold" && (
+ <>
+ {" "}
+ <InlineBadgePopover text={thresholdText}>
+ <ThresholdInput />
+ </InlineBadgePopover>
+ </>
+ )}
+ </>
+ )}
+ </span>
+ );
+}
+
+function RewardAmountInput() {
+ const { watch, register } = useAddEditRewardForm();
+ const { setIsOpen } = useContext(InlineBadgePopoverContext);
+
+ const type = watch("type");
+ const fieldName = type === "flat" ? "amountInCents" : "amountInPercentage";
+
+ return (
+ <div className="relative rounded-md shadow-sm">
+ {type === "flat" && (
+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">
+ $
+ </span>
+ )}
+ <input
+ className={cn(
+ "block w-full rounded-md border-neutral-300 px-1.5 py-1 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm",
+ type === "flat" ? "pl-4 pr-12" : "pr-7",
+ )}
+ {...register(fieldName, {
+ required: true,
+ setValueAs: (value: string) => (value === "" ? undefined : +value),
+ min: 0,
+ max: type === "percentage" ? 100 : undefined,
+ onChange: handleMoneyInputChange,
+ })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setIsOpen(false);
+ return;
+ }
+
+ handleMoneyKeyDown(e);
+ }}
+ />
+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">
+ {type === "flat" ? "USD" : "%"}
+ </span>
+ </div>
+ );
+}
+
+function ThresholdInput() {
+ const { register, setValue, watch } = useAddEditRewardForm();
+ const { setIsOpen } = useContext(InlineBadgePopoverContext);
+
+ const config = watch("config");
+ const thresholdDollars =
+ config?.trigger === "commissionThreshold"
+ ? config.commissionsThresholdInCents
+ : undefined;
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="relative rounded-md shadow-sm">
+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">
+ $
+ </span>
+ <input
+ className="block w-full rounded-md border-neutral-300 px-1.5 py-1 pl-4 pr-12 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm"
+ placeholder="1"
+ defaultValue={thresholdDollars}
+ {...register("config.commissionsThresholdInCents" as any, {
+ required: true,
+ setValueAs: (v: string) => (v === "" ? undefined : +v),
+ min: 1,
+ onChange: handleMoneyInputChange,
+ })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setIsOpen(false);
+ return;
+ }
+ handleMoneyKeyDown(e);
+ }}
+ onBlur={(e) => {
+ const next = Number((e.target as HTMLInputElement).value);
+ if (!Number.isNaN(next) && next >= 1) {
+ setValue("config.commissionsThresholdInCents" as any, next, {
+ shouldDirty: true,
+ });
+ }
+ }}
+ />
+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">
+ USD
+ </span>
+ </div>
+ <p className="text-xs text-neutral-500">Minimum $1</p>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/rewards/reward-event-icon.tsx b/apps/web/ui/partners/rewards/reward-event-icon.tsx
new file mode 100644
index 0000000000..a1d7683bc8
--- /dev/null
+++ b/apps/web/ui/partners/rewards/reward-event-icon.tsx
@@ -0,0 +1,8 @@
+import { CursorRays, InvoiceDollar, Nodes4, UserPlus } from "@dub/ui/icons";
+
+export const REWARD_EVENT_ICON = {
+ click: CursorRays,
+ lead: UserPlus,
+ sale: InvoiceDollar,
+ referral: Nodes4,
+};
diff --git a/apps/web/ui/partners/rewards/reward-preview-card.tsx b/apps/web/ui/partners/rewards/reward-preview-card.tsx
index 63af696d59..6cfa919a6e 100644
--- a/apps/web/ui/partners/rewards/reward-preview-card.tsx
+++ b/apps/web/ui/partners/rewards/reward-preview-card.tsx
@@ -5,12 +5,12 @@ import { cn, nFormatter, pluralize } from "@dub/utils";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useWatch } from "react-hook-form";
-import { REWARD_EVENTS } from "../constants";
import { ProgramRewardDescription } from "../program-reward-description";
import {
getRewardPayload,
useAddEditRewardForm,
} from "./add-edit-reward-sheet";
+import { REWARD_EVENT_ICON } from "./reward-event-icon";
import { getRewardQuality, RewardQualityIndicator } from "./reward-quality";
export function RewardPreviewCard() {
@@ -25,7 +25,7 @@ export function RewardPreviewCard() {
return null;
}
- const Icon = REWARD_EVENTS[reward.event].icon;
+ const Icon = REWARD_EVENT_ICON[reward.event];
const type = data.type ?? reward.type;
const hasConditions = !!data.modifiers?.length;
const quality = getRewardQuality({
diff --git a/packages/email/src/templates/new-commission-alert-partner.tsx b/packages/email/src/templates/new-commission-alert-partner.tsx
index a8ef59f97f..0a1b8d78b1 100644
--- a/packages/email/src/templates/new-commission-alert-partner.tsx
+++ b/packages/email/src/templates/new-commission-alert-partner.tsx
@@ -41,7 +41,7 @@ export default function NewCommissionAlertPartner({
holdingPeriodDays: number;
};
commission: {
- type: "click" | "lead" | "sale" | "custom";
+ type: "click" | "lead" | "sale" | "custom" | "referral";
amount: number;
earnings: number;
};
diff --git a/packages/prisma/schema/application.prisma b/packages/prisma/schema/application.prisma
index 11c60e4cbf..aef67803e9 100644
--- a/packages/prisma/schema/application.prisma
+++ b/packages/prisma/schema/application.prisma
@@ -58,6 +58,7 @@ model ProgramApplicationEvent {
referredByPartner Partner? @relation(fields: [referredByPartnerId], references: [id])
application ProgramApplication? @relation(fields: [programApplicationId], references: [id])
+ programEnrollment ProgramEnrollment? @relation(fields: [programId, partnerId], references: [programId, partnerId])
@@unique([programId, partnerId])
@@index([programId, visitedAt])
diff --git a/packages/prisma/schema/commission.prisma b/packages/prisma/schema/commission.prisma
index 862020ce8f..64e5d321ad 100644
--- a/packages/prisma/schema/commission.prisma
+++ b/packages/prisma/schema/commission.prisma
@@ -12,29 +12,32 @@ enum CommissionType {
click
lead
sale
+ referral
custom
}
model Commission {
- id String @id @default(cuid())
- programId String
- partnerId String
- rewardId String?
- linkId String?
- payoutId String?
- invoiceId String? // only for sales (idempotency key, each sale event is associated with a unique invoice)
- customerId String? // only for leads and sales
- eventId String? @unique // only for leads and sales
- description String?
- type CommissionType
- amount Int // only for sales (amount of the sale event)
- quantity Int // only for clicks/leads (quantity of the event)
- earnings Int @default(0) // amount earned by the partner
- currency String @default("usd")
- status CommissionStatus @default(pending)
- userId String? // user who created the manual commission
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ programId String
+ partnerId String
+ rewardId String?
+ linkId String?
+ payoutId String?
+ invoiceId String? // only for sales (idempotency key, each sale event is associated with a unique invoice)
+ customerId String? // only for leads and sales
+ eventId String? @unique // only for leads and sales
+ description String?
+ type CommissionType
+ amount Int // only for sales (amount of the sale event)
+ quantity Int // only for clicks/leads (quantity of the event)
+ earnings Int @default(0) // amount earned by the partner
+ currency String @default("usd")
+ status CommissionStatus @default(pending)
+ userId String? // user who created the manual commission
+ sourceCommissionId String?
+ sourcePartnerId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
program Program @relation(fields: [programId], references: [id])
partner Partner @relation(fields: [partnerId], references: [id])
diff --git a/packages/prisma/schema/group.prisma b/packages/prisma/schema/group.prisma
index aa0d68b9cd..e9e4c7c255 100644
--- a/packages/prisma/schema/group.prisma
+++ b/packages/prisma/schema/group.prisma
@@ -13,6 +13,7 @@ model PartnerGroup {
clickRewardId String? @unique
leadRewardId String? @unique
saleRewardId String? @unique
+ referralRewardId String? @unique
discountId String? @unique
linkStructure PartnerLinkStructure @default(short)
additionalLinks Json? @db.Json
@@ -35,6 +36,7 @@ model PartnerGroup {
clickReward Reward? @relation("ClickReward", fields: [clickRewardId], references: [id])
leadReward Reward? @relation("LeadReward", fields: [leadRewardId], references: [id])
saleReward Reward? @relation("SaleReward", fields: [saleRewardId], references: [id])
+ referralReward Reward? @relation("ReferralReward", fields: [referralRewardId], references: [id])
discount Discount? @relation(fields: [discountId], references: [id])
partners ProgramEnrollment[]
applications ProgramApplication[]
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index 88ee744ff8..ed60368ab3 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -116,6 +116,7 @@ model Partner {
@@index(payoutMethodHash)
@@index(cryptoWalletAddress)
@@index(identityVerifiedAt)
+ @@index(referredByPartnerId)
@@fulltext([email, name, companyName]) // For full-text search
}
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 5924b948c8..95b9fe3a5d 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -98,17 +98,18 @@ model Program {
}
model ProgramEnrollment {
- id String @id @default(cuid())
- partnerId String
- programId String
- tenantId String?
- groupId String?
- applicationId String? @unique
- clickRewardId String?
- leadRewardId String?
- saleRewardId String?
- discountId String?
- status ProgramEnrollmentStatus @default(pending)
+ id String @id @default(cuid())
+ partnerId String
+ programId String
+ tenantId String?
+ groupId String?
+ applicationId String? @unique
+ clickRewardId String?
+ leadRewardId String?
+ saleRewardId String?
+ referralRewardId String?
+ discountId String?
+ status ProgramEnrollmentStatus @default(pending)
// partner stats
totalClicks Int @default(0) // total clicks
@@ -137,16 +138,17 @@ model ProgramEnrollment {
bannedAt DateTime?
bannedReason PartnerBannedReason?
- partner Partner @relation(fields: [partnerId], references: [id], onUpdate: Cascade, onDelete: Cascade)
- program Program @relation(fields: [programId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ partner Partner @relation(fields: [partnerId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ program Program @relation(fields: [programId], references: [id], onUpdate: Cascade, onDelete: Cascade)
links Link[]
customers Customer[]
- partnerGroup PartnerGroup? @relation(fields: [groupId], references: [id])
- application ProgramApplication? @relation(fields: [applicationId], references: [id])
- clickReward Reward? @relation("ClickRewardEnrollments", fields: [clickRewardId], references: [id])
- leadReward Reward? @relation("LeadRewardEnrollments", fields: [leadRewardId], references: [id])
- saleReward Reward? @relation("SaleRewardEnrollments", fields: [saleRewardId], references: [id])
- discount Discount? @relation(fields: [discountId], references: [id])
+ partnerGroup PartnerGroup? @relation(fields: [groupId], references: [id])
+ application ProgramApplication? @relation(fields: [applicationId], references: [id])
+ clickReward Reward? @relation("ClickRewardEnrollments", fields: [clickRewardId], references: [id])
+ leadReward Reward? @relation("LeadRewardEnrollments", fields: [leadRewardId], references: [id])
+ saleReward Reward? @relation("SaleRewardEnrollments", fields: [saleRewardId], references: [id])
+ referralReward Reward? @relation("ReferralRewardEnrollments", fields: [referralRewardId], references: [id])
+ discount Discount? @relation(fields: [discountId], references: [id])
bountySubmissions BountySubmission[]
discountCodes DiscountCode[]
commissions Commission[]
@@ -155,6 +157,7 @@ model ProgramEnrollment {
fraudAlerts FraudAlert[]
discoveredPartner DiscoveredPartner?
programPartnerTags ProgramPartnerTag[]
+ applicationEvent ProgramApplicationEvent?
submittedLeads SubmittedLead[]
// unique constraints
@@ -179,5 +182,6 @@ model ProgramEnrollment {
@@index(clickRewardId)
@@index(leadRewardId)
@@index(saleRewardId)
+ @@index(referralRewardId)
@@index(discountId)
}
diff --git a/packages/prisma/schema/reward.prisma b/packages/prisma/schema/reward.prisma
index b6c0c4feca..3b41ed1946 100644
--- a/packages/prisma/schema/reward.prisma
+++ b/packages/prisma/schema/reward.prisma
@@ -2,6 +2,7 @@ enum EventType {
click
lead
sale
+ referral
}
enum RewardStructure {
@@ -20,17 +21,20 @@ model Reward {
amountInPercentage Decimal? @db.Decimal(5, 2)
maxDuration Int? // in months (0 -> not recurring, null -> infinite)
modifiers Json? @db.Json
+ config Json? @db.Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- program Program @relation(fields: [programId], references: [id])
- clickEnrollments ProgramEnrollment[] @relation("ClickRewardEnrollments")
- leadEnrollments ProgramEnrollment[] @relation("LeadRewardEnrollments")
- saleEnrollments ProgramEnrollment[] @relation("SaleRewardEnrollments")
- clickPartnerGroup PartnerGroup? @relation("ClickReward")
- leadPartnerGroup PartnerGroup? @relation("LeadReward")
- salePartnerGroup PartnerGroup? @relation("SaleReward")
- commissions Commission[]
+ program Program @relation(fields: [programId], references: [id])
+ clickEnrollments ProgramEnrollment[] @relation("ClickRewardEnrollments")
+ leadEnrollments ProgramEnrollment[] @relation("LeadRewardEnrollments")
+ saleEnrollments ProgramEnrollment[] @relation("SaleRewardEnrollments")
+ referralEnrollments ProgramEnrollment[] @relation("ReferralRewardEnrollments")
+ clickPartnerGroup PartnerGroup? @relation("ClickReward")
+ leadPartnerGroup PartnerGroup? @relation("LeadReward")
+ salePartnerGroup PartnerGroup? @relation("SaleReward")
+ referralPartnerGroup PartnerGroup? @relation("ReferralReward")
+ commissions Commission[]
@@index([programId, event])
@@index(event) // used in aggregate-clicks cron job
diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.ts
index 37225059e2..e171b418ea 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -180,6 +180,7 @@ export * from "./msg";
export * from "./msgs";
export * from "./msgs-dotted";
export * from "./msgs-fill";
+export * from "./nodes-4";
export * from "./note";
export * from "./office-building";
export * from "./page2";
@@ -243,6 +244,7 @@ export * from "./trophy";
export * from "./tv";
export * from "./ui-card";
export * from "./user";
+export * from "./user-arrow-left";
export * from "./user-arrow-right";
export * from "./user-check";
export * from "./user-crown";
diff --git a/packages/ui/src/icons/nucleo/nodes-4.tsx b/packages/ui/src/icons/nucleo/nodes-4.tsx
new file mode 100644
index 0000000000..fbc0565736
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/nodes-4.tsx
@@ -0,0 +1,33 @@
+import { SVGProps } from "react";
+
+export function Nodes4(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 15.6013 15.0636"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ >
+ <path d="M7.80067 9.63889C8.65978 9.63889 9.35622 8.94244 9.35622 8.08333C9.35622 7.22422 8.65978 6.52778 7.80067 6.52778C6.94156 6.52778 6.24511 7.22422 6.24511 8.08333C6.24511 8.94244 6.94156 9.63889 7.80067 9.63889Z" />
+ <path d="M7.80067 3.86111C8.65978 3.86111 9.35622 3.16467 9.35622 2.30556C9.35622 1.44645 8.65978 0.75 7.80067 0.75C6.94156 0.75 6.24511 1.44645 6.24511 2.30556C6.24511 3.16467 6.94156 3.86111 7.80067 3.86111Z" />
+ <path d="M2.30556 7.85311C3.16467 7.85311 3.86111 7.15667 3.86111 6.29756C3.86111 5.43845 3.16467 4.742 2.30556 4.742C1.44645 4.742 0.75 5.43845 0.75 6.29756C0.75 7.15667 1.44645 7.85311 2.30556 7.85311Z" />
+ <path d="M4.40422 14.3136C5.26333 14.3136 5.95978 13.6171 5.95978 12.758C5.95978 11.8989 5.26333 11.2024 4.40422 11.2024C3.54511 11.2024 2.84867 11.8989 2.84867 12.758C2.84867 13.6171 3.54511 14.3136 4.40422 14.3136Z" />
+ <path d="M11.1971 14.3136C12.0562 14.3136 12.7527 13.6171 12.7527 12.758C12.7527 11.8989 12.0562 11.2024 11.1971 11.2024C10.338 11.2024 9.64156 11.8989 9.64156 12.758C9.64156 13.6171 10.338 14.3136 11.1971 14.3136Z" />
+ <path d="M13.2958 7.85311C14.1549 7.85311 14.8513 7.15667 14.8513 6.29756C14.8513 5.43845 14.1549 4.742 13.2958 4.742C12.4367 4.742 11.7402 5.43845 11.7402 6.29756C11.7402 7.15667 12.4367 7.85311 13.2958 7.85311Z" />
+ <path d="M7.80067 6.52778V5.63889" />
+ <path d="M6.32156 7.60244L5.47622 7.32778" />
+ <path d="M6.886 9.342L6.36422 10.0611" />
+ <path d="M8.71533 9.342L9.23711 10.0611" />
+ <path d="M9.27978 7.60244L10.1251 7.32778" />
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/ui/src/icons/nucleo/user-arrow-left.tsx b/packages/ui/src/icons/nucleo/user-arrow-left.tsx
new file mode 100644
index 0000000000..eabb278381
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/user-arrow-left.tsx
@@ -0,0 +1,43 @@
+import { SVGProps } from "react";
+
+export function UserArrowLeft(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ width={16}
+ height={16}
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <path
+ d="M8.00109 6.44553C9.35113 6.44553 10.4455 5.35113 10.4455 4.00109C10.4455 2.65104 9.35113 1.55664 8.00109 1.55664C6.65104 1.55664 5.55664 2.65104 5.55664 4.00109C5.55664 5.35113 6.65104 6.44553 8.00109 6.44553Z"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M12.6675 9.11133L10.4453 11.3336L12.6675 13.5558"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M9.19259 8.81596C8.80707 8.72938 8.41249 8.66797 8.00031 8.66797C5.73276 8.66797 3.78787 10.028 2.92565 11.9746C2.6012 12.708 3.00298 13.5514 3.76742 13.7923C4.85631 14.1354 6.29711 14.4449 8.00031 14.4449C8.59578 14.4449 9.1445 14.3965 9.67072 14.3314"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M10.4453 11.334H14.8898"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ );
+}
diff --git a/packages/utils/src/constants/main.ts b/packages/utils/src/constants/main.ts
index 5d82a13f69..e36c4f8318 100644
--- a/packages/utils/src/constants/main.ts
+++ b/packages/utils/src/constants/main.ts
@@ -79,3 +79,12 @@ export const LEGAL_WORKSPACE_ID = "clrflia0j0000vs7sqfhz9c7q";
export const LEGAL_USER_ID = "clqei1lgc0000vsnzi01pbf47";
export const R2_URL = process.env.STORAGE_BASE_URL || "https://dubassets.com";
+
+// Network program (TODO: Update this)
+export const NETWORK_WORKSPACE_ID = "ws_1KRHGNRSY2YZQZD96H5S85VX6";
+export const NETWORK_PROGRAM_ID = "prog_1KRHH2Y9XZJTJDSCD7B5NXECG";
+export const NETWORK_PROGRAM_SLUG = "network";
+export const NETWORK_PROGRAM_DEFAULT_GROUP_ID = "grp_1KRHH2YV0GH8AN57T1S9W9CBE";
+export const NETWORK_PROGRAM_DEFAULT_SALE_REWARD_ID =
+ "rw_1KRHH2YVWP5TVHC30CZE5JVK7";
+export const NETWORK_USER_ID = "cl7p1s07k000687rbuhpwqkqa";